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
<file_sep>package com.prisbox.zzp.base.controller; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class BaseController { static Logger logger = Logger.getLogger(BaseController.class); @RequestMapping(value="test") public String test(){ logger.debug("debug"); logger.info("info"); logger.warn("warn"); logger.error("error"); return "welcome"; } }
380b84664c8f86329dc77cf273e0b1dae6906eba
[ "Java" ]
1
Java
wynzn2009/zop
2c5a2b3973f09aa35744059374e16ee284c5c88f
862e5c9a19eddf4bc1dd50171bbcbb650e85bf76
refs/heads/master
<repo_name>yunusyerli1/customer<file_sep>/src/redux/reducers/customerReducers.js import { FETCH_CUSTOMERS, DELETE_CUSTOMER, UPDATE_CUSTOMER, CREATE_CUSTOMER } from "../types"; export const customerReducer = (state={}, action) => { switch(action.type) { case FETCH_CUSTOMERS: return {customers: action.payload}; case CREATE_CUSTOMER: return {customers: [...state.customers, action.payload]}; case DELETE_CUSTOMER: return {customers: state.customers.filter(x => x.id !== action.payload)}; case UPDATE_CUSTOMER: return {customers: [...state.customers.filter(x => x.id !== action.payload.id), action.payload]}; default: return state; } }<file_sep>/src/App.js import React from 'react'; import {BrowserRouter, Route} from 'react-router-dom'; import CustomerList from './screens/CustomerList'; import CustomerDetails from './screens/CustomerDetails'; class App extends React.Component { render(){ return ( <BrowserRouter> <div> <Route path="/details/:id" component={CustomerDetails}/> <Route path="/" component={CustomerList} exact/> </div> </BrowserRouter> ); } } export default App; <file_sep>/src/util.js export default function circleName(name) { let firstLetter=name[0]; let indexOfLastLetter=name.indexOf(" "); let lastLetter = name[indexOfLastLetter+1]; return firstLetter + lastLetter; }<file_sep>/src/components/SideBarAbout.js import React from 'react' const SideBarAbout = (props) => { const {customer} = props; return ( <div> SideBarAbout </div> ) } export default SideBarAbout;<file_sep>/src/screens/CustomerDetails.js import React, { Component } from 'react'; import SideBarProfile from '../components/SideBarProfile'; import SideBarMap from '../components/SideBarMap'; import SideBarAbout from '../components/SideBarAbout'; class CustomerDetails extends Component { state={customer:{}} componentDidMount = () => { const customer=this.props.location.state.customer[0]; this.setState({customer:customer}) } render() { console.log(this.state.customer); return ( <div className="content-details"> <div className="sidebar-details"> <SideBarProfile customer={this.state.customer} /> <SideBarMap /> <SideBarAbout /> </div> <div className="main-details"> szf </div> </div> ) }} export default CustomerDetails;<file_sep>/src/components/List.js import React from 'react'; import circleName from '../util'; import {Link} from 'react-router-dom'; const List = ({customers}) => { return ( !customers ? <div>Loading...</div> :( <div className="list"> <table id="customers"> <thead> <tr> <th className="hiddenBorder" > </th> <th>Customer Name</th> <th>Type</th> <th>Related Firm</th> <th>Address</th> <th>GSM</th> <th>Email</th> <th>Portal Information</th> </tr> </thead> <tbody> {customers.map((customer) => ( <tr key={customer.id}> <td><span className="round" >{circleName(customer.name)}</span></td> <Link to={{ pathname:`/details/${customer.id}`, state: {customer:customers.filter(x => x.id ===customer.id)} }} className="table-link"><td key={customer}>{customer.name}</td></Link> <td>{customer.customerType}</td> <td>{customer.relatedFirm}</td> <td>{customer.address}</td> <td>{customer.phone}</td> <td>{customer.email}</td> <td>{customer.note}</td> </tr> ))} </tbody> </table> </div>) ) } export default List;<file_sep>/src/components/SideBarMap.js import React from 'react' const SideBarMap = () => { return ( <div> SideBarMap </div> ) } export default SideBarMap;<file_sep>/src/screens/CustomerList.js import React, { Component } from 'react'; import List from '../components/List'; import SideBar from '../components/SideBar'; import { fetchCustomers } from '../redux/actions/customerActions'; import {connect} from 'react-redux'; class CustomerList extends Component { componentDidMount() { this.props.fetchCustomers(); } render() { const {customers} = this.props.customers; return ( <div className="content"> <div className="main"> <List customers={customers}/> </div> <div className="sidebar"> <SideBar/> </div> </div> ) } } const mapStateToProps = state => { return { customers: state.list }; } export default connect(mapStateToProps,{fetchCustomers})(CustomerList);<file_sep>/src/redux/types.js export const FETCH_CUSTOMERS = "FETCH_CUSTOMERS"; export const DELETE_CUSTOMER = "DELETE_CUSTOMER"; export const UPDATE_CUSTOMER = "UPDATE_CUSTOMER"; export const CREATE_CUSTOMER = "CREATE_CUSTOMER";
f39942b917bfeb724ed0dfbc6d18c98dc7d44c9a
[ "JavaScript" ]
9
JavaScript
yunusyerli1/customer
4b2733bf2c10d79be486fad850b8570b2c765fe9
e72cf8240547a8c5dc41dd4a4d0c26db77e3db27
refs/heads/master
<repo_name>dougdworkin/jQuery_streetfighter<file_sep>/js/app.js $(document).ready(function(){ // Control starting and pausing music $('.playTheme').click(function () { $('#theme').trigger('play'); }); $('.pauseTheme').click(function () { $('#theme').trigger('pause'); }); // **** Opening title animations ******* // Delay and show title $('#streetFighter') .delay(300).fadeIn(2000) .delay(200).fadeOut(900); // ... then delay & show intro part I $('#introText01') .delay(3400).fadeIn(2000) .delay(2000).fadeOut(900); // ... then delay & show intro part II $('#introText02') .delay(5400).fadeIn(1000) .delay(1000).fadeOut(900); // ... then delay & show instructions $('#instructions') .delay(8300).fadeIn(1000); // **** End ppening title animations ******* // cool position & play music when x pressed $(document).keydown(function(e) { if (e.which == 88) { // 88 = "x" key $('.ryuStill').hide(); $('.ryuReady').hide(); $('.ryuCool').show(); $('#beinCool').trigger('play'); } }) // cool to still position & stop music when x depressed .keyup(function(e) { if (e.which == 88) { $('.ryuCool').hide(); $('.ryuStill').show(); $('#beinCool').trigger('pause'); } }); // Show Ryu in ready position on mouseover $('#Ryu').mouseenter(function() { $('.ryuStill').hide(); $('.ryuReady').show(); }) // put Ryu back into still position when mouse leaves .mouseleave(function() { $('.ryuReady').hide(); $('.ryuStill').show(); }) // Ryu goes into stance and fires hadouken w/sound on downclick .mousedown(function() { //play hadouken sound playHadouken(); //show and hide positions $('.ryuReady').hide(); $('.ryuStill').hide(); $('.ryuThrowing').show(); //show and animate hadouken across the screen $('.hadouken').finish().show().animate ( {'left':'1020px'}, 500, function() { $(this).hide(); $(this).css('left', '529px'); } ); }) // RYU goes back to ready position on upclick .mouseup(function() { $('.ryuThrowing').hide(); $('.ryuStill').show(); }); }); //function to set volume and play hadouken sound function playHadouken () { $('#hadouken-sound')[0].volume = 0.5; $('#hadouken-sound')[0].load(); $('#hadouken-sound')[0].play(); }
0d8073a9eea0b2e113dfca00dc8341755422ea3d
[ "JavaScript" ]
1
JavaScript
dougdworkin/jQuery_streetfighter
32aea1b2ada0b19fad27fa6b4b138af6a583198c
b1bd7d7b8ab8bca3559c5636b0f5896727d01fb4
refs/heads/master
<repo_name>anbrandt/Angular-MultiView<file_sep>/src/app/second.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-second', template: '<p> Second Component </p> <img src="http://www.clker.com/cliparts/y/G/s/h/j/O/two-md.png">', }) export class SecondComponent { } <file_sep>/src/app/third.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-third', template: '<p> Third Component </p> <img src = "http://www.clker.com/cliparts/Z/9/b/Z/K/I/number-three-md.png">', }) export class ThirdComponent { } <file_sep>/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { AppComponent } from './app.component'; import { FirstComponent } from './first.component'; import { SecondComponent } from './second.component'; import { ThirdComponent } from './third.component'; import { RandomService } from './random.service'; @NgModule({ declarations: [ AppComponent, FirstComponent, SecondComponent, ThirdComponent ], imports: [ BrowserModule, RouterModule.forRoot([ { //path is an address to certain component -> localhost:4200/second path: "third", component: ThirdComponent }, { path: "second", component: SecondComponent }, { path: "", pathMatch: "full", component: FirstComponent } ]) ], providers: [RandomService], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>/src/app/random.service.ts import { Injectable } from '@angular/core'; @Injectable() export class RandomService { getRandom(start: number, stop: number) { let num = Math.floor(Math.random() * (stop - start)) + start; return Promise.resolve(num); } }<file_sep>/src/app/first.component.ts import { Component, OnInit } from '@angular/core'; import {RouterModule, Router } from '@angular/router'; import { RandomService } from './random.service'; @Component({ selector: 'app-first', template: '<div><p> First Component Something </p> <img src = " https://www.drupal.org/files/project-images/edit%2827117%29.png"> <button (click) ="goToSecond()">Go to Second</button></div>', }) export class FirstComponent implements OnInit { num: number = 0; constructor(public randomService: RandomService, private router: Router) { } ngOnInit() { this.randomService.getRandom(1,100).then((num)=> { this.num = num; }); } goToSecond() { this.router.navigate(['/second']); } }
9c7811716cdb615e2743699cd65105e8b889a4eb
[ "TypeScript" ]
5
TypeScript
anbrandt/Angular-MultiView
e2976c1c946cb11000d5cfe9bf662d67542a28cb
fa4e3467695ceaba77c15ab1981c6d4bfe19765a
refs/heads/master
<repo_name>sundropgold/sequelizedBurger<file_sep>/db/seeds.sql INSERT INTO burgers(burger_name) VALUES ("Big Meaty Burger"); INSERT INTO burgers(burger_name) VALUES ("Krabby Patty Burger"); INSERT INTO burgers(burger_name) VALUES ("Pretty Patty Burger"); INSERT INTO burgers(burger_name) VALUES ("The Chick Filleter");<file_sep>/db/jaws.sql CREATE TABLE burgers ( id INTEGER(11) AUTO_INCREMENT NOT NULL, burger_name VARCHAR(200) NOT NULL, devoured BOOLEAN DEFAULT false NOT NULL, date TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, PRIMARY KEY (id) ); INSERT INTO burgers(burger_name) VALUES ("Big Meaty Burger"); INSERT INTO burgers(burger_name) VALUES ("<NAME>"); INSERT INTO burgers(burger_name) VALUES ("Pretty Patty Burger"); INSERT INTO burgers(burger_name) VALUES ("The <NAME>");<file_sep>/controllers/burgers_controller.js // Dependencies ----------------------------------------------------- var db = require("../models"); // Node Dependencies var express = require('express'); var router = express.Router(); // Extracts the sequelize connection from the models object var sequelizeConnection = db.sequelize; // Sync the tables sequelizeConnection.sync(({force:true})); // Router ----------------------------------------------------- // create routes that will connect the model and view // route that gets/shows all the burgers router.get("/", function(req,res){ db.Burgers.findAll({}).then(function(dbBurger){ var burgerObject = { burgers: dbBurger }; res.render("index", burgerObject); }); }); // route to post/add a burger router.post("/", function(req,res){ db.Burgers.create({ burger_name:req.body.burger }).then(function(dbBurger){ res.redirect("/"); }); }); // route to devour a burger by updating its devoured category to true router.put("/:id", function(req,res){ db.Burgers.update({ devoured:true },{ where:{ id:req.params.id } }).then(function(dbBurger){ res.redirect("/"); }); }); module.exports = router; <file_sep>/README.md # Burger Bonanza! ## A Burger Eating App ### Summary Burger Bonanza is a burger creating and devouring app! Whenever the user adds a burger, the burger will appear in the left-side column. Once eaten, the burger will appear in the right-side column. All burgers are stored in a database, whether devoured or not. Your turn! Add a burger, eat the burger. ### Features * MySQL Database * JawsDB * Node.js * Express * Handlebars * Homemade ORM * Heroku Deployment ### Demo https://burgerbonanza.herokuapp.com/
9814130d3feb169f756c73be6b48db60cf171015
[ "JavaScript", "SQL", "Markdown" ]
4
SQL
sundropgold/sequelizedBurger
500638af8b8c47ea3f9637ee3446fd13c4fb5f80
ada2f276d52fbd7a6168e2b1ae75fd8e6337a187
refs/heads/master
<repo_name>GiorgiSheklashvili/Authcoin-truffle<file_sep>/test/TestRevokeEntityIdentityRecord.js const util = require('ethereumjs-util'); var AuthCoin = artifacts.require("AuthCoin"); var ECSignatureVerifier = artifacts.require("signatures/ECSignatureVerifier"); var RsaSignatureVerifier = artifacts.require("signatures/RsaSignatureVerifier"); var EntityIdentityRecord = artifacts.require("EntityIdentityRecord"); contract('Authcoin & EntityIdentityRecord', function (accounts) { let authCoin // EIR values let identifiers = [web3.fromAscii("<EMAIL>"), web3.fromAscii("<NAME>")] let contentRsaPubKey = web3.toHex("<KEY>") let contentEcPubKey = web3.toHex("0x192e545a9025d55e6088c55c7755ab3633e3e589") let idRsa = web3.sha3(contentRsaPubKey, {encoding: 'hex'}) let idEc = web3.sha3(contentEcPubKey, {encoding: 'hex'}) let contentTypeRsa = util.bufferToHex(util.setLengthRight("rsa", 32)) let contentTypeEc = util.bufferToHex(util.setLengthRight("ec", 32)) let hashRsa = web3.toHex("0x5874f34935bfeea6079953d667b89f971f0127bdaf4bffc69d197c050a8b849e") let hashEc = web3.toHex("0x3365d64d81008b4f4b4399a7b05864c0dbb6a47ac82c34146f6847159a98d726") let rsaEirSignature = web3.toHex("0x01eef652c011db5bdf671a13742a38584295e3aae19e453eb187cbc15cbc0f09f70230d76126033fd5b025884851c3a96a9b9851abbe0e1eb91533caff528e16", 128) let ecEirSignature = web3.toHex("0x24f59e7d653d5f1e9f12fe4ee04f2720b708bb99f3e441b1661ea45951b2060368eaf1f19c3d18e067e332f8f8408d651f7257e5bf7f1a6f6e4a5ef5e225587101", 128) before("setup contract for all tests", async function () { authCoin = await AuthCoin.new(accounts[0]) let ecSignatureVerifier = await ECSignatureVerifier.new(accounts[0]) let rsaSignatureVerifier = await RsaSignatureVerifier.new(accounts[0]) await authCoin.registerSignatureVerifier(ecSignatureVerifier.address, contentTypeEc) await authCoin.registerSignatureVerifier(rsaSignatureVerifier.address, contentTypeRsa) await authCoin.registerEir(contentRsaPubKey, contentTypeRsa, identifiers, hashRsa, rsaEirSignature) await authCoin.registerEir(contentEcPubKey, contentTypeEc, identifiers, hashEc, ecEirSignature) }) it("should not revoke EIR with RSA content type and invalid revocation signature", async function () { let directKeyRevocationSignature = web3.toHex("0x216c3a4651486<KEY>00000000000000", 128) await authCoin.revokeEir(idRsa, directKeyRevocationSignature); let eir = EntityIdentityRecord.at(await authCoin.getEir(idRsa)) assert.isFalse(await eir.isRevoked()) }) it("should not revoke EIR with EC content type and invalid revocation signature", async function () { let directKeyRevocationSignature = web3.toHex("<KEY>", 128) await authCoin.revokeEir(idEc, directKeyRevocationSignature); let eir = EntityIdentityRecord.at(await authCoin.getEir(idEc)) assert.isFalse(await eir.isRevoked()) }) it("should revoke EIR with RSA content type and valid revocation signature", async function () { let directKeyRevocationSignature = web3.toHex("0x43c476c6ba4b3ea090bfaece16dac0036df89731828485674ee4a6deae672101b1862694093482e3155347c74d23dd94939b913ce75d7bff3719634935b30faa", 128) await authCoin.revokeEir(idRsa, directKeyRevocationSignature); let eir = EntityIdentityRecord.at(await authCoin.getEir(idRsa)) assert.isTrue(await eir.isRevoked()) }) it("should revoke EIR with EC content type and valid revocation signature", async function () { let directKeyRevocationSignature = web3.toHex("<KEY>", 128) await authCoin.revokeEir(idEc, directKeyRevocationSignature); let eir = EntityIdentityRecord.at(await authCoin.getEir(idEc)) assert.isTrue(await eir.isRevoked()) }) }) <file_sep>/test/TestChallengeRecordSignatureVerification.js const util = require('ethereumjs-util'); var AuthCoin = artifacts.require("AuthCoin"); var ECSignatureVerifier = artifacts.require("signatures/ECSignatureVerifier"); var EntityIdentityRecord = artifacts.require("EntityIdentityRecord"); contract('AuthCoin & ChallengeRecord', function (accounts) { let authCoin let eir1 let eir2 let verifierEirId let targetEirId // EIR values let identifiers = [web3.fromAscii("<EMAIL>"), web3.fromAscii("<NAME>")] let contentType = util.bufferToHex(util.setLengthRight("ec", 32)) let eirContent1 = web3.toHex("0x192e545a9025d55e6088c55c7755ab3633e3e589") let eirContent2 = web3.toHex("0x81970d1d41c548cc4b83c7cb5d7d7e6aecdcb1f5") let eirId1 = web3.sha3(eirContent1, {encoding: 'hex'}) let eirId2 = web3.sha3(eirContent2, {encoding: 'hex'}) let eirHash1 = web3.toHex("0x3365d64d81008b4f4b4399a7b05864c0dbb6a47ac82c34146f6847159a98d726") let eirHash2 = web3.toHex("0xeb5ed83a92d2c0e8651b2e56c3bce04475c2db646d96439cc13d9ed8f69cba8b") let eirSignature1 = web3.toHex("0x24f59e7d653d5f1e9f12fe4ee04f2720b708bb99f3e441b1661ea45951b2060368eaf1f19c3d18e067e332f8f8408d651f7257e5bf7f1a6f6e4a5ef5e225587101", 128) let eirSignature2 = web3.toHex("0xcc63444aeeaf217fe8323e55d176577994cfc6324f13703cfca525c9960f163f3217520597a54977c73cd3e76c9b3e3165ac5f7c0870d37ae1ddcc7627b0029801", 128) // CR values let challengeId = web3.fromAscii("challenge1") let vaeId = util.bufferToHex(util.setLengthRight("vae1", 32)) let challengeType = web3.fromAscii("signing challenge") let challenge = web3.fromAscii("sign value 'HELLO'", 128) let challengeHash = web3.toHex("0x0e4302d84aabc8a965883a5a97dfa6ba95c8970bfa64bfccc2369495bc5e14bc") let challengeSignature = web3.toHex("0x385fb6c60d61d78873c9f2817660b5d7d5f363a18fa18a15f0a6618104666f6a4550bd267755c362222848b383a109ff33c36dfa3eab98d696f8af3a23d6e47200", 128) beforeEach('setup contract for test', async function () { authCoin = await AuthCoin.new(accounts[0]) let ecSignatureVerifier = await ECSignatureVerifier.new(accounts[0]) await authCoin.registerSignatureVerifier(ecSignatureVerifier.address, contentType) await authCoin.registerEir(eirContent1, contentType, identifiers, eirHash1, eirSignature1) await authCoin.registerEir(eirContent2, contentType, identifiers, eirHash2, eirSignature2) eir1 = EntityIdentityRecord.at(await authCoin.getEir(eirId1)) eir2 = EntityIdentityRecord.at(await authCoin.getEir(eirId2)) verifierEirId = await eir1.getId() targetEirId = await eir2.getId() }) it("should add ChallengeRecord with valid hash and signature by verifier EIR", async function () { let success = false try { await authCoin.registerChallengeRecord(challengeId, vaeId, challengeType, challenge, verifierEirId, targetEirId, challengeHash, challengeSignature) success = true } catch (error) {} assert.isOk(success) }) it("should not add ChallengeRecord with valid hash and valid signature by target EIR", async function () { let success = false try { await authCoin.registerChallengeRecord(challengeId, vaeId, challengeType, challenge, targetEirId, verifierEirId, challengeHash, challengeSignature) success = true } catch (error) {} assert.isNotOk(success) }) it("should not add ChallengeRecord with invalid hash and valid signature", async function () { let success = false try { await authCoin.registerChallengeRecord(challengeId, vaeId, challengeType, challenge, verifierEirId, targetEirId, web3.toHex("0x0"), challengeSignature) success = true } catch (error) {} assert.isNotOk(success) }) it("should not add ChallengeRecord with valid hash and invalid signature", async function () { let success = false try { await authCoin.registerChallengeRecord(challengeId, vaeId, challengeType, challenge, verifierEirId, targetEirId, challengeHash, web3.toHex("0x0")) success = true } catch (error) {} assert.isNotOk(success) }) }) <file_sep>/test/TestValidationAuthenticationEntry.js const util = require('ethereumjs-util'); var ValidationAuthenticationEntry = artifacts.require("ValidationAuthenticationEntry"); var EntityIdentityRecord = artifacts.require("EntityIdentityRecord"); var DummyVerifier = artifacts.require("signatures/DummyVerifier"); contract('ValidationAuthenticationEntry', function (accounts) { let vaeId = util.bufferToHex(util.setLengthRight("vae1", 32)) let vaeId2 = util.bufferToHex(util.setLengthRight("vae2", 32)) let eir1 let eir2 // CR values let challengeId = web3.fromAscii("challenge1") let challengeId2 = web3.fromAscii("challenge2") let challengeId3 = web3.fromAscii("challenge3") let challengeType = web3.fromAscii("signing challenge") let challenge = web3.fromAscii("sign value 'HELLO'", 128) let hash = web3.fromAscii("hash", 32) let signature = web3.fromAscii("signature", 128) // RR values let responseContent = web3.fromAscii("challengeresponse", 128) let responseHash = web3.toHex("0xba8077882ce7b9fe1c17c07cdd822e6e77d0ce5bdc46a2bbe1dc8646d37c2c3d") let responseHash1 = web3.toHex("0x10447f9447dd21a763b10a344a06b790b171125aed7179f72940c5b68321e5f9") let responseHashUnknown = web3.toHex("0x33ab355bca41fb09d659746cb4a1034aeb69538d05f4dcb2608f8117993f25cf") // SR values let signatureRecordHash1 = web3.toHex("0xb57c81638d82f7746528c56ba6120c4522a50455588bef00d499f58dc7ed5adf") let signatureRecordHash2 = web3.toHex("0x12b4205ffb323e835f5e6df19ad05c425ddad327cd207008f43d6ca2f982e54d") let signatureRecordHashUnknown = web3.toHex("0x6ba7448662dbe4911f6ec0167624264cd7d32b2e5e69d616595b2625d56d3d26") //EIR values let identifiers = [web3.fromAscii("<EMAIL>", 32), web3.fromAscii("<NAME>", 32)] let content = web3.fromAscii("content") let content2 = web3.fromAscii("content2") let eirType = util.bufferToHex(util.setLengthRight("dummy", 32)) beforeEach('setup contract for each test', async function () { let dummyVerifier = await DummyVerifier.new(accounts[0]) eir1 = await EntityIdentityRecord.new(identifiers, content, eirType, hash, signature, dummyVerifier.address, accounts[0]) eir2 = await EntityIdentityRecord.new(identifiers, content2, eirType, hash, signature, dummyVerifier.address, accounts[0]) }) it("creation must be successful and properly initialized", async function () { let vae = await ValidationAuthenticationEntry.new(vaeId, accounts[1]) assert.equal(await vae.getVaeId(), vaeId); assert.equal(await vae.getOwner(), accounts[1]); assert.equal(await vae.getChallengeCount(), 0); }) it("should accept new challenge records", async function () { let vae = await ValidationAuthenticationEntry.new(vaeId, accounts[1]) await vae.addChallengeRecord(challengeId, vaeId, challengeType, challenge, eir1.address, eir2.address, hash, signature, accounts[0]) await vae.addChallengeRecord(challengeId2, vaeId, challengeType, challenge, eir2.address, eir1.address, hash, signature, accounts[0]) assert.equal(await vae.getVaeId(), vaeId); assert.equal(await vae.getOwner(), accounts[1]); assert.equal(await vae.getChallengeCount(), 2); }) it("should fail if same challenge record is added multiple times", async function () { let vae = await ValidationAuthenticationEntry.new(vaeId, accounts[1]) await vae.addChallengeRecord(challengeId, vaeId, challengeType, challenge, eir1.address, eir2.address, hash, signature, accounts[0]) let success = false try { await vae.addChallengeRecord(challengeId, vaeId, challengeType, challenge, eir1.address, eir2.address, hash, signature, accounts[0]) success = true } catch (error) {} assert.isNotOk(success) assert.equal(await vae.getChallengeCount(), 1); }) it("should fail if challenge request VAE is different", async function () { let vae = await ValidationAuthenticationEntry.new(vaeId, accounts[1]) await vae.addChallengeRecord(challengeId, vaeId, challengeType, challenge, eir1.address, eir2.address, hash, signature, accounts[0]) let success = false try { await vae.addChallengeRecord(challengeId, vaeId2, challengeType, challenge, eir1.address, eir2.address, hash, signature, accounts[0]) success = true } catch (error) {} assert.isNotOk(success) }) it("should fail if participants are different", async function () { let vae = await ValidationAuthenticationEntry.new(vaeId, accounts[1]) await vae.addChallengeRecord(challengeId, vaeId, challengeType, challenge, eir1.address, eir2.address, hash, signature, accounts[0]) let success = false try { await vae.addChallengeRecord(challengeId2, vaeId, challengeType, challenge, accounts[1], eir1.address, hash, signature, accounts[0]) success = true } catch (error) {} assert.isNotOk(success) }) it("should fail if participants are different 2", async function () { let vae = await ValidationAuthenticationEntry.new(vaeId, accounts[1]) await vae.addChallengeRecord(challengeId, vaeId, challengeType, challenge, eir1.address, eir2.address, hash, signature, accounts[0]) let success = false try { await vae.addChallengeRecord(challengeId2, vaeId, challengeType, challenge, eir2.address, accounts[0], hash, signature, accounts[0]) success = true } catch (error) {} assert.isNotOk(success) }) it("should fail if more than 2 challenge records are added", async function () { let vae = await ValidationAuthenticationEntry.new(vaeId, accounts[1]) await vae.addChallengeRecord(challengeId, vaeId, challengeType, challenge, eir1.address, eir2.address, hash, signature, accounts[0]) await vae.addChallengeRecord(challengeId2, vaeId, challengeType, challenge, eir2.address, eir1.address, hash, signature, accounts[0]) let success = false try { await vae.addChallengeRecord(challengeId3, vaeId, challengeType, challenge, eir1.address, eir2.address, hash, signature, accounts[0]) success = true } catch (error) {} assert.isNotOk(success) }) it("must accept new challenge response records", async function () { let vae = await ValidationAuthenticationEntry.new(vaeId, accounts[1]) await vae.addChallengeRecord(challengeId, vaeId, challengeType, challenge, eir1.address, eir2.address, hash, signature, accounts[0]) await vae.addChallengeRecord(challengeId2, vaeId, challengeType, challenge, eir2.address, eir1.address, hash, signature, accounts[0]) await vae.addChallengeResponseRecord(vaeId, challengeId, responseContent, responseHash, signature, accounts[0]) assert.equal(await vae.getVaeId(), vaeId); assert.equal(await vae.getOwner(), accounts[1]); assert.equal(await vae.getChallengeCount(), 2); assert.equal(await vae.getChallengeResponseCount(), 1); }) it("should fail if challenge records aren't added before response records", async function () { let vae = await ValidationAuthenticationEntry.new(vaeId, accounts[1]) let success = false try { await vae.addChallengeResponseRecord(vaeId, challengeId, responseContent, responseHash, signature, accounts[0]) success = true } catch (error) {} assert.isNotOk(success) }) it("should fail if challenge response record VAE id is invalid", async function () { let vae = await ValidationAuthenticationEntry.new(vaeId, accounts[1]) await vae.addChallengeRecord(challengeId, vaeId, challengeType, challenge, eir1.address, eir2.address, hash, signature, accounts[0]) await vae.addChallengeRecord(challengeId2, vaeId, challengeType, challenge, eir2.address, eir1.address, hash, signature, accounts[0]) let success = false try { await vae.addChallengeResponseRecord(web3.fromAscii("unknown"), challengeId, responseContent, responseHashUnknown, signature, accounts[0]) success = true } catch (error) {} assert.isNotOk(success) }) it("should fail if challenge response record challenge id is unknown", async function () { let vae = await ValidationAuthenticationEntry.new(vaeId, accounts[1]) await vae.addChallengeRecord(challengeId, vaeId, challengeType, challenge, eir1.address, eir2.address, hash, signature, accounts[0]) await vae.addChallengeRecord(challengeId2, vaeId, challengeType, challenge, eir2.address, eir1.address, hash, signature, accounts[0]) let success = false try { await vae.addChallengeResponseRecord(vaeId, web3.fromAscii("unknown"), responseContent, responseHashUnknown, signature, accounts[0]) success = true } catch (error) {} assert.isNotOk(success) }) it("should fail if challenge response record is added multiple times", async function () { let vae = await ValidationAuthenticationEntry.new(vaeId, accounts[1]) await vae.addChallengeRecord(challengeId, vaeId, challengeType, challenge, eir1.address, eir2.address, hash, signature, accounts[0]) await vae.addChallengeRecord(challengeId2, vaeId, challengeType, challenge, eir2.address, eir1.address, hash, signature, accounts[0]) await vae.addChallengeResponseRecord(vaeId, challengeId, responseContent, responseHash, signature, accounts[0]) let success = false try { await vae.addChallengeResponseRecord(vaeId, challengeId, responseContent, responseHash, signature, accounts[0]) success = true } catch (error) {} assert.isNotOk(success) }) it("must accept new challenge signature records", async function () { let vae = await ValidationAuthenticationEntry.new(vaeId, accounts[1]) await vae.addChallengeRecord(challengeId, vaeId, challengeType, challenge, eir1.address, eir2.address, hash, signature, accounts[0]) await vae.addChallengeRecord(challengeId2, vaeId, challengeType, challenge, eir2.address, eir1.address, hash, signature, accounts[0]) await vae.addChallengeResponseRecord(vaeId, challengeId, responseContent, responseHash, signature, accounts[0]) await vae.addChallengeResponseRecord(vaeId, challengeId2, responseContent, responseHash1, signature, accounts[0]) await vae.addChallengeSignatureRecord(vaeId,challengeId2, 100000, true, signatureRecordHash2, signature, accounts[0]) await vae.addChallengeSignatureRecord(vaeId,challengeId, 100000, true, signatureRecordHash1, signature, accounts[0]) assert.equal(await vae.getVaeId(), vaeId); assert.equal(await vae.getOwner(), accounts[1]); assert.equal(await vae.getChallengeCount(), 2); assert.equal(await vae.getChallengeResponseCount(), 2); assert.equal(await vae.getChallengeSignatureCount(), 2); }) it("adding signature record should fail if VAE doesn't contain challenge records", async function () { let vae = await ValidationAuthenticationEntry.new(vaeId, accounts[1]) let success = false try { await vae.addChallengeSignatureRecord(vaeId,challengeId2, 100000, true, hash, signature, accounts[0]) success = true } catch (error) { } assert.isNotOk(success) }) it("adding signature record should fail if VAE doesn't contain challenge response records", async function () { let vae = await ValidationAuthenticationEntry.new(vaeId, accounts[1]) await vae.addChallengeRecord(challengeId, vaeId, challengeType, challenge, eir1.address, eir2.address, hash, signature, accounts[0]) await vae.addChallengeRecord(challengeId2, vaeId, challengeType, challenge, eir2.address, eir1.address, hash, signature, accounts[0]) let success = false try { await vae.addChallengeSignatureRecord(vaeId,challengeId2, 100000, true, hash, signature, accounts[0]) success = true } catch (error) { } assert.isNotOk(success) }) it("should fail if more than 2 signature records are added", async function () { let vae = await ValidationAuthenticationEntry.new(vaeId, accounts[1]) await vae.addChallengeRecord(challengeId, vaeId, challengeType, challenge, eir1.address, eir2.address, hash, signature, accounts[0]) await vae.addChallengeRecord(challengeId2, vaeId, challengeType, challenge, eir2.address, eir1.address, hash, signature, accounts[0]) await vae.addChallengeResponseRecord(vaeId, challengeId, responseContent, responseHash, signature, accounts[0]) await vae.addChallengeResponseRecord(vaeId, challengeId2, responseContent, responseHash1, signature, accounts[0]) await vae.addChallengeSignatureRecord(vaeId,challengeId2, 100000, true, signatureRecordHash2, signature, accounts[0]) await vae.addChallengeSignatureRecord(vaeId,challengeId, 100000, true, signatureRecordHash1, signature, accounts[0]) let success = false try { await vae.addChallengeSignatureRecord(vaeId,challengeId, 100000, true, signatureRecordHash1, signature, accounts[0]) success = true } catch (error) { } assert.isNotOk(success) }) it("signature record can not be overwritten", async function () { let vae = await ValidationAuthenticationEntry.new(vaeId, accounts[1]) await vae.addChallengeRecord(challengeId, vaeId, challengeType, challenge, eir1.address, eir2.address, hash, signature, accounts[0]) await vae.addChallengeRecord(challengeId2, vaeId, challengeType, challenge, eir2.address, eir1.address, hash, signature, accounts[0]) await vae.addChallengeResponseRecord(vaeId, challengeId, responseContent, responseHash, signature, accounts[0]) await vae.addChallengeResponseRecord(vaeId, challengeId2, responseContent, responseHash1, signature, accounts[0]) await vae.addChallengeSignatureRecord(vaeId,challengeId2, 100000, true, signatureRecordHash2, signature, accounts[0]) let success = false try { await vae.addChallengeSignatureRecord(vaeId,challengeId2, 100000, true, signatureRecordHash2, signature, accounts[0]) success = true } catch (error) { } assert.isNotOk(success) }) it("signature record can not be added without corresponding challenge record", async function () { let vae = await ValidationAuthenticationEntry.new(vaeId, accounts[1]) await vae.addChallengeRecord(challengeId, vaeId, challengeType, challenge, eir1.address, eir2.address, hash, signature, accounts[0]) await vae.addChallengeRecord(challengeId2, vaeId, challengeType, challenge, eir2.address, eir1.address, hash, signature, accounts[0]) await vae.addChallengeResponseRecord(vaeId, challengeId, responseContent, responseHash, signature, accounts[0]) await vae.addChallengeResponseRecord(vaeId, challengeId2, responseContent, responseHash1, signature, accounts[0]) let success = false try { await vae.addChallengeSignatureRecord(vaeId,web3.fromAscii("unknown"), 100000, true, signatureRecordHashUnknown, signature, accounts[0]) success = true } catch (error) { } assert.isNotOk(success) }) }) <file_sep>/migrations/2_deploy_authcoin.js var AuthCoinContract = artifacts.require("./AuthCoin.sol"); var BytesUtils = artifacts.require("./utils/BytesUtils.sol"); module.exports = function(deployer) { deployer.deploy([BytesUtils]); deployer.link(BytesUtils, AuthCoinContract); deployer.deploy([AuthCoinContract]); }; <file_sep>/test/TestAuthCoin.js const util = require('ethereumjs-util'); var AuthCoin = artifacts.require("AuthCoin"); var DummyVerifier = artifacts.require("signatures/DummyVerifier"); contract('AuthCoin', function (accounts) { let authCoin let eirType = util.bufferToHex(util.setLengthRight("dummy", 32)) beforeEach('setup contract for each test', async function () { authCoin = await AuthCoin.new(accounts[0]) }) it("supports adding new signature verifiers", async function () { let dummyVerifier = await DummyVerifier.new(accounts[0]) await authCoin.registerSignatureVerifier(dummyVerifier.address, eirType) let verifier = await authCoin.getSignatureVerifier(eirType) assert.equal(dummyVerifier.address, verifier) }) it("should override old value if new verifier is added using already registered eir type", async function () { let dummyVerifier = await DummyVerifier.new(accounts[0]) let dummyVerifier2 = await DummyVerifier.new(accounts[1]) let verifiers = await authCoin.getSignatureVerifierTypes() assert.equal(verifiers.length, 1) await authCoin.registerSignatureVerifier(dummyVerifier.address, eirType) await authCoin.registerSignatureVerifier(dummyVerifier2.address, eirType) let verifier = await authCoin.getSignatureVerifier(eirType) assert.equal(dummyVerifier2.address, verifier) verifiers = await authCoin.getSignatureVerifierTypes() assert.equal(verifiers.length, 2) }) it("should return empty value if verifier doesn't exist", async function () { let verifier = await authCoin.getSignatureVerifier(eirType) assert.equal(verifier, '0x0000000000000000000000000000000000000000') }) it("should return all verifier types known to AutCoin contract", async function () { let dummyVerifier = await DummyVerifier.new(accounts[0]) let verifiers = await authCoin.getSignatureVerifierTypes() assert.equal(verifiers.length, 1) await authCoin.registerSignatureVerifier(dummyVerifier.address, eirType) await authCoin.registerSignatureVerifier(dummyVerifier.address, eirType) await authCoin.registerSignatureVerifier(dummyVerifier.address, util.bufferToHex(util.setLengthRight("dummy2", 32))) verifiers = await authCoin.getSignatureVerifierTypes() assert.equal(verifiers.length, 3) }) it("should throw error when verifier isn't added by the owner", async function () { let dummyVerifier = await DummyVerifier.new(accounts[0]) let success = false try { await authCoin.registerSignatureVerifier(dummyVerifier.address, eirType, {from:accounts[1]}) success = true } catch (error) {} assert.isNotOk(success) }) }) <file_sep>/test/TestRegisterChallengeRecord.js const util = require('ethereumjs-util'); var AuthCoin = artifacts.require("AuthCoin"); var DummyVerifier = artifacts.require("signatures/DummyVerifier"); var EntityIdentityRecord = artifacts.require("EntityIdentityRecord"); var ValidationAuthenticationEntry = artifacts.require("ValidationAuthenticationEntry"); contract('AuthCoin & ChallengeRecord', function (accounts) { let authCoin let eir1 let eir2 let verifierEirId let targetEirId // EIR values let identifiers = [web3.fromAscii("<EMAIL>"), web3.fromAscii("<NAME>")] let content = web3.fromAscii("content") let content2 = web3.fromAscii("content2") let id = web3.sha3(content, {encoding: 'hex'}) let id2 = web3.sha3(content2, {encoding: 'hex'}) let contentType = util.bufferToHex(util.setLengthRight("dummy", 32)) let eirHash1 = web3.toHex("0xa1e945cea940a4b22e4d188cb5a5ec5d4dbdb02e07e29976a1230a80c1eccd43") let eirHash2 = web3.toHex("0xbb7f3dd4cf198d5b2c1bcc21987c134098732a200a411d5041d0f4b75c292561") // CR values let challengeId = web3.fromAscii("challenge1") let vaeId = util.bufferToHex(util.setLengthRight("vae1", 32)) let challengeType = web3.fromAscii("signing challenge") let challenge = web3.fromAscii("sign value 'HELLO'", 128) let challengeHash = web3.toHex("0x342f63fcce85352bb0cdacb05dcc17bcab0c0586289dd799678b210623d9f7ce") let signature = web3.fromAscii("signature", 128) beforeEach('setup contract for each test', async function () { authCoin = await AuthCoin.new(accounts[0]) let dummyVerifier = await DummyVerifier.new(accounts[0]) await authCoin.registerSignatureVerifier(dummyVerifier.address, contentType) await authCoin.registerEir(content, contentType, identifiers, eirHash1, signature) await authCoin.registerEir(content2, contentType, identifiers, eirHash2, signature) eir1 = EntityIdentityRecord.at(await authCoin.getEir(id)) eir2 = EntityIdentityRecord.at(await authCoin.getEir(id2)) verifierEirId = await eir1.getId() targetEirId = await eir2.getId() }) it("should fail when challenge records is added using unknown verifier EIR", async function () { let success = false try { await authCoin.registerChallengeRecord(challengeId, vaeId, challengeType, challenge, web3.fromAscii("dummy", 32), targetEirId, challengeHash, signature) success = true } catch (error) {} assert.isNotOk(success) }) it("should fail when challenge records is added using unknown target EIR", async function () { let success = false try { await authCoin.registerChallengeRecord(challengeId, vaeId, challengeType, challenge, verifierEirId, web3.fromAscii("dummy", 32), challengeHash, signature) success = true } catch (error) {} assert.isNotOk(success) }) it("supports adding new challenge record", async function () { var vaeEvents = authCoin.LogNewVae({_from: web3.eth.coinbase}, {fromBlock: 0, toBlock: 'latest'}); await authCoin.registerChallengeRecord(challengeId, vaeId, challengeType, challenge, verifierEirId, targetEirId, challengeHash, signature) assert.equal(await authCoin.getVaeCount(), 1) let vae = ValidationAuthenticationEntry.at(await authCoin.getVae(vaeId)) assert.equal(await vae.getVaeId(), vaeId) assert.equal(await vae.getChallengeCount(), 1) var event = vaeEvents.get() assert.equal(event.length, 1); assert.equal(event[0].args.id, vaeId) }) it("querying VAE array by EIR id", async function () { var vaeEvents = authCoin.LogNewVae({_from: web3.eth.coinbase}, {fromBlock: 0, toBlock: 'latest'}); await authCoin.registerChallengeRecord(challengeId, vaeId, challengeType, challenge, verifierEirId, targetEirId, challengeHash, signature) assert.equal(await authCoin.getVaeCount(), 1) let vaeArray = await authCoin.getVaeArrayByEirId(verifierEirId); assert.equal(vaeArray.length, 1) let vaeArray2 = await authCoin.getVaeArrayByEirId(targetEirId); assert.equal(vaeArray2.length, 1) assert.equal(vaeArray[0], vaeArray2[0]) var event = vaeEvents.get() assert.equal(event[0].args.vaeAddress, vaeArray[0]) }) it("querying VAE array by EIR that doesn't have any challenges return empty array", async function () { let vaeArray = await authCoin.getVaeArrayByEirId(verifierEirId); assert.equal(vaeArray.length, 0) }) }) <file_sep>/README.md # Introduction # Authcoin is an alternative approach to the commonly used public key infrastructures such as central authorities and the PGP web of trust. It combines a challenge response-based validation and authentication process for domains, certificates, email accounts and public keys with the advantages of a block chain-based storage system. Due to its transparent nature and public availability, it is possible to track the whole validation and authentication process history of each entity in the Authcoin system which makes it much more difficult to introduce sybil nodes and prevent such nodes from getting detected by genuine users. This repository contains Solidity smart contracts for Authcoin protocol. Current implementation contains the following functionality: * [Posting an entity identity record (EIR) to the blockchain](#eir_post) * [Querying EIR by id](#eir_post) * [Revoking EIR](#eir_revoke) * [Customized EIR format](#eir_custom) * [Posting a challenge record (CR) to the blockchain](#cr_post) * [Querying CR by id](#vae_get) * [Customized challenge record format](#cr_custom) * [Posting a challenge response record (RR) to the blockchain](#rr_post) * [Querying challenge response record](#vae_get) * [Posting a signature record (SR) to the blockchain](#sr_post) * [Querying signature records](#vae_get) * [Revoking signature records](#sr_revoke) ## Posting and Querying Entity Identity Records <a name="eir_post"></a> ## [Entity identity record](contracts/EntityIdentityRecord.sol) (EIR) contains all information that links an entity to a certain identity and the corresponding public key. EIR is created during the key generation process and posted to the blockchain. EIR can be updated during the revocation process. EIR can be registered by calling the [AuthCoin.registerEir](contracts/AuthCoin.sol#L56) function. It has the following input parameters: | Name | Type | Description | |:-------------- | :--------------| :----------- | | content |bytes | Content of the EIR. It may contain a public key or a X509 certificate| | contentType |bytes32 | Type of the EIR. Used to select EIR factory that will be used for EIR creation.| | identifiers |bytes32[] | List of identifiers| | hash |bytes32 | SHA3 hash of the input data.| | signature |bytes | Signature covering the input data| The following _qtum-cli_ command can be used to register new EIR: ``` qtum-cli sendtocontract <authcoin_conract_address> <encoded_function_call> ``` The following _ethabi_ command can be used to generate encoded function call ``` ethabi encode function <authcoin_contract_abi> registerEir -p <content> <contentType> <identifiers> <hash> <signarure> ``` [AuthCoin.getEir](contracts/AuthCoin.sol#L254) function can be used to query EIR by the id. The following _qtum-cli_ command can be used to query EIR: ``` qtum-cli callcontract <authcoin_conract_address> <encoded_function_call> ``` The following _ethabi_ command can be used to generate encoded function call ``` ethabi encode function <authcoin_contract_abi> getEir -p <eirId> <revokingSignature> ``` ## Revoking EIR <a name="eir_revoke"></a> ## EIRs can be revoked by calling the [AuthCoin.revokeEir](contracts/AuthCoin.sol#L96) function and it has following parameters: | Name | Type | Description | |:----------------- | :--------------| :----------- | | eirId |bytes32 | EIR identifier (SHA3 hash of EIR content) | | revokingSignature |bytes | Signature covering SHA3 hash of EIR data | The following _qtum-cli_ command can be used to revoke EIR: ``` qtum-cli sendtocontract <authcoin_conract_address> <encoded_function_call> ``` The following _ethabi_ command can be used to generate encoded function call ``` ethabi encode function <authcoin_contract_abi> revokeEir -p <eirId> <revokingSignature> ``` ## Posting Challenge Record <a name="cr_post"></a> ## Because Authcoin uses bidirectional validation and authentication process, both verifier and target create challenges for each other. The challenge record is stored as a struct in [ValidationAuthenticationEntry (VAE)](contracts/ValidationAuthenticationEntry.sol#L18). CRs can be registered by calling the [AuthCoin.registerChallengeRecord](contracts/AuthCoin.sol#105) function and it has the following parameters: | Name | Type | Description | |:-------------- | :--------------| :----------- | | id |bytes32 | CR identifier | | vaeId |bytes32 | Validation & authentication entry id. Identifier used to group together CRs, RRs and SRs| | challengeType |bytes32 | Type of the challenge| | challenge |bytes | Description of the challenge| | verifierEir |bytes32 | Verifier EIR id| | targetEir |bytes32 | Target EIR id| | hash |bytes32 | SHA3 hash of the input data| | signature |bytes | Signature covering the input data| The following _qtum-cli_ command can be used to register new challenge record: ``` qtum-cli sendtocontract <authcoin_conract_address> <encoded_function_call> ``` The following _ethabi_ command can be used to generate encoded function call ``` ethabi encode function <authcoin_contract_abi> registerChallengeRecord -p <id> <vaeId> <challengeType> <challenge> <verifierEir> <targetEir> <hash> <signature> ``` ## Posting Challenge Response Record <a name="rr_post"></a> ## A challenge response record (RR) is created as part of the validation and authentication process. The verifier and the target create responses to the corresponding challenge requests. A RR contains the response itself and related information. The challenge response record is stored as a struct in [ValidationAuthenticationEntry (VAE)](contracts/ValidationAuthenticationEntry.sol#L30). RR can be registered by calling the [AuthCoin.registerChallengeResponse](contracts/AuthCoin.sol#L166) function. It has the following input parameters: | Name | Type | Description | |:-------------- | :--------------| :----------- | | vaeId |bytes32 | Validation & authentication entry id.| | challengeId |bytes32 | Challenge record id | | response |bytes | Response of the challenge | | hash |bytes32 | SHA3 hash of the input data| | signature |bytes | Signature covering the input data| The following _qtum-cli_ command can be used to register new challenge response record: ``` qtum-cli sendtocontract <authcoin_conract_address> <encoded_function_call> ``` The following _ethabi_ command can be used to generate encoded function call ``` ethabi encode function <authcoin_contract_abi> registerChallengeResponse -p <vaeId> <challengeId> <response> <hash> <signature> ``` ## Posting Challenge Signature Record <a name="sr_post"></a> ## A challenge signature record (SR) is created as part of the validation and authentication process. The verifier and the target create signatures to the corresponding challenge response requests. A SR contains the signature itself and related information. The challenge response record is stored as a struct in [ValidationAuthenticationEntry (VAE)](contracts/ValidationAuthenticationEntry.sol#L40). SR can be registered by calling the [AuthCoin.registerChallengeSignature](contracts/AuthCoin.sol#L192) function. It has the following input parameters: | Name | Type | Description | |:-------------- | :--------------| :----------- | | vaeId |bytes32 | Validation & authentication entry id.| | challengeId |bytes32 | Challenge record id | | expirationBlock |uint | Block number when the signature expires | | successful |bool | True if corresponding chalenge response is considered valid| | hash |bytes32 | SHA3 hash of the input data| | signature |bytes | Signature covering the input data| The following _qtum-cli_ command can be used to register new challenge signature record: ``` qtum-cli sendtocontract <authcoin_conract_address> <encoded_function_call> ``` The following _ethabi_ command can be used to generate encoded function call ``` ethabi encode function <authcoin_contract_abi> registerChallengeSignature -p <vaeId> <challengeId> <expirationBlock> <successful> <hash> <signature> ``` ## Querying Validation Authentication Entry and CR, RR, SR records <a name="vae_get"></a> ## Because Authcoin uses bidirectional validation and authentication process, both verifier and target create challenges, challenge responses and challenge signatures for each other. All this information is stored in contract validation authentication entry (VAE) [ValidationAuthenticationEntry (VAE)](contracts/ValidationAuthenticationEntry.sol) VAE contract address can be queried by calling the [AuthCoin.getVae](contracts/AuthCoin.sol#L261) function. It has the following input parameters: | Name | Type | Description | |:-------------- | :--------------| :----------- | | vaeId |bytes32 | Validation & authentication entry id.| The following _qtum-cli_ command can be used to register new challenge signature record: ``` qtum-cli callcontract <authcoin_conract_address> <encoded_function_call> ``` The following _ethabi_ command can be used to generate encoded function call ``` ethabi encode function <authcoin_contract_abi> getVae -p <vaeId> ``` CRs can be queried by calling the [ValidationAuthenticationEntry.getChallenge](contracts/ValidationAuthenticationEntry.sol#239) function and it has the following parameters: | Name | Type | Description | |:-------------- | :--------------| :----------- | | challengeId |bytes32 | CR identifier | The following _qtum-cli_ command can be used to register new challenge record: ``` qtum-cli callcontract <vae_conract_address> <encoded_function_call> ``` The following _ethabi_ command can be used to generate encoded function call ``` ethabi encode function <authcoin_contract_abi> getChallenge -p <challengeId> ``` RRs can be queried by calling the [ValidationAuthenticationEntry.getChallengeResponse](contracts/ValidationAuthenticationEntry.sol#261) function and it has the following parameters: | Name | Type | Description | |:-------------- | :--------------| :----------- | | challengeId |bytes32 | CR identifier | The following _qtum-cli_ command can be used to register new challenge record: ``` qtum-cli callcontract <vae_conract_address> <encoded_function_call> ``` The following _ethabi_ command can be used to generate encoded function call ``` ethabi encode function <authcoin_contract_abi> getChallengeResponse -p <challengeId> ``` SRs can be queried by calling the [ValidationAuthenticationEntry.getChallengeSignature](contracts/ValidationAuthenticationEntry.sol#273) function and it has the following parameters: | Name | Type | Description | |:-------------- | :--------------| :----------- | | challengeId |bytes32 | CR identifier | The following _qtum-cli_ command can be used to register new challenge record: ``` qtum-cli callcontract <vae_conract_address> <encoded_function_call> ``` The following _ethabi_ command can be used to generate encoded function call ``` ethabi encode function <authcoin_contract_abi> getChallengeSignature -p <challengeId> ``` # Development # ## Setup Development Environment ## Truffle framework is used to write and test Solidity smart contracts. To set up the development environment we need to have _Node_ and _npm_ installed. After that we need to install the _TestRPC_ and _Truffle_: ``` npm install ``` ## Directory Structure ## The project directory has the following structure: * **/contracts:** - Contains the Solidity source files for smart contracts. There is an important contract in here called Migrations.sol. Be sure **not to delete** this file! * **/migrations:** - Truffle uses a migration system to handle smart contract deployments. A migration is an additional special smart contract that keeps track of changes. * **/literature:** - Contains Authcoin related literature. * **/test:** - Contains tests for smart contracts. All unit test should be written in Solidity. * **truffle.js:** - Truffle's configuration file * **ethpm.js:** - Publishing and consuming Ethereum packages. ## Compile Smart Contracts ## Execute `truffle compile` command ## Run Tests ## ``` npm run test ``` ## Run Code Coverage ## ``` npm run coverage ``` ## Run Linting ## ``` npm run lint ``` ## Application Binary Interface ## The ABI, Application Binary Interface, is basically how you call functions in a contract and get data back. ``` An ABI determines such details as how functions are called and in which binary format information should be passed from one program component to the next... ``` An Ethereum smart contract is bytecode, EVM, on the Ethereum blockchain. Among the EVM, there could be several functions in a contract. An ABI is necessary so that you can specify which function in the contract to invoke, as well as get a guarantee that the function will return data in the format you are expecting. **ethabi** library encodes function calls and decodes their output. For more information visit the project page at https://github.com/paritytech/ethabi ## Using Smart Contracts with Qtum ## The smart contract interface in Qtum still requires some technical knowledge. The GUI is not completed yet, so all smart contract interation must happen either using qtum-cli at the command line, or in the debug window of qtum-qt. For more information how to call contracts on Qtum visit https://github.com/qtumproject/qtum/blob/master/doc/sparknet-guide.md <file_sep>/truffle-config.js module.exports = { networks: { development: { gas:8000000, host: "127.0.0.1", port: 7545, network_id: "*" // Match any network id }, live: { // provider: Web3.providers.HttpProvider("http://<host>:<port>"), network_id: 1, host: "127.0.0.1", port: 23889, // optional config values: gas:200000, gasPrice:0x28, from: "0x982fce9ecd065e3b29e0229d8cb2d31dd64a7666" // provider - web3 provider instance Truffle should use to talk to the Ethereum network. // - function that returns a web3 provider instance (see below.) // - if specified, host and port are ignored. // skipDryRun: - true if you don't want to test run the migration locally before the actual migration (default is false) // timeoutBlocks: - if a transaction is not mined, keep waiting for this number of blocks (default is 50) } }, solc: { optimizer: { enabled: true, runs: 200 } } };
86eab079a74d105f83cf2745e7efc6be1fbe658a
[ "JavaScript", "Markdown" ]
8
JavaScript
GiorgiSheklashvili/Authcoin-truffle
9e6db9e7aeace309b9ad56da585c011e548ef726
590c071608f7699e7bec3427469a623947f4eaee
refs/heads/master
<repo_name>rampas90/persnal_study<file_sep>/게시판만들기/c-cgi-mysql 게시판 만들기/cgi-bin/db_lib.h #include "/usr/include/mysql/mysql.h" #define server "dev-smc.com" #define user "root" #define pwd "<PASSWORD>" #define database "main" MYSQL *connection=NULL, conn; MYSQL_RES *res; // (SELECT, SHOW, DESCRIBE, EXPLAIN)등의 쿼리를 내렸을때 그 결과를 다루기 위해 사용되는 구조체이다. MYSQL_ROW row; // 데이터의 하나의 row 값을 가리킨다. 만약 row 값이 없다면 null 을 가르키게 된다. int total_count; unsigned int num_fields; unsigned int num_rows; char search_type[MAX_LEN], search[MAX_LEN]; // DB 접속 및 접속실패 체크 void mysqlDbConn(){ // mysql 한글문자열 깨짐 방지 mysql_init(&conn); mysql_options(&conn, MYSQL_SET_CHARSET_NAME, "utf8"); mysql_options(&conn, MYSQL_INIT_COMMAND, "SET NAMES utf8"); connection = mysql_real_connect(&conn, server, user, pwd, database, 3306, (char *)NULL, 0); if(connection == NULL){ fprintf(stderr, "%s\n", mysql_error(&conn)); exit(1); } } /* * mysqlQuery 함수를 분기처리한 이유 ? * mysql_query 실행을 select,insert,updqte 모두 한꺼번에 함수화해서 처리 하고 싶으나. * resultset 이 있는지(select) 없는지(insert, update)에 따라 분기처리 * * mysqlQuery 의 주요 사용함수 * mysql_store_result : row들을 한번에 모두 얻어와서 클라이언트의 메모리에 저장한다. * 매번 row 값을 얻기위해 서버에 접근할 필요가 없으므로 속도가 빠르다. * 또한, mysql_data_seek()이나 mysql_row_seek() 등을 이용해서 현재 row의 앞이나 뒤로 자유자재로 컨트롤이 가능하며, * myql_num_rows()를 이용해서, 몇 개의 row가 리턴됬는지 알 수도 있다. * 대신 결과로 넘어온 row의 크기가 클 경우 메모리가 많이 필요하게 된다. * 연관함수 : mysql_data_seek(), mysql_row_seek(), myql_num_rows(), mysql_num_fields() * * mysql_use_result : 한번에 한개의 row를 서버로 부터 가져온다. * 따라서 메모리를 많이 사용하지 않는다. 하지만, 그만큼 mysql_store_result()만큼의 효용성이 없으므로, * row가 특별히 크지 않은 경우라면 보통 mysql_store_result()를 호출하는 것이 좋다. * * mysql_num_fields : 현재의 res에 몇개의 field가 있는지 확인 가능한 함수 * 흔히 최종적으로 쿼리를 수행하고난 후 mysql_fetch_row()를 사용할 경우 * 배열형태로 각 필드에 접근 하므로 배열의 인덱스를 알아야 정확한 데이터를 얻을 수 있다. 이러한 용도로 사용.. * * 참고 사이트 MySQL reference manual - http://dev.mysql.com/doc/refman/5.7/en/mysql-num-fields.html */ int mysqlQuery(MYSQL *connection, char *query){ if(mysql_query(connection, query)){ // mysql_query 는 성공적으로 수행될 경우 0을 리턴하므로 에러핸들링 로직 fprintf(stderr, "%s\n", mysql_error(connection)); exit(1); } else{ res = mysql_store_result(connection); // 리턴된 row가 있다. if(res){ /* * row 값들을 얻어오는 루틴 이경우 반드시 mysql_free_result()를 이용해 메모리를 해제시켜줘야 한다.(mysqlDbClose) */ //num_fields = mysql_num_fields(res); // 필드갯수( index 참고용) total_count = mysql_num_rows(res); // 최종 쿼리 row 개수 } // 리턴된 row가 없다. ( row가 없는 쿼리거나 query 수행중에 에러가 났거나..) else{ // row를 리턴하지 않는 쿼리를 실행 (update,insert등...) if (mysql_field_count(connection) == 0){ num_rows = mysql_affected_rows(connection); // 최근 MySQL 작업으로 변경된 행 개수 } // row를 리턴하지 않는 쿼리도 아닌데 리턴된 row가 없다? 즉 에러라는 소리 else{ fprintf(stderr, "%s\n", mysql_error(connection)); exit(1); } } } return total_count; } void mysqlDbClose(){ if(res){ mysql_free_result(res); // 페이징 데이터를 위한 쿼리 해제 ( limit 가 없는 쿼리 ) } mysql_close(connection); // mysql 접속해제 } // select 쿼리 int mysqlDbSelect(char search_type[MAX_LEN] , char search[MAX_LEN] ){ if(strcheck(search_type)){ sprintf(query, "SELECT * FROM bbsc WHERE %s LIKE '%c%s%c' ORDER BY seq desc", search_type, '%', search, '%'); } else{ sprintf(query, "SELECT * FROM bbsc ORDER BY seq desc"); } mysqlQuery(connection, query); } // select 쿼리 limit void mysqlDbSelectLimit(char search_type[MAX_LEN] , char search[MAX_LEN], int limit, int list){ if(strcheck(search_type)){ sprintf(query, "SELECT * FROM bbsc WHERE %s LIKE '%c%s%c' ORDER BY seq desc limit %d, %d", search_type, '%', search, '%', limit, list); } else{ sprintf(query, "SELECT * FROM bbsc ORDER BY seq desc limit %d, %d", limit, list); } mysqlQuery(connection, query); } void mysqlSelectOne(char seq[MAX_LEN]){ sprintf(query, "SELECT * FROM bbsc WHERE seq='%s'", seq); mysqlQuery(connection, query); } //void updateData(char *arr[]){ void updateData(char title[MAX_LEN], char name[MAX_LEN], char content[MAX_LEN], char seq[MAX_LEN]){ sprintf(query, "UPDATE bbsc SET title='%s', name='%s', content='%s' WHERE seq='%s'", title, name, content, seq); mysqlQuery(connection, query); } void insertData(char title[MAX_LEN], char name[MAX_LEN], char content[MAX_LEN]){ sprintf(query, "INSERT INTO bbsc (title, name, content) values('%s', '%s', '%s')", title, name, content); mysqlQuery(connection, query); } <file_sep>/java/java_web_develop_workBook/6장. 미니 MVC 프레임워크 만들기/README.md ## 6. 미니 MVC 프레임워크 만들기 > 요지 대부분의 프로젝트들은 프레임워크 기반으로 개발을 진행한다. 그 이유는 여러가지가 있지만, 문제는 프레이워크를 사용하는 개발자다. 프레임워크를 기반으로 개발을 진행하다 보면 5년, 10년이 지나도 실력이 늘지 않는 경우가 많고, 프레임워크로 해결할 수 없는 요구사항이 들어오면 어떻게 대처해야할지 막막하기도 하다. 그렇다고, 프레임워크를 안 쓸수는 없고, 정확하게 알고 제대로 쓰기위해 무엇이 필요한지 알아보자 - 디자인 패턴과 라이브러리를 적용하여 MVC 프레임워크를 직접 만들어보자 - 스프링 프레임워크를 모방하여 작은 웹 MVC 프레임워크를 만들어보자. - 프레임워크를 만드는 과정 속에서 디자인 패턴의 응용과 오픈소스 라이브러리의 사용, 자바 리플렉션 API와 어노테이션을 사용하는 방법을 익혀보자. ### 프런트 컨트롤러의 도입 `프런트 컨트롤러`라는 디자인 패턴을 이용하여 좀 더 유지보수가 쉬운 구조로 MVC를 개선해보자. 컨트롤러를 만들다 보면 요청데이터를 처리하는 코드나 모델과 뷰를 제어하는 코드가 중복되는 경우가 있다. 중복 코드들은 유지보수를 어렵게 하므로 `프런트 컨트롤러`를 통해 이 문제를 해결해 보자. #### 프런트 컨트롤러 패턴 이전 장에서 배운 MVC는 컨트롤러가 하나였지만, 프런트 컨트롤러 디자인 패턴에서는 두 개의 컨트롤러를 사용하여 웹브라우저 요청을 처리한다. 즉 기존에 서블릿이 단독으로 하던 작업을 프론트 컨트롤러와 페이지 컨트롤러, 두 개의 역할로 나누어 수행하는 것이다. 프런트 컨트롤러는 VO 객체의 준비, 뷰 컴포넌트로의 위임, 오류 처리등과 같은 공통 작업을 담당하고, 페이지 컨트롤러는 이름 그대로 요청한 페이지만을 위한 작업을 수행한다. > 디자인 패턴 자바가상머신이 가비지를 찾아서 자동으로 없애 준다고 하지만, 이 작업 또한 CPU를 사용하는 일이기에 시스템 성능에 영향을 끼친다. 따라서 개발자는 늘 인스턴스의 생성과 소멸에 대해 관심을 가지고 시스템 성능을 높일 수 있는 방법으로 구현해야 한다. 이런 개발자들의 노력은 시스템에 적용되어 많은 시간 동안 시스템이 운영되면서 검증된다. 디자인 패턴은 이렇게 검증된 방법들을 체계적으로 분류하여 정의한 것이다. > 프레임워크 디자인 패턴이 특정 문제를 해결하기 위한 검증된 방법이라면, 프레임워크는 이런 디자인 패턴을 적용해 만든 시스템중에서 우수사례를 모아 하나의 개발 틀로 표준화시킨 것이다. 프레임 워크의 대표적인 예로 스프링이 있으며, 이보다 기능은 작지만, MVC 프레임워크로 특화된 스트럿츠가 있다. Mybatis는 데이터베이스 연동을 쉽게 해주는 프레임워크다. 자바스크립트를 위한 프레임워크인 Angular와 Ember도 있으니 참고하자. #### 프런트 컨트롤러만들기 ```java package spms.servlets; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import spms.vo.Member; @WebServlet("*.do") public class DispatcherServlet extends HttpServlet { @Override protected void service( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html; charset=UTF-8"); String servletPath = request.getServletPath(); try{ String pageControllerPath = null; if("/member/list.do".equals(servletPath)){ pageControllerPath="/member/list"; } else if("/member/add.do".equals(servletPath)){ pageControllerPath="/member/add"; if (request.getParameter("email") != null) { request.setAttribute("member", new Member() .setEmail(request.getParameter("email")) .setPassword(request.getParameter("<PASSWORD>")) .setName(request.getParameter("name"))); } } else if("/member/update.do".equals(servletPath)){ pageControllerPath="/member/update"; if(request.getParameter("email") != null){ request.setAttribute("member", new Member() .setNo(Integer.parseInt(request.getParameter("no"))) .setEmail(request.getParameter("email")) .setName(request.getParameter("name"))); } } else if("/member/delete.do".equals(servletPath)){ pageControllerPath="/member/delete"; } else if("auth/login.do".equals(servletPath)){ pageControllerPath="/auth/login"; } else if("auth/logout.do".equals(servletPath)){ pageControllerPath="/auth/logout"; } RequestDispatcher rd=request.getRequestDispatcher(pageControllerPath); rd.include(request, response); String viewUrl=(String) request.getAttribute("viewUrl"); if(viewUrl.startsWith("redirect:")){ response.sendRedirect(viewUrl.substring(9)); return; } else{ rd=request.getRequestDispatcher(viewUrl); rd.include(request, response); } } catch (Exception e){ e.printStackTrace(); request.setAttribute("error", e); RequestDispatcher rd=request.getRequestDispatcher("/Error.jsp"); rd.forward(request, response); } } } ``` 프런트 컨트롤러도 서블릿이기 때문에 HttpServlet을 상속받는다. ```java service(HttpServletRequest request, HttpServletResponse response) ``` > 여기서 주목할 점은 오버라이딩하는 메소드다. 분명히 처음엔 `Servlet`을 상속받아 `Servlet인터페이스`에 선언된 다섯개의 메소드를 구현했고, 사실상 `service()`메소드만 구현해도 되기때문에 `init()`, `destroy()`, `getServletConfig()`, `getServletInfo()`를 미리 구현하여 상속해준 `GenericServlet`을 사용했다. 거기에 또다시` service()메소드`를 `doGet()`과 `doPost()`, `doPut()`등으로 상황에 따라 나누어 구현하기 위헤 `HttpServlet`을 상속받아 사용했었다 > 그런데 왜 이제와서 `HttpServle`t 을 상속받아놓고 `doGet()`, `doPost()`가 아니라 `service()`를 구현했을까? 이 메소드의 매개변수를 살펴보면, `ServletRequest`와 `ServletResponse`가 아니라 `HttpServletRequest`와 `HttpServletResponse`이다 **즉 Servlet 인터페이스에 선언된 메소드가 아니라는 뜻이다.** ```java protected void service(HttpServletRequest request, HttpServletResponse response) ``` 그럼 이 메소드는 서블릿 컨테이너(톰캣)가 직접 호출하지 않는다는 것인데, 도대체 언제 호출되는 걸까? 순서를 통해 살펴보자 1. 클라이언트로부터 요청이 들어오면 서블릿 컨테이너는 규칙에 따라 Servlet인터페이스에 선언된 service() 메소드를 호출한다. 2. 이 `service(ServletRequest, ServletResponse)` 메소드는 HttpServlet 클래스에 추가된 동일한 이름의 `service(HttpServletRequest, HttpServletResponse)`메소드를 호출한다. 이름은 같지만, 매개변수가 다르다 3. service(HttpServletRequest, HttpServletResponse)메소드는 HTTP 요청 프로토콜을 분석하여 다시 doGet(),doPost()등을 호출한다. 어찌 되었든 GET요청이든, POST요청이든 service(HttpServletRequest, HttpServletResponse)메소드가 호출된다는 것이다. 그래서 이 메소드를 오버라이딩 한 것이다. > 그럼 여기서 다시 의문 " 차라리 doGet(),doPost()를 오버라이딩하지 왜 궂이 service()를 오버라이딩하지?" 물론 doGet(), doPost()를 오버라이딩하여 `프론트 컨트롤러`를 만들 수 있다. 그럼에도 service()를 오버라이딩 한 이유는 첫째, GET, POST뿐만 아니라 다양한 요청방식에도 대응하기 위해서다. 둘째, 가능한 HttpServlet의 내부 구조를 조금이라도 알아보기 위해서다 ###### 요청URL에서 서블릿 경로 알아내기 프론트 컨트롤러의 역할은 클라이언트의 요청을 적절한 페이지 컨트롤러에게 전달하는 것이다. 그러려면 클라이언트가 요청한 서블릿의 URL을 알아내야 한다. 예를 들어 요청 URl이 다음과 같다고 가정해보자 `http://localhost:9999/web06/member/list.do?pageNo=1&pageSize=10` | 메소드 | 설명 | 반환값 |--------|--------|-- | getRequestURL() | 요청 URL 리턴(단, 매개변수 제외) | http://localhost:9999/web06/member/list.do | getRequestURI() | 서버 주소를 제외한 URL | /web06/member/list.do | getContextPath() | 웹 어플리케이션 경로 | /web06 | getServletPath() | 서블릿 경로 | /member/list.do | getQueryString() | 요청 매개변수 정보 | pageNo=1&pageSize=10 위의 표를 참고하여 클라이언트가 요청한 서블릿의 경로를 알고 싶다면 `getServletPath()`를 호출하면 된다. ###### 페이지 컨트롤러로 위임 서블릿 경로에 따라 조건문을 사용하여 적절한 페이지 컨트롤러를 인클루딩 한다 아래는 위 전체 코드중 해당 부분을 보기 좋게 축약한 소스다 ```java String pageControllerPath = null; if("/member/list.do".equals(servletPath)){ pageControllerPath="/member/list"; } else if("/member/add.do".equals(servletPath)){ pageControllerPath="/member/add"; ... } else if("/member/update.do".equals(servletPath)){ pageControllerPath="/member/update"; ... } else if("/member/delete.do".equals(servletPath)){ pageControllerPath="/member/delete"; } else if("auth/login.do".equals(servletPath)){ pageControllerPath="/auth/login"; } else if("auth/logout.do".equals(servletPath)){ pageControllerPath="/auth/logout"; } RequestDisptcher rd=request.getRequestDispatcher(pageControllerPath); rd.include(request,response); ``` ###### 요청 매개변수로부터 VO 객체 준비 프론트 컨트롤러의 역할 중 하나는 페이지 컨트롤러가 필요한 데이터를 미리 준비하는 것이다. 가령 회원정보 등록과 변경은 사용자가 입력한 데이터를 페이지 컨트롤러에게 전달하기 위해, 요청 매개변수의 값을 꺼내서 VO객체에 담고, "member"라는 키로 ServletRequest에 보관했다 ```java request.setAttribute("member", new Member() .setEmail(request.getParameter("email")) .setPassword(request.getParameter("<PASSWORD>")) .setName(request.getParameter("name"))); ``` 여기서는 쓸데없는 임시 변수의 사용을 최소화하기 위해 Member 객체를 생성한 후, 바로 값을 할당하고, ServletRequset에 보관했다. ###### JSP로 위임 페이지 컨트롤러의 실행이 끝나면, 화면 출력을 위해 ServletRequest에 보관된 뷰URL로 실행을 위임했다. 단 뷰 URL이 "redirec:" 로 시작한다면, 인클루딩 하는 대신에 sendRedirect()를 호출한다. ```java String viewUrl=(String) request.getAttribute("viewUrl"); if(viewUrl.startsWith("redirect:")){ response.sendRedirect(viewUrl.substring(9)); return; } else{ rd=request.getRequestDispatcher(viewUrl); rd.include(request, response); } ``` ###### 오류처리 서블릿을 만들 때 매번 작성한 것 중의 하나가 오류처리다. 이제 프런트 컨트롤러에서 오류 처리를 담당하기 때문에, 페이지 컨트롤러를 작성할 때는 오류 처리 코드를 넣을 필요가 없다. ```java catch (Exception e){ e.printStackTrace(); request.setAttribute("error", e); RequestDispatcher rd=request.getRequestDispatcher("/Error.jsp"); rd.forward(request, response); } ``` ###### 프론트 컨트롤러의 배치 @WebServlet 어노테이션을 사용하여 프론트 컨트롤러의 배치 URL을 `*.do`로 지정했다. 즉 클라이언트의 요청 중에서 서블릿 경로 이름이 .do로 끝나는 경우는 DispatcherServlet이 처리하겠다는 의미다. ```java @WebServlet("*.do") public class DispatcherServlet extends HttpServlet { ``` ___ #### MemberListServlet을 페이지 컨트롤러로 만들기 프론트 컨트롤러가 준비됬으니 기존의 서블릿을 페이지 컨트롤러로 변경해 보자. 먼저 MemberListServlet을 바꿔보자 > spm.servlet.MemeberListServlet 클래스 ```java package spms.servlets; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import spms.dao.MemberDao; // 프론트 컨트롤러 적용 @WebServlet("/member/list") public class MemberListServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { ServletContext sc = this.getServletContext(); MemberDao memberDao = (MemberDao)sc.getAttribute("memberDao"); request.setAttribute("members", memberDao.selectList()); } catch (Exception e) { throw new ServletException(e); } } } ``` > 응답 데이터의 문자 집합은 프론트 컨트롤러에서 이미 설정했기 때문에 페이지 컨트롤러에서 코드를 제거했다. ```java response.setContentType("text/html; charset=UTF-8"); ``` > 또한, 화면 출력을 위해 JSP로 실행을 위임하는 것도 프론트 컨트롤러가 처리하기때문에 역시 제거했다. ```java RequestDispatcher rd =request.getRequestDisptcher("/member/MemberList.jsp"); rd.include(request,response); ``` > 대신 JSP URL정보를 프론트 컨트롤러에게 알려주고자 ServletRequest 보관소에 저장한다. ```java request.setAttribute("viewUrl", "/member/MemberList.jsp"); ``` > 오류가 발생했을 때 오류 처리 페이지(/Error.jsp)로 실행을 위임하는 작업도 프론트컨트롤러가 하기 때문에 코드를 제거했다. ```java e.printStackTrace(); request.setAttribute("error", e); RequestDispatcher rd=request.getRequestDispatcher("/Error.jsp"); rd.forward(request, response); ``` 대신 Dao를 실행하다가 오류가 발생한다면, 기존의 오류를 ServletException 객체에 담아서 던지도록 했다. ```java throw new ServletException(e/); ``` service() 메소드는 ServletException을 던지도록 선언되어 있기 때문에 기존의 예외 객체를 그냥 던질 수 없다. 그래서 ServletException객체를 생성한 것이다. ___ #### 프론트 컨트롤러를 통한 회원 목록 페이지 요청 ###### `*.do` 요청 요청 URL이 `.do`로 끝나기 때문에, DispatcherServlet이 요청을 받는다. /member/list.do 요청을 처리할 페이지 컨트롤러(MemberListServlet)를 찾아 실행을 위임하는 것이다. ###### 회원 목록 페이지에 있는 링크의 URL에 .do 접미사 붙이기 회원 목록 페이지에 있는 링크들들 보면 아직 예전의 서블릿 URL을 가리키고있는데. 이 링크 URL에 `.do`를 붙이자 > MemberList.jsp ```java <jsp:include page="/Header.jsp"/> <h1>회원목록2</h1> <p><a href='add.do'>신규 회원</a></p> <c:forEach var="member" items="${members}"> ${member.no}, <a href='update.do?no=${member.no}'>${member.name}</a>, ${member.email}, ${member.createdDate} <a href='delete.do?no=${member.no}'>[삭제]</a><br> </c:forEach> <jsp:include page="/Tail.jsp"/> ``` 이렇게 링크를 변경하면 프론트 컨트롤러(DispatcherServlet)에게 요청할 것이다. #### MemberAddServlet을 페이지 컨트롤러로 만들기 회원리스트는 변경했으니 회원등록 서블릿에 프론트 컨트롤러를 적용해 보자 > spms.servlets.MemberAddServlet ```java package spms.servlets; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import spms.dao.MemberDao; import spms.vo.Member; // 프론트 컨트롤러 적용 @WebServlet("/member/add") public class MemberAddServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - RequestDispatcher rd = request.getRequestDispatcher( - "/member/MemberForm.jsp"); - rd.forward(request, response); + request.setAttribute("viewUrl", "/member/MemberForm.jsp); } @Override protected void doPost( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { ServletContext sc = this.getServletContext(); MemberDao memberDao = (MemberDao)sc.getAttribute("memberDao"); - memberDao.insert(new Member() - .setEmail(request.getParameter("email")) - .setPassword(request.getParameter("password")) - .setName(request.getParameter("name"))); - - response.sendRedirect("list"); + Member member = (Member)request.getAttribute("member"); + memberDao.insert(member); + request.setAttribute("viewUrl", "redirect:list.do"); } catch (Exception e) { - e.printStackTrace(); - request.setAttribute("error", e); - RequestDispatcher rd = request.getRequestDispatcher("/Error.jsp"); - rd.forward(request, response); + throw new ServletException(e); } } } ``` ###### 뷰로 포워딩하는 코드를 제거 GET 요청을 처리하는 doGet() 메소드에서 MemberForm.jsp로 포워딩하는 코드를 제거하고 MemberForm.jsp의 URL을 ServletRequest에 저장했다. ```java // RequestDispatcher rd = request.getRequestDispatcher("/member/MemberForm.jsp"); // rd.forward(request, response); request.setAttribute("viewUrl", "/member/MemberForm.jsp"); ``` ###### 요청매개변수의 값을 꺼내는 코드를 제거 회원등록을 요구하는 POST 요청이 들어오면 doPost()가 호출 된다. 클라이언트가 보낸 회원정보를 꺼내기 위해 getParameter()를 호출하는 대신, 프론트 컨트롤러가 준비해 놓은 Member 객체를 ServletRequest 보관소에서 꺼내도록 doPost() 메소드를 변경했다. ```java // memberDao.insert(new Member() // .setEmail(request.getParameter("email")) // .setPassword(request.getParameter("password")) // .setName(request.getParameter("name"))); // // response.sendRedirect("list"); Member member = (Member)request.getAttribute("member"); memberDao.insert(member); ``` ###### 리다이렉트를 위한 뷰 URL설정 회원 정보를 데이터베이스에 저장한 다음, 회원 목록 페이지로 리다이렉트 해야 하는데, 기존 코드를 제거하고 대신에 ServletRequest에 리다이렉트 URL을 저장했다. ```java // response.sendRedirect("list"); request.setAttribute("viewUrl", "redirect:list.do"); ``` 뷰 URL이 "redirec:"문자열로 시작할 경우, 프론트 컨트롤러는 그 URL로 리다이렉트 한다. 따라서 리다이렉트 해야하는 경우 반드시 URL앞부분에 "redirect:"문자열을 붙여야 한다. ###### 오류 처리 코드 제거 MemberListServlet과 마찬가지로 오류가 발생했을 때 오류 처리 페이지로 실행을 위임하는 코드를 제거하고, 그 자리에 ServletException 을 던지는 코드를 넣었다 ```java - e.printStackTrace(); - request.setAttribute("error", e); - RequestDispatcher rd = request.getRequestDispatcher("/Error.jsp"); - rd.forward(request, response); + throw new ServletException(e); ``` ###### 회원 등록 폼의 action URL에 .do붙이기 MemberForm.jsp 에도 `<form>` 태그의 action 값을 변경하자 ```java - <form action='add' method='post'> + <form action='add.do' method='post'> ``` 나머지 MemberUpdateServlet, MemberDeleteServlet, LogInServlet, LogOutServlet 등도 같은 방식으로 변경해보자. --- ### 페이지 컨트롤러의 진화 프론트 컨트롤러를 도입하면 페이지 컨트롤럴르 굳이 서블릿으로 만들어야 할 이유가 없다. 이번 절에서는 페이지 컨트롤러를 일반 클래스로 전환해 보자. 일반 클래스로 만들면 서블릿 기술에 종속되지 않기 때문에 재사용성이 더 높아진다. 이제 프론트 컨트롤러에서 페이지 컨트롤러로 작업을 위임할 때는 포워딩이나 인클루딩 대신 메소드를 호출해야 한다. #### 프론트 컨트롤러와 페이지 컨트롤러의 호출 규칙 정의 프론트 컨트롤러가 페이지 컨트롤러를 일관성 있게 사용하려면, 호출 규칙을 정의해야 한다. 프론트 컨트롤러와 페이지 컨트롤러 사이의 호출 규칙을 문법으로 정의해 두면 개발자들은 그 규칙에 따라 해당 클래스를 작성하고 호출하면 되기때문에 프로그래밍의 일관성을 확보할 수 있어 유지보수에 도움이 된다. 또한 페이지 컨트롤러를 서블릿이 아닌 일반 클래스로 만들면 web.xml 파일에 등록할 필요가 없어 유지보수가 쉬워진다. #### 호출 규칙 정의 프론트 컨트롤러와 페이지 컨트롤러 사이의 호출 규칙을 정의할때 사용하는 문법이 `인터페이스`이다. 즉 인터페이스는 사용자와 피사용자(또는 호출자와 피호출자) 사이의 일관성 있는 사용을 보장하기 위해 만든 자바 ㅜㅁㄴ법이다. > 서블릿으로 작성된 모든 페이지 컨트롤러를 프론트 컨트롤러의 호출 규칙에 맞추워 일반 클래스로 전환해보자 아래 순서는 인터페이스가 적용된 페이지 컨트롤러의 대략적인 사용시나리오다 1. 웹브라우저는 회원목록페이지를 요청한다. 2. 프론트 컨트롤러 `DispatcherServlet`은 회원 목록 요청 처리를 담당하는 페이지 컨트롤러를 호출한다. 이때 데이터를 주고받을 바구니 역할을 할 Map 객체를 넘긴다. 3. 페이지 컨트롤러 `MemberListController`는 `Dao`에게 회원 목록 데이터를 요청한다. 4. `MemberDao` 는 데이터베이스로부터 회원 목록 데이터를 가져와서, Member 객체에 담아 반환한다. 5. 페이지 컨트롤러는 Dao가 반환한 회원 목록 데이터를 Map 객체에 저장한다. 그리고 프론트 컨트롤러에게 뷰 URL을 반환한다. 6. 프론트 컨트롤러는 Map객체에 저장된 페이지 컨트롤러의 작업 결과물을 JSP가 사용할 수 있도록 ServletRequest로 옮긴다. 7. 나머지는 바로 앞에서 배운 과정과 동일하다. > 여기서 중요한 점은 프론트 컨트롤러가 페이지 컨트롤러에게 작업을 위임할 때 더 이상 포워딩이나 인클루딩 방식을 사용하지 않고, > 페이지 컨트롤러에게 일을 시키기 위해 `excute()`메소드를 호출한다. 또한 프론트와 페이지 사이에 데이터를 주고받기 위해 Map객체를 사용하고 있는데 이는, 페이지 컨트롤러가 Servlet API를 직접 사용하지 않도록 하기 위함으로 서블릿 기술에 종속되는 것을 줄일수록 페이지 컨트롤러의 재사용성이 높아지기 때문이다. #### 페이지 컨트롤러를 위한 인터페이스 정의 > 새로운 spms.controls 패키지를 만들고 Controller 인터페이스를 생성하자 ```java package spms.controls; import java.util.Map; public interface Controller { String excute(Map<String, Object>model) throws Exception; } ``` `excute()`는 프론트 컨트롤러가 페이지 컨트롤러에게 일을 시키기 위해 호출하는 메소드다. 여기서는 프론트컨트롤러가 excute를 호출하려면 Map객체를 매개변수로 넘겨줘야 한다. #### 페이지 컨트롤러 MemberListServlet을 일반 클래스로 전환 회원목록을 처리했던 페이지 컨트롤러 `MemberListServlet`을 일반 클래스로 전환해보자 > spms.controls 패키지에 MemberListController 클래스 생성 ```java package spms.controls; import java.util.Map; import spms.dao.MemberDao; public class MemberListController implements Controller { @Override public String excute(Map<String, Object> model)throws Exception{ MemberDao memberDao = (MemberDao)model.get("memberDao"); model.put("members", memberDao.selectList()); return "/member/MemberList.jsp"; } } ``` ###### Controller 인터페이스의 구현 페이지 컨트롤러가 되려면 Controller 규칙에 따라 클래스를 작성해야 한다 ```java public class MemberListController implements Controller { public String excute(Map<String, Object> model)throws Exception{ ``` 또한 페이지 컨트롤러는 더 이상 예외 처리를 할 필요가 없고, 예외가 발생했을 때 호출자인 프론트 컨트롤러에게 던지면 된다. ###### 페이지 컨트롤러에게 사용할 객체를 Map에서 꺼내기 MemberDao 객체는 프론트 컨트롤러가 넘겨준 마법의 상자, "Map 객체(model)"에 들어있다. 물론 지금 프론트단에 작업되었다는게 아니라 그렇게 할거라는 말이다. ```java MemberDao memberDao = (MemberDao)model.get("memberDao"); ``` ###### 페이지 컨트롤러가 작업한 결과물을 Map에 담기 Map객체 'model' 매개변수는 페이지 컨트롤러가 작업한 결과를 담을 때도 사용한다. 예제에서는 회원 목록 데이터를 model에 저장하고 있다. ```java model.put("members", memberDao.selectList()); ``` Map 객체에 저장된 값은 프론트 컨트롤러가 꺼내서 ServletRequest 보관소로 옮길 것이다. ServletRequest 보관소에 저장된 값은 다시 JSP가 꺼내서 사용할 것이다. ###### 뷰URL 반환 페이지 컨트롤러의 반환 값은 화면을 출력할 JSP의 URL 이며, 프론트 컨트롤러는 이 URL로 실행을 위임한다. ```java return "/member/MemberList.jsp"; ``` #### 프론트 컨트롤러 변경 이제 Controller 규칙에 따라 페이지 컨트롤러를 호출하도록 프론트 컨트롤러를 변경해보자. > spms.servlets.DispatcherServlet 클래스의 service()메소드 ```java ServletContext sc = this.getServletContext(); // 페이지 컨트롤러에게 전달할 Map 객체를 준비한다. HashMap<String,Object> model = new HashMap<String,Object>(); model.put("memberDao", sc.getAttribute("memberDao")); String pageControllerPath = null; Controller pageController = null; if("/member/list.do".equals(servletPath)){ .. } else if("/member/add.do".equals(servletPath)){ .. } else if("/member/update.do".equals(servletPath)){ .. } else if("/member/delete.do".equals(servletPath)){ .. } else if("auth/login.do".equals(servletPath)){ .. } else if("auth/logout.do".equals(servletPath)){ .. } // 페이지 컨트롤러를 실행한다. String viewUrl = pageController.execute(model); // Map 객체에 저장된 값을 ServletRequest에 복사한다. for (String key : model.keySet()) { request.setAttribute(key, model.get(key)); } /* RequestDispatcher rd=request.getRequestDispatcher(pageControllerPath); rd.include(request, response); String viewUrl=(String) request.getAttribute("viewUrl"); */ if(viewUrl.startsWith("redirect:")){ response.sendRedirect(viewUrl.substring(9)); return; } else{ RequestDispatcher rd=request.getRequestDispatcher(viewUrl); rd.include(request, response); } ``` ###### Map 객체 준비 프론트 컨트롤러와 페이지 컨트롤러 사이에 데이터나 객체를 주고 받을 때 사용할 Map객체를 준비한다. 즉 MemberListController가 사용할 객체를 준비하여 Map객체에 담아서 전달해 준다 ```java ServletContext sc = this.getServletContext(); // 페이지 컨트롤러에게 전달할 Map 객체를 준비한다. HashMap<String,Object> model = new HashMap<String,Object>(); model.put("memberDao", sc.getAttribute("memberDao")); ``` MemberListController는 회원 목록을 가져오기 위해 MemberDao 객체가 필욯다. 그래서 ServletContext 보관소에 저장된 MemberDao 객체를 꺼내서 Map객체에 담았다. ###### 회원 목록을 처리할 페이지 컨트롤러 준비 > 페이지 컨트롤러는 Controller의 구현체이기 때문에, 인터페이스 타입의 참조변수를 선언했다. 그래야만 앞으로 만들 MemberAddController, MemberUpdateController, MemberDeleteController등의 객체 주소도 저장할수 있기 때문이다. ```java Contoller pageController = null; ``` > 회원목록요청을 처리할 페이지 컨트롤러를 준비한다. ```java if("/member/list.do".equals(servletPath)){ pageController = new MemberListController(); } ``` 일단은 회원 목록에 대해서만 위처럼 적용한다. ###### 페이지 컨트롤러의 실행 이전에는 페이지 컨트롤러가 서블릿이었기 때문에 인클루딩(혹은 포워드)처리로 실행을 위임했지만, 이제는 MemberListController가 일반 클래스이기 때문에 메소드를 호출해야 한다. 그것도 Controller 인터페이스에 정해진 대로 `excute()`메소드를 호출해야 한다. ```java String viewUrl = pageController.excute(model); ``` `excute()`를 호출할 때 페이지 컨트롤러를 위해 준비한 Map 객체를 매개변수로 넘긴다. excute()의 반환값은 화면 출력을 수행하는 JSP의 URL 이다. ###### Map 객체에 저장된 값을 ServletRequest에 복사 Map객체는 페이지 컨트롤러에게 데이터나 객체를 보낼 때 사용되기도 하지만 페이지 컨트롤러의 실행 결과물을 받을 때도 사용한다. 따라서 페이지 컨트롤러의 실행이 끝난 다음, Map객체에 보관되어 있는 데이터나 객체를 JSP가 사용할 수 있도록 ServletRequest에 복사한다. ```java for(String ket : model.keySet()){ request.setAttribute(ket,model.get(key)); } ``` ___ #### 회원 등록 페이지 컨트롤러에 Controller 규칙 적용하기 MemberListController처럼 MemberAddServlet에 대해서도 적용해 보자 > spms.controls.MemberAddController ```java package spms.controls; import java.util.Map; import spms.dao.MemberDao; import spms.vo.Member; public class MemberAddController implements Controller { @Override public String excute(Map<String, Object> model) throws Exception{ if(model.get("member")==null){ // 입력폼을 요청할 때 return "/member/MemberForm.jsp"; } else{ // 회원등록을 요청할 때 MemberDao memberDao = (MemberDao)model.get("memberDao"); Member member = (Member)model.get("member"); memberDao.insert(member); return "redirect:list.do"; } } } ``` MemberAddServlet은 서블릿이기 때문에 GET요청과 POST 요청을 구분하여 처리할 수 있었다. 그러나 MemberAddController는 일반 클래스이기 때문에 클라이언트 요청에 대해 GET과 POST를 구분할 수 없다. 그래서 Map객체에 VO객체 "Member"가 들어 있으면 POST요청으로 간주하고, 그렇지 않으면 GET요청으로 간주한 것이다. Map 객체에 "Member" 인스턴스가 없으면, 입력폼을 위한 JSP URL을 반환한다. ```java if(model.get("member")==null){ return "/member/MemberForm.jsp"; } ``` Map 객체에 "Member" 인스턴스가 있으면, MemberDao를 통해 DB에 저장한다. ```java else{ // 회원등록을 요청할 때 MemberDao memberDao = (MemberDao)model.get("memberDao"); Member member = (Member)model.get("member"); memberDao.insert(member); return "redirect:list.do"; } ``` #### 회원등록 요청을 처리하기 위해 DispatcherSevlet 변경 MemberListController 때와 마찬가지로 MemberAddController를 사용하도록 DispatcherServlet을 변경해야 한다. > spms.servlets.DispatcherServlet 클래스의 service()메소드에서 회원 등록을 처리하는 부분 ```java else if("/member/add.do".equals(servletPath)){ pageController=new MemberAddController(); if (request.getParameter("email") != null) { model.put("member", new Member() .setEmail(request.getParameter("email")) .setPassword(request.getParameter("password")) .setName(request.getParameter("name"))); } } ``` MemberAddController의 인스턴스를 생성했다. 또한 이전에는 사용자가 입력한 데이터에 대해 Member 객체를 만든후, ServletRequest 보관소에 담았지만, 이제는 Map 객체에 담는다. > 새로운 소스가 잘 작동하는지 웹에서 테스트 해보자 이처럼 기존의 소스를 변경하거나 새로운 기능을 추가하거나 할때는 한꺼번에 모든것을 작성하지 말고, 지금처럼 회원목록, 등록 을 순차적으로 작성했듯이 해나가는것이 좋다. 디버깅하기도 쉽고... > 나머지도 마저 바꿔보자 (로그인,아웃 경우에는 session 처리에 유의 ) --- ### DI를 이용한 빈 의존성 관리 MemberListController 작업을 수행하려면 데이터베이스로부터 회원 정보를 가져다 줄 MemberDao가 필요하다. 이렇게 특정 작업을 수행할 때 사용하는 객체를 '의존객체'라고 하고, 이런 관게를 의존관게(dependency) 라고 한다. #### 의존객체의 관리 의존 객체 관리에는 필요할 때마다 의존 객체를 직접 생성하는 고전적인 방법에서부터 외부에서 의존 객체를 주입해 주는 최근읜 방법까지 다양한 방안이 존재한다. > 의존 객체가 필요하면 즉시 생성 ( 고저적인방법 ) 의존 객체를 사용하는 쪽에서 직접 그 객체를 생성하고 관리하는 것. 이전에 작성했던 MemberListServlet 의 일부 코드를 보자 ```java public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try{ ServletContext sc = this.getServletContext(); Connection conn = (connection) sc.getAttribute("conn"); MemberDao memberDao = new MemberDao(); memberDao.setConnection(conn); request.setAttribute("members", memberDao.selectList()); .. } } ``` 회원 목록을 가져오기 위해 직접 MemberDao 객체를 생성하고 있다. 이 방식의 문제점은 doGet()이 호출될 때마다 MemberDao가 객체를 생성하기 때문에 비효율적이다. ###### 의존객체를 미리 생성해 두엇다가 필요할 때 사용 앞의 방법을 조금 개선한한것이 사용할 객체를 미리 생성해 둑 필요할 때마다 꺼내 쓰는 방식이다. 윂 에플리켜이션이 시작될때 MemberDao 객체를 미리 생성하여 ServletContext 에 보관해 둔다. 그리고 아래처럼 필요할 때 마다 꺼내 쓴다 ```java public void doGET{ .. try{ ServletContext sc = thisl.getServletContext(); Member memberDao = (MemberDao) sc.getAttribute("memberDao" memberDao.setConnect(conn); request.setAttribute("members", memberDao.selectList()); } } } ``` 이전에 작성한 `MemberListController`또한 이러한 방식을 사용하고 있다. 다만, ServletContext가 아닌 Map객체에서 꺼낸다는 것이 다를뿐이다. ###### 의존객체와의 결합도 증가에 따른 문제 앞에서 처럼 의존 객체를 생성하거나 보관소에서 꺼내는 방식으로 관리하다 보니 문제가 발생한다.. 1) 코드의 잦은 변경 의존 객체를 사용하는 쪽과 의존 객체(또는 보관소)사이의 결합도가 높아져서 의존 객체나 보관소에 변경이 발생하면 바로 영향을 받는다는 것이다. 예를 들면 의존 객체의 기본생성자가 `public` 에서 `private`으로 바뀐다면 의존객체를 생성하는 모든 코드를 찾아 변경해 주어야 한다. 보관소도 마찬가지다. 보관소가 변경되면 그 보관소를 사용하는 모든 코드를 변경해야 한다. 2) 대체가 어렵다 의존 객체를 다른 객체로 대체하기가 어렵다. 현재 MemberListController가 사용하는 MemberDao는 MySQL DB를 사용하도록 작성되어있다. 만약 오라클 DB를 사용해야 한다면, 일부 SQL문을 그에 맞게끔 변경해야 한다. 다른 방법으로는 각 DB별로 MemberDao를 준비하는 것이다. 그래도 여전히 문제는 남아있다. 바로 DB가 바뀔 때 마다 DAO를 사용하는 코드도 변경해야 한다는 것이다. > 그래서 이러한 문제들을 해결하기 위해 등장한 방법이 바로 다음에 소개할 내용이다. #### 의존 객체를 외부에서 주입 초창기 객체 지향 프로그래밍에서는 의존객체를 직접 생성해왔다. 그러다가 위에서 언급한 문제를 해결하기 위해 의존객체를 외부에서 주입받는 방식`(Dependency Injection)`으로 바뀌게 된것이다. > 이렇게 의존객체를 전문으로 관리하는 빈 컨테이너(Java Beans Container)가 등장한 것이다. 빈 컨테이너는 객체가 실행되기 전에 그 객체가 필요로 하는 의존 객체를 주입해 주는 역할을 수행한다. 이런 방식으로 의존객체를 관리하는 것을 `의존성 주입(DI:Dependenct Injection)`이라 한다. 좀 더 일반적인 말로 `역 제어(IoC:Inversion of Control)` 라고 부르는데 즉 역제어(IoC)방식의 한 예가 의존성 주입(DI)인 것이다. #### MemberDao 와 DataSource 지금까지 사용했던 MemberDao에 DI 기법이 이미 적용되어 있다. MemberDao가 작업을 수행하려면 데이터베이스와 연결을 수행하는 DataSource가 필요하다. 그런데 이 DataSource 객체를 MemberDao에서 직접 생성하는 것이 아니라 외부에서 주입 받는다. 다음 코드가 MemberDao에 DataSource를 주입하는 코드다 ```java public void contextInitialized(ServletContextEvent event) { try { ServletContext sc = event.getServletContext(); InitialContext initialContext = new InitialContext(); DataSource ds = (DataSource)initialContext.lookup( "java:comp/env/jdbc/studydb"); MemberDao memberDao = new MemberDao(); memberDao.setDataSource(ds); ``` ContextLoaderListener의 contextInitialized()는 웹 에플리케이션이 시작될 때 호출되는 메소드다. 이 메소드를 살펴보면 setDateSource()를 호출하는 부분이 있는데, 바로 이 부분이 MemberDao가 사용할 의존 객체인 DataSource를 주입하는 부분이다. #### MemberListController에 MemberDao 주입 MemberListController가 작업을 수행하려면 MemberDao가 필요하다. MemberListController에도 DI를 적용해보자 > spms.controls.MemberListController ```java public class MemberListController implements Controller { MemberDao memberDao; public MemberListController setMamberDao(MemberDao memberDao){ this.memberDao=memberDao; return this; } @Override public String excute(Map<String, Object> model)throws Exception{ MemberDao memberDao = (MemberDao)model.get("memberDao"); model.put("members", memberDao.selectList()); return "/member/MemberList.jsp"; } } ``` ###### 의존객체 주입을 위한 인스턴스 변수와 세터 메소드 MemberDao에서 DataSource 객체를 주입 받고자 인스턴스 변수와 세터 메소드를 선언했듯이, MemberListController에도 MemberDao를 주입 받기 위한 인스턴스 변수와 세터 메소드를 추가했다. > 여기서는 세터 메소드를 좀 더 쉽게 사용하기 위해 Member 클래스에서처럼 리턴 타입이 그 자신의 인스턴스 값을 리턴하도록 했따. ###### 의존 객체를 스스로 준비하지 않는다. 외부에서 MemberDao 객체를 주입해 줄 것이기 때문에 이제 더 이상 Map 객체에서 MemberDao를 꺼낼 필요가 없다. 따라서 아래의 코드를 제거했다. ```java MemberDao memberDao = (MemberDao)model.get("memberDao"); ``` > 나머지 Controller 들도 (delete,login 등등...) MemberDao를 주입하기 위한 인스턴스 변수와 세터 메소드를 추가해보자 #### 페이지 컨트롤러 객체들을 준비 페이지 컨트롤러도 MemberDao 처럼 ContextLoaderListener 에서 준비하자 > spms.listeners.ContextLoaderListener ```java public void contextInitialized(ServletContextEvent event) { try { ServletContext sc = event.getServletContext(); InitialContext initialContext = new InitialContext(); DataSource ds = (DataSource)initialContext.lookup( "java:comp/env/jdbc/studydb"); MemberDao memberDao = new MemberDao(); memberDao.setDataSource(ds); //sc.setAttribute("memberDao", memberDao); sc.setAttribute("/auth/login.do", new MemberLogInController().setMemberDao(memberDao)); sc.setAttribute("/auth/logout.do", new MemberLogOutController()); sc.setAttribute("/member/list.do", new MemberListController().setMemberDao(memberDao)); sc.setAttribute("/member/add.do", new MemberAddController().setMemberDao(memberDao)); sc.setAttribute("/member/update.do", new MemberUpdateController().setMemberDao(memberDao)); sc.setAttribute("/member/delete.do", new MemberDeleteController().setMemberDao(memberDao)); } catch(Throwable e) { e.printStackTrace(); } } ``` ###### 페이지 컨트롤러 객체를 준비 페이지 컨트롤러 객체를 생성하고 나서 MemberDao가 필요한 객체에 대해서는 세터 메소드를 호출하여 주입해준다. ```java new MemberLogInController().setMemberDao(memberDao) ``` 이렇게 생성된 페이지 컨트롤러를 ServletContext에 저장한다. 단, 저장할 때 서블릿 요청 URL을 키(key)로 하여 저장했음을 주의하자. 프론트 컨트롤러에서 ServletContext에 보관된 페이지 컨트롤러를 꺼낼 때 이 서블릿 요청 URL을 사용할 것이다. ```java sc.setAttribute("/auth/login.do", new MemberLogInController().setMemberDao(memberDao)); ``` #### 프론트 컨트롤러의 변경 페이지 컨트롤러 객체를 ContextLoaderListener에서 준비했기 때문에 프론트컨트롤러를 변경해야 한다. > spms.servlets.DispatcherServlet ```java protected void service( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html; charset=UTF-8"); String servletPath = request.getServletPath(); try{ ServletContext sc = this.getServletContext(); // 페이지 컨트롤러에게 전달할 Map 객체를 준비한다. HashMap<String,Object> model = new HashMap<String,Object>(); model.put("session", request.getSession()); Controller pageController = (Controller) sc.getAttribute(servletPath); if("/member/add.do".equals(servletPath)){ if (request.getParameter("email") != null) { model.put("member", new Member() .setEmail(request.getParameter("email")) .setPassword(request.getParameter("password")) .setName(request.getParameter("name"))); } } else if("/member/update.do".equals(servletPath)){ if(request.getParameter("email") != null){ model.put("member", new Member() .setNo(Integer.parseInt(request.getParameter("no"))) .setEmail(request.getParameter("email")) .setName(request.getParameter("name"))); } else{ model.put("no", new Integer(request.getParameter("no"))); } } else if("/member/delete.do".equals(servletPath)){ model.put("no", new Integer(request.getParameter("no"))); } else if("auth/login.do".equals(servletPath)){ if (request.getParameter("email") != null) { model.put("loginInfo", new Member() .setEmail(request.getParameter("email")) .setPassword(request.getParameter("password"))); } } ``` MemberDao 객체는 더 이상 Map객체에 담을 필요가 업어서 제거했다. ```java model.put("memberDao", sc.getAttribute("memberDao")); ``` ###### ServletContext 페이지 컨트롤러 꺼내기 페이지 컨트롤러는 ServletContext 보관소에 저장되어 있다. 이 보관소에서 페이지 컨트롤러를 꺼낼 때는 서블릿 URL을 사용한다 ```java Controller pageController=(Controller)sc.getAttribute(servletPath); ``` ###### 조건문 변경 if~else 조건문에서 페이지 컨트롤러가 사용할 데이터를 준비하는 부분을 제외하고는 모두 제거했다. #### 인터페이스를 활용하여 공급처를 다변화 하자 실무에서는 오라클을 사용할 수도 있고, MySQL이나 MS-SQL을 사용할 수도 있다. 그렇게되면 각데이터베이스에 맞춰 DAO클래스를 준비해야 한다. 문제는 데이터베이스를 바꿀 때마다 DAO 클래스를 사용하는 코드도 변경해야 하기 때문에 여간 번거로운 것이 아니다. 바로 이런 경우에 인터페이스를 활용하면 손쉽게 해결할 수 있다. 의존객체를 사용할 때 구체적으로 클래스 이름을 명시하는 대신에 인터페이스를 사용하면, 그 자리에 다양한 구현체(인터페이스를 구현한 클래스)를 놓을 수 있다. 즉 인터페이스라는 문법으로 DAO가 갖춰야 할 규격을 정의하고, 그 규격을 준수하는 클래스라면 어떤 클래스를 상속받았는지 따지지 않고 허용하는 것이다. #### MemberDao 인터페이스 정의 MemberDao에 인터페이스를 적용해 보자 지금까지 사용했던 기존의 MemberDao 클래스를 MySqlMemberDao 로 변경한 후 MemberDao 인터페이스를 생성하자 > spms.dao.MemberDao 인터페이스 ```java package spms.dao; import java.util.List; import spms.vo.Member; public interface MemberDao { List<Member> selectList() throws Exception; int insert(Member member) throws Exception; int delete(int no) throws Exception; Member selectOne(int no) throws Exception; int update(Member member) throws Exception; Member exist(String email, String password) throws Exception; } ``` ###### MySqlMemberDao 클래스를 MemberDao 규격에 맞추기 MySqlMemberDao 클래스를 MemberDao 인터페이스를 구현하도록 변경해야 한다. > spms.dao.MySqlMemberDao 클래스 ```java public class MySqlMemberDao implements MemberDao{} ``` ###### ContextLoaderListener 클래스 변경 MemberDao는 이제 클래스가 아니므로, MemberDao 객체의 준비를 담당했던 ContextLoadListener 클래스를 변경하자 > spms.listeners.ContextLoaderListener 클래스 ```java - MemberDao memberDao = new MemberDao(); + MySqlMemberDao memberDao = new MySqlMemberDao(); ``` 이제 MemberDao는 인터페이스이기 때문에 인스턴스를 생성할 수 없으므로 그 코드를 제거했고 대신 MemberDao 인터페이스를 구현한 MySqlMemberDao 객체를 생성했다. 즉, 페이지 컨트롤러에 주입되는것은 바로 MySqlMemberDao 객체가 되는 것이다. #### 정리 `의존성 주입` 기법으로 의존 객체를 관리하는 방법에 대해 알아보았지만 아직 개선할 점들은 뭐가 있을까? DispatcherServlet의 경우 페이지 컨트롤러가 추가될 때마다 조건문을 변경해야하는 문제도 있을것이고, ContextLoaderListener도 Dao나 페이지 컨트롤러가 추가될 때마다 변경해야 한다. ### 리플랙션 API를 이용하여 프론트 컨트롤러 개선하기 지금까지 작업한 프론트컨트롤러는 안타깝지만 페이지 컨트롤러를 추가할 때마다 코드를 변경해야 한다. 특히 매개변수 값을 받아서 VO객체를 생성하는 부분에 많은 손이 간다. 작성했던 코드를 통해 살펴보자 > spms.servlets.DispatcherServlet 의 일부분 ```java if ("/member/add.do".equals(servletPath)) { if (request.getParameter("email") != null) { model.put("member", new Member() .setEmail(request.getParameter("email")) .setPassword(request.getParameter("password")) .setName(request.getParameter("name"))); } } ``` 위 코드는 페이지 컨트롤러 MemberAddController 를 위해서 신규 회원 등록에 필요한 데이터를 준비하는 코드다. 사용자가 입력한 매개변수 값으로부터 Member 객체를 생성한 후 Map객체에 저장한다. 거기에 MemberUpdateController 를 위해서는 또 다른 코드가 필요하고 나머지들도 다 마찬가지로 매개변수값에 대해 이런식으로 VO객체를 준비하게 되면, 데이터를 사용하는 페이지 컨트롤러를 추가할 때 마다 계속 프론트컨트롤러를 변경해야 하는 문제가 발생하고, 이는 자연적으로 유지보수를 매우매우매우매우 불편하고 어렵게 만든다 > 바로 이런 문제를 개선하기 위해 리플렉션 API를 활용하여 인스턴스를 자동생성하고, 메소드를 자동으로 호출하는 방법을 배워보자 #### 신규회원정보 추가 자동화 신규회원 정보를 추가할 때의 시나리오를 살펴보자 지금까지와 다른 점은 데이터를 준비하는 부분을 자동화하는 것이다. 1. 웹브라우저는 회원등록을 요청하고, 사용자가 입력한 매개변수 값을 서블릿에 전달한다. 2. 프론트컨트롤러 `DispatcherServlet`은 회원 등록을 처리하는 페이지 컨트롤러에게 어떤 데이터가 필요한지 물어고, 페이지 컨트롤러 `MemberAddController`는 작업하는 데 필요한 데이터의 이름과 타입 정보를 담은 배열을 리턴한다. 3. 프론트 컨트롤러는 `ServletRequestDataBinder`를 이용하여, 요청 매개변수로부터 페이지 컨트롤러가 원하는 형식의 값 객체(예:Member, Integer, Date등)을 만든다. 4. 프론트 컨트롤러는 `ServletRequestDataBinder`가 만들어 준 값 객체를 Map에 저장한다. 5. 프론트 컨트롤러는 페이지 컨트롤러 `MemberAddController`를 실행하고, 페이지 컨트롤러의 `execute()`를 호출할 때, 값이 저장된 Map 객체를 매개변수로 너긴다. #### DataBinding 인터페이스 정의 위의 실행 시나리오에서 프론트 컨트롤러가 페이지 컨트롤러를 실행하기 전에 원하는 데이터가 무엇인지 묻는다고 했따. 이것에 대해 호출규칙을 정의해 보자 프론트 컨트롤러 입장에서는 이 규칙을 준수하는 페이지 컨트롤러를 호출할 때만 VO객체를 준비하면 된다. > spms.bind 패키지를 새로 생성하고 DataBinding 인터페이스를 생성하자 ```java package spms.bind; public interface DataBinding { Object[] getDataBinders(); } ``` 페이지 컨트롤러 중에서 클라이언트가 보낸 데이터가 필요한 경우 이 DataBinding 인터페이스를 구현한다. getDataBinders()의 반환값은 데이터의 이름과 타입 정보를 담은 Object의 배열이다. 여기서 배열을 작성하는 형식은 다음과 같다. ```java new Object[]{"데이터이름", 데이터타입, "데이터이름", 데이터타입, ...} ``` 데이터 이름과 타입(Class객체)이 한쌍으로 순서대로 오도록 작성한다. 물론 짝수가 되겠찌 #### 페이지 컨트롤러의 DataBinding 구현 클라이언트가 보낸 데이터를 사용하는 페이지 컨트롤러는 MemberAddController, MemberUpdateController, MemberDeleteController, LogInController 다. 이중 실행 시나리오에서 예로 살펴본 ADD 부터 인터페이스를 적용해보자 > spms.controls.MemberAddController 클래스 ```java package spms.controls; import java.util.Map; import spms.bind.DataBinding; import spms.dao.MemberDao; import spms.dao.MySqlMemberDao; import spms.vo.Member; // 의존 객체 주입을 위해 인스턴스 변수와 셋터 메서드 추가 //- 또한 의존 객체를 꺼내는 기존 코드 변경 public class MemberAddController implements Controller, DataBinding { MemberDao memberDao; public MemberAddController setMemberDao(MemberDao memberDao) { this.memberDao = memberDao; return this; } public Object[] getDataBinders(){ return new Object[]{ "member", spms.vo.Member.class }; } @Override public String execute(Map<String, Object> model) throws Exception { Member member=(Member)model.get("member"); if (model.get("member") == null) { // 입력폼을 요청할 때 return "/member/MemberForm.jsp"; } else { // 회원 등록을 요청할 때 memberDao.insert(member); return "redirect:list.do"; } } } ``` ###### DataBinding 인터페이스 선언 MemberAddController 는 클라이언트가 보낸 데이터를 프론트 컨트롤러로부터 받아야 하기 때문에, 위에서 정의한 규칙에 따라 DataBinding 인터페이스를 구현한다. ```java public class MemberAddController implements Controller, DataBinding{} ``` ###### getDataBinders() 메소드 구현 DataBinding 인터페이스를 구현한다고 선언했으니 getDataBinders()메소드를 구현해야 한다. MemberAddController 가 원하는 데이터는 사용자가 회원 등록 폼에 입력한 이름, 이메일, 암호값이다. 이 함수의 반환값, Obejct배열을 살펴보면~~ 그 의미는 클라이언트가 보낸 매개변수 값을 Member인스턴스에 담아서 "member" 라는 이름으로 Map 객체에 저장해 달라는 뜻이다. ```java public Object[] getDataBinderS(){ return new Object[]{ "member", spms.vo.Member.class }; } ``` 프론트 컨트롤러는 Object 배열에 지정된 대로 Member 인스턴스를 준비하여 Map 객체에 저장하고, execute()를 호출할 때 매개변수로 이 Map 객체를 넘길 것이다. ###### execute() 메소드 기존의 excute()에 비교해 조건문이 약간 달려졌다. 이전 코드에서는 Map 객체에 Member 가 들어있는지 없는지에 따라 작업을 분기했었는데 > 이전코드 ```java if(model.get("member") == null){ ... }else{ ... } ``` 이제부터는 getDataBinders()에서 지정한 대로 프론트 컨트롤러가 VO객체를 무조건 생성할 것이기 때문에 Member가 있는지 여부로 판단해서는 안되고, 대신 Member에 이메일이 들어 있는지로 여부를 검사한 것이다. > 바뀐 코드 ```java Member member (Member)model.get("member"); if(member.getEmail()==null){ ... }else{ ... } ``` > 클라이언트에서 데이터를 보내지 않는 MemberListController와 LogOutController를 빼고 나머지 페이지 컨트롤러들도 > DataBinding 인터페이스를 구현하자 #### 프론트컨트롤러의 변경 페이지 컨트롤러를 변경했으니, 프론트컨트롤러도 그에 맞게 변경해야 한다. > spms.servlets.DispathcerServlet ```java package spms.servlets; import java.io.IOException; import java.util.HashMap; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import spms.bind.DataBinding; import spms.bind.ServletRequestDataBinder; import spms.controls.Controller; // DataBinding 처리 @SuppressWarnings("serial") @WebServlet("*.do") public class DispatcherServlet extends HttpServlet { @Override protected void service( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html; charset=UTF-8"); String servletPath = request.getServletPath(); try { ServletContext sc = this.getServletContext(); // 페이지 컨트롤러에게 전달할 Map 객체를 준비한다. HashMap<String,Object> model = new HashMap<String,Object>(); model.put("session", request.getSession()); Controller pageController = (Controller) sc.getAttribute(servletPath); if (pageController instanceof DataBinding) { prepareRequestData(request, model, (DataBinding)pageController); } // 페이지 컨트롤러를 실행한다. String viewUrl = pageController.execute(model); // Map 객체에 저장된 값을 ServletRequest에 복사한다. for (String key : model.keySet()) { request.setAttribute(key, model.get(key)); } if (viewUrl.startsWith("redirect:")) { response.sendRedirect(viewUrl.substring(9)); return; } else { RequestDispatcher rd = request.getRequestDispatcher(viewUrl); rd.include(request, response); } } catch (Exception e) { e.printStackTrace(); request.setAttribute("error", e); RequestDispatcher rd = request.getRequestDispatcher("/Error.jsp"); rd.forward(request, response); } } private void prepareRequestData(HttpServletRequest request, HashMap<String, Object> model, DataBinding dataBinding) throws Exception { Object[] dataBinders = dataBinding.getDataBinders(); String dataName = null; Class<?> dataType = null; Object dataObj = null; for (int i = 0; i < dataBinders.length; i+=2) { dataName = (String)dataBinders[i]; dataType = (Class<?>) dataBinders[i+1]; dataObj = ServletRequestDataBinder.bind(request, dataType, dataName); model.put(dataName, dataObj); } } } ``` ###### service()메소드 드디어 service()메소드에서 조건문이 사라졌다. 이제부터는 매개변수 값을 사용하는 페이지 컨트롤러를 추가하더라도 조건문을 삽입할 필요가 없다. 대신 데이터 준비를 자동으로 수행하는 `prepareRequestData()`를 호출한다. ```java if(pageController instanceof DataBinding){ prepareRequestData(request, model, (DataBinding)pageController); } ``` 매개변수 값이 필요한 페이지 컨트롤러에 대해 DataBinding 인터페이스를 구현하기로 규칙을 정했다. 따라서 DataBiding을 구현했는지 여부를 검사하여, 해당 인터페이스를 구현한 경우에만 prepareRequestData()를 호출하여 페이지 컨트롤러를 위한 데이터를 준비했다 ###### prepareRequestData()메소드 prepareRequestData()에서 어떤 방법으로 데이터를 준비하는지 살펴보자 먼저 페이지 컨트롤러에게 필요한 데이터가 무엇인지 묻는다 ```java Object[] dataBinders = dataBinding.getDataBinders(); ``` getDataBinders()메소드가 반환하는 것은 ["데이터이름",데이터타입....]으로 나열된 Object 배열일 것이다. 배열을 반복하기 전에 배열에서 꺼낸 값을 보관할 임시 변수를 준비하고, 데이터 이름(String), 데이터 타입(Class), 데이터 객체(Object)를 위한 참조 변수다. ```java String dataName = null; Class<?> dataType = null; Object dataObj = null; ``` 데이터 이름과 데이터 타입을 꺼내기 쉽게 2씩 증가하면서 반복문을 돌린다. ```java for (int i = 0; i < dataBinders.length; i+=2) { dataName = (String)dataBinders[i]; dataType = (Class<?>) dataBinders[i+1]; } ``` for문 안을 들여다보면, ServletRequestDataBinder 클래스의 bind() 메소드를 호출하고 있따. 이 메소드는 dataName과 일치하는 요청 매개변수를 찾고 dataType 을 통해 해당 클래스의 인스턴스를 생성한다. 찾은 매개변수 값을 인스턴스에 저장하며 그 인스턴스를 반환한다. ```java dataObj = ServletRequestDataBinder.bind(request, dataType, dataName); model.put(dataName, dataObj); ``` bind() 메소드가 반환한 데이터 객체는 Map 객체에 담는다. 이 작업을 통해 페이지 컨트롤러가 사용할 데이터를 준비하는 것이다. #### ServletRequestDataBinder 클래스 생성 ServletRequestDataBinder 클래스는 클라이언트가 보낸 매개변수 값을 자바 객체에 담아 주는 역할을 수행한다. > spms.bind 패키지에 ServletRequestDataBinder 클래스를 생성하다 ```java package spms.bind; import java.lang.reflect.Method; import java.util.Date; import java.util.Set; import javax.servlet.ServletRequest; public class ServletRequestDataBinder { public static Object bind( ServletRequest request, Class<?> dataType, String dataName) throws Exception { if (isPrimitiveType(dataType)) { return createValueObject(dataType, request.getParameter(dataName)); } Set<String> paramNames = request.getParameterMap().keySet(); Object dataObject = dataType.newInstance(); Method m = null; for (String paramName : paramNames) { m = findSetter(dataType, paramName); if (m != null) { m.invoke(dataObject, createValueObject(m.getParameterTypes()[0], request.getParameter(paramName))); } } return dataObject; } private static boolean isPrimitiveType(Class<?> type) { if (type.getName().equals("int") || type == Integer.class || type.getName().equals("long") || type == Long.class || type.getName().equals("float") || type == Float.class || type.getName().equals("double") || type == Double.class || type.getName().equals("boolean") || type == Boolean.class || type == Date.class || type == String.class) { return true; } return false; } private static Object createValueObject(Class<?> type, String value) { if (type.getName().equals("int") || type == Integer.class) { return new Integer(value); } else if (type.getName().equals("float") || type == Float.class) { return new Float(value); } else if (type.getName().equals("double") || type == Double.class) { return new Double(value); } else if (type.getName().equals("long") || type == Long.class) { return new Long(value); } else if (type.getName().equals("boolean") || type == Boolean.class) { return new Boolean(value); } else if (type == Date.class) { return java.sql.Date.valueOf(value); } else { return value; } } private static Method findSetter(Class<?> type, String name) { Method[] methods = type.getMethods(); String propName = null; for (Method m : methods) { if (!m.getName().startsWith("set")) continue; propName = m.getName().substring(3); if (propName.toLowerCase().equals(name.toLowerCase())) { return m; } } return null; } } ``` 이 클래스는 외부에서 호출할 수 있는 한개의 public 메소드와 내부에서 사용할 세 개의 private메소드를 가지고 있다. 이 클래스에 있는 메소드 모두 static으로 선언했다. 즉 인스턴스를 생성할 필요가 없이 클래스 이름으로 바로 호출하겠다는 의도다. 이렇게 특정 인스턴스의 값을 다루지 않는다면 static으로 선언하여 클래스 메소드로 만드는 것이 좋다. ###### bind()메소드 프론트 컨트롤러에서 호출하는 메소드다. 요청 매개변수의 값과 데이터이름, 데이터 타입을 받아서 데이터객체(예:Member, String, Date, Integer 등)를 만드는 일을 한다. ```java public static Object bind(ServletRequest request, Class<?> dataType, String dataName) throws Exception{ ... return dataObject; } ``` 이 메소드의 첫 번째 명령문은 dataType이 기본 타입인지 아닌지 검사하는 일이다. 만약 기본타입이라면 즉시 객체를 생성하여 반환할 것이다. ```java if (isPrimitiveType(dataType)) { return createValueObject(dataType, request.getParameter(dataName)); } ``` > `isPrimitiveType()` 메소드는 int,long,float,double,boolean,java.util.Date, java.lang.String 타입에 대해 > 기본타입으로 간주하며 treu를 반환하는 메소드다. > `createValueObject()`메소드는 기본 타입의 객체를 생성할 때 호출한다. > 요청 매개변수의 값으로부터 String이나 Date등의 기본타입 객체를 생성한다. Member 클래스처럼 dataType이 기본타입이 아닌 경우는 요청 매개변수의 이름과 일치하는 세서 메소드를 찾아서 호출한다. 먼저 요청 매개변수의 이름 목록을 얻는다. ```java Set<String> paramNames = request.getParameterMap().ketSet(); ``` request.getParameterMap()은 매개변수의 이름과 값을 맵 객체에 담아서 반환한다. 우리가 필요한것은 매개변수의 이름이기 때문에 Map의 keySet()을 호출하여 이름 목록만 꺼낸다. 그리고 값을 저장할 객체를 생성하고. Class의 newInstance()를 사용하면 해당 클래스의 인스턴스를 얻을 수 있따. new 연산자를 사용하지 않고도 아래 코드처럼 이런 식으로 객체를 생성할 수 있다. ```java Object dataObject = dataTyep.newInstance(); ``` 요청 매개변수의 이름 목록이 준비되었으면 for 반복문을 실행gkrh, 데이터 타입 클래스에서 매개변수 이름과 일치하는 프로퍼티(세터메소드)를 찾느다 ```java m = findSetter(dataType, paramName); ``` > `findSetter()` 는 데이터타입(Class)과 매개변수 이름(String)을 주면 세터 메소드를 찾아서 반환하는 메소드 이다. 세터 메소드를 찾았으면 이전에 생성한 dataObject에 대해 호출한다. ```java if(m != null){ m.invoke(dataObject, ....); } ``` 세터 메소드를 호출할 때 요청 매개변수의 값을 그 형식에 맞추어 넘긴다. ```java createValueObject( m.getParameterTypes()[0], request.getParameter(paramName) ) ``` createValueObject() 메소드는 앞에서 설명한 바와 같이, 요청 매개변수의 값을 가지고 기본 타입의 객체를 만들어 준다. 이렇게 요청 매개변수의 개수만큼 반복하면서, 데이터 객체(예:Member)에 대해 값을 할당한다. ###### createValueObject() 메소드 기본타입의 경우 세터메소드가 없기 때문에 값을 할당할 수 없고, 보통 생성자를 호출할 때 값을 할당한다. 그래서 createValueObject()메소드를 만든 것이다. 이 메소드는 세터로 값을 할당할 수 없는 기본타입에 대해 객체를 생성하는 메소드이다. ###### findSetter() 메소드 findSetter()는 클래스(type)을 조사하여 주어진 이름(name)과 일치하는 세터 메소드를 찾는다. ```java private static Method findSetter(Class<?> type, String name){} ``` 제일 먼저 데이터 타입에서 메소드 목록을 얻는다. ```java Method[] methods = type.getMethods(); ``` 메소드 목록을 반복하여 세터메소드에 대해서만 작업을 수행한다. 만약 메소드 이름이 "set"으로 시작하지 않는다면 무시한다. ```java for(Method m : methods){ if(!m.getName().startsWith("set")) continue; } ``` 세터 메소드일 경우 요청매개변수의 이름과 일치하는지 검사한다. 단 대소문자를 구분하지 않기 위해 모두 소문자로 바꾼 다음에 비교한다. 그리고 세터 메소드의 이름에서 "set"은 제외한다 ```java propName = m.getName().substring(3); if (propName.toLowerCase().equals(name.toLowerCase())) { return m; } ``` 마지막으로 일치하는 세터메소드를 찾았다면 즉시 반환한다. > 이제 서버를 재시작한 후 기능을 테스트 해보자 #### 리플렉션 API 이번 절에서 가장 중요한 내용은 `리플렉션 API`이다. 이 도구가 없다면 클래스에 어떤 메소드가 있는지, 메소드의 이름은 무엇인지, 클래스의 이름은 무엇인지 알 수가 없다. 사전적 정의처럼 클래스나 메소드의 내부 구조를 들여다 볼 때 사용하는 도구라는 뜻으로 이번에 사용한 리플렉션 API를 정리해보면 다음 표와 같다 | 메소드 | 설명 | |--------|--------| | Class.newInstance() | 주어진 클래스의 인스턴스를 생성 | | Class.getName() | 클래스의 이름을 반환 | | Class.getMethods() | 클래스에 선언된 모든 public메소드의 목록을 배열로 반환 | | Method.invoke() | 해당 메소드를 호출 | | Method.getParameterTypes() | 메소드의 매개변수 목록을 배열로 반환 | ### 프로퍼티를 이용한 객체 관리 리플렉션 API를 사용하여 프론트 컨트롤러를 개선해서 이제는 페이지 컨트롤러를 추가하더라도 프론트 컨트롤러를 손댈 필요가 없어졌다. 하지만 ContextLoaderListener는 변경해야 한다. 왜냐하면 이 리스너에서 페이지 컨트롤러 객체를 생성하기 때문이다. 코드를 통해 살펴보자 > ContextLoaderListener ```java public void contextInitialized(ServletContextEvent event) { try { ServletContext sc = event.getServletContext(); InitialContext initialContext = new InitialContext(); DataSource ds = (DataSource)initialContext.lookup( "java:comp/env/jdbc/studydb"); MySqlMemberDao memberDao = new MySqlMemberDao(); memberDao.setDataSource(ds); sc.setAttribute("/auth/login.do", new LogInController().setMemberDao(memberDao)); sc.setAttribute("/auth/logout.do", new LogOutController()); sc.setAttribute("/member/list.do", new MemberListController().setMemberDao(memberDao)); sc.setAttribute("/member/add.do", new MemberAddController().setMemberDao(memberDao)); sc.setAttribute("/member/update.do", new MemberUpdateController().setMemberDao(memberDao)); sc.setAttribute("/member/delete.do", new MemberDeleteController().setMemberDao(memberDao)); } } ``` 페이지 컨트롤러 뿐만 아니라 DAO를 추가하는 경우에도 ContextLoaderListener 클래스에 코드를 추가해야 한다. > 이번에는 바로 이부분, 객체를 생성하고 의존객체를 주입하는 부분을 자동화 해보자 #### 프로퍼티 파일 작성 > WebContent/WEB-INF 폴더에 application-context.properties 파일 생성 ``` jndi.dataSource-java:comp/env/jdbc/studydb memberDao=spms.dao.MySqlMemberDao /auth/login.do=spms.controls.LogInController /auth/logout.do=spms.controls.LogOutController /member/list.do=spms.controls.MemberListController /member/add.do=spms.controls.MemberAddController /member/update.do=spms.controls.MemberUpdateController /member/delete.do=spms.controls.MemberDeleteController ``` 이 프로퍼티 파일은 ApplicationContext에서 객체를 준비할 때 사용한다.' 객체에 따라 준비하는 방법이 다르므로 몇 가지 작성 규칙을 정의 했다. 이 규칙에 대해서 알아보자 ( 물론 이 규칙은 우리가 만드는 미니 프레임워크에만 해당한다~ ) ###### 톰캣 서버에서 제공하는 객체 DataSource 처럼 톰캣 서버에서 제공하는 객체는 ApplicationContext에서 생성할 수 없다. 대신 InitialContext를 통해 해당 객체를 얻어야 한다. ```java jndi.{객체이름}={JNDI이름} ``` 프로퍼티의 키(key)는 `jndi.`와 객체 이름을 결합하여 작성한다. 프로퍼티의 값(value)은 톰캣 서버에 등록된 객체의 JNDI 이름이다. 앞의 프로퍼티 파일에서 첫 번째 줄의 내용이 톰캣 서버가 제공하는 DataSource객체에 대한 것이다. ###### 일반객체 MemberDao와 같은 일반객체는 다음의 규칙으로 설정한다. ```java {객체이름}={패키지 이름을 포함한 클래스 이름} ``` 프로퍼티의 키는 객체를 알아보는 데 도움이 되는 이름을 사용한다. 단 다른 이름과 중복되어서는 안된다. 프로퍼티의 값은 패키지이름을 포함한 전체 클래스 이름(fully qualified class name)이어야 한다. 두 번째 줄이 여기에 해당하는 MemberDao를 설정하는 코드이다. #### 페이지 컨트롤러 객체 페이지 컨트롤러는 프론트 컨트롤러에서 찾기 쉽도록 다음의 규칙으로 작성한다. ```java {서블릿 URL}={패키지 이름을 포함한 클래스 이름} ``` 프로퍼티의 키는 서블릿 URL이다. 프론트 컨트롤러는 DispatcherServlet은 서블릿 URl을 이용하여 페이지 컨트롤러를 찾는다 ``` /auth/login.do=spms.controls.LogInController ``` #### ApplicationContext 클래스 ApplicationContext 클래스는 앞 절의 실습 시나리오에서 언급한 대로 프로퍼티 파일에 설정된 객체를 준비하는 일을 한다. > spms.context 패키지를 새로 생성한 후 spms.context패키지에 ApplicationContext 클래스를 생성 ```java package spms.context; import java.io.FileReader; import java.lang.reflect.Method; import java.util.Hashtable; import java.util.Properties; import javax.naming.Context; import javax.naming.InitialContext; // 프로퍼티 파일을 이용한 객체 준비 public class ApplicationContext { Hashtable<String,Object> objTable = new Hashtable<String,Object>(); public Object getBean(String key) { return objTable.get(key); } public ApplicationContext(String propertiesPath) throws Exception { Properties props = new Properties(); props.load(new FileReader(propertiesPath)); prepareObjects(props); injectDependency(); } private void prepareObjects(Properties props) throws Exception { Context ctx = new InitialContext(); String key = null; String value = null; for (Object item : props.keySet()) { key = (String)item; value = props.getProperty(key); if (key.startsWith("jndi.")) { objTable.put(key, ctx.lookup(value)); } else { objTable.put(key, Class.forName(value).newInstance()); } } } private void injectDependency() throws Exception { for (String key : objTable.keySet()) { if (!key.startsWith("jndi.")) { callSetter(objTable.get(key)); } } } private void callSetter(Object obj) throws Exception { Object dependency = null; for (Method m : obj.getClass().getMethods()) { if (m.getName().startsWith("set")) { dependency = findObjectByType(m.getParameterTypes()[0]); if (dependency != null) { m.invoke(obj, dependency); } } } } private Object findObjectByType(Class<?> type) { for (Object obj : objTable.values()) { if (type.isInstance(obj)) { return obj; } } return null; } } ``` ###### 객체의 보관 프로퍼티에 설정된 대로 객체를 준비하면, 객체를 저장할 보관소가 필요한데 이를 위해 해시테이블을 준비한다. 또한 해시 테이블에서 객체를 꺼낼(getter)메소드도 정의한다. ```java Hashtable<String,Object> objTable = new Hashtable<String,Object>(); public Object getBean(String key) { ``` ###### 프로퍼티 파일의 로딩 ApplicationContext 생성자가 호출되면 매개변수로 지정된 프로퍼티 파일의 내용을 로딩해야 한다. 이를 위해 java.util.Properties 클래스를 사용했다 ```java Properties props = new Properties(); props.load(new FileReader(propertiesPath)); ``` Properties는 `이름=값`형태로 된 파일을 다룰때 사용하는 클래스다. load()메소드는 FileReader를 통해 읽어들니 프로퍼티 내용을 키-값 형태로 내부 맵에 보관한다. ###### prepareObjects()메소드 프로퍼티 파일의 내용을 로딩했으면, 그에 따라 객체를 준비해야 한다. prepareObjects()가 바로 그 일을 수행하는 메소드로, 먼저 JNDI객체를 찾을 때 사용할 InitialContext를 준비한다. ```java Context ctx = new InitialContext(); ``` 그리고 반복문을 통해 프로퍼티에 들어있는 정보를 꺼내서 객체를 생성한다. ```java for (Object item : props.keySet()) {...} ``` Properties로부터 클래스 이름을 꺼내려며 키(key)를 알아야 한다. keySet()메소드는 Properties에 저장된 키 목록을 반환한다. 만약 프로퍼티의 키가 "jndi."로 시작한다면 객체를 생성하지 않고, InitialContext를 통해 얻는다. ```java if(key.startsWith("jndi.")){ objTable.put(key, ctx.lookup(value)); } ``` InitialContext의 lookup() 메소드는 JNDI 인터페이스를 통해 톰캣 서버에 등록된 객체를 찾는다. 그 밖의 객체는 Class.forName()을 호출해 클래스를 로딩하고, newInstance()를 사용하여 인스턴스를 생성한다. ```java else{ objTable.put(key, Class.forName(value).newInstance()); } ``` ###### injectDependency() 메소드 톰캣 서버로부터 객체를 가져오거나(예:DataSource) 직접 객체를 생성했으면(예:MemberDao), 이제는 각 객체가 필요로 하는 의존 객체를 할당해 줘야 한다. 이런일을 하는 메소드가 injectDependency() 다. ```java if (!key.startsWith("jndi.")) { callSetter(objTable.get(key)); } ``` 객체 이름이 "jndi."로 시작하는 경우 톰캣 서버에서 제공한 객체이므로 의존객체를 주입해서는 안되므로, 제외시켰다. 나머지 객체에 대해서는 세터 메소드를 호출한다. ###### callSetter() 메소드 callSetter()는 매개변수로 주어진 객체에 대해 세터 메소드를 찾아서 호출하는 일을 하며, 먼저 세터 메소드를 찾는다. ```java for (Method m : obj.getClass().getMethods()) { if (m.getName().startsWith("set")) { ``` 세터메소드를 찾았으면 세터 메소드의 매개변수와 타입이 일치하는 객체를 objTable에서 찾는다 ```java dependency = findObjectByType(m.getParameterTypes()[0]); ``` 의존 객체를 찾았으면, 세터 메소드를 호출한다. ```java if (dependency != null) { m.invoke(obj, dependency); } ``` ###### findObjectByType() 메소드 이 메소드는 세터 메소드를 호출할 때 넘겨줄 의존객체를 찾는 일을 하며, objTable에 들어있는 객체를 모두 뒤진다. ```java for(Object obj : objTable.values()){} ``` 만약 세터메소드의 매개변수 타입과 일치하는 객체를 찾았다면 그 객체의 주소를 리턴한다. ```java if (type.isInstance(obj)) { return obj; } ``` Class의 isInstance() 메소드는 주어진 객체가 해당 클래스 또는 인터페이스의 인스턴스인지 검사한다. #### ContextLoaderListener 변경 ApplicationContext를 만든 이유는 페이지 컨트롤러나 DAO가 추가되더라도 ContextLoaderListener를 변경하지 않기 위함이다. 정말 그게 가능하닞 확인해보자 > spms.listeners.ContextLoadListener 클래스를 변경한 소스다 ```java package spms.listeners; // 페이지 컨트롤러 객체 준비 import javax.naming.InitialContext; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; import javax.sql.DataSource; import spms.controls.LogInController; import spms.controls.LogOutController; import spms.controls.MemberAddController; import spms.controls.MemberDeleteController; import spms.controls.MemberListController; import spms.controls.MemberUpdateController; import spms.dao.MySqlMemberDao; @WebListener public class ContextLoaderListener implements ServletContextListener { static ApplicationContext applicationContext; public static ApplicationContext getApplicationContext(){ return applicationContext; } @Override public void contextInitialized(ServletContextEvent event) { try { ServletContext sc = event.getServletContext(); String propertiesPath=sc.getRealPath(sc.getInitParameter("contextConfigLocation")); applicationContext=new ApplicationContext(propertiesPath); } catch(Throwable e) { e.printStackTrace(); } } @Override public void contextDestroyed(ServletContextEvent event) {} } ``` 얼핏봐도 소스가 한결 간결해졌다. 그것 외에도 정말 중요한 것은 더이상 이제 더이상 이 클래스를 변경할 필요가 없다는 것이다. 페이지 컨트롤러나 DAO등을 추가할 때는 프로퍼티 파일에 그 클래스에 대한 정보를 한줄 추가하면 자동으로 그 객체가 생성된다 ###### 프로퍼티 파일의 경로 프로퍼티 파일이ㅡ 이름과 경로 정보도 web.xml 파일로부터 읽어 오게 처리했다. ServletContext의 getInitParameter()를 호출하여 web.xml에 설정된 매개변수 정보를 가져온다. ```java String propertiesPath=sc.getRealPath(sc.getInitParameter("contextConfigLocation")); ``` 그리고 ApplicationContext 객체를 생성할 때 생성자의 매개변수로 넘겨준다. ```java applicationContext = new ApplicationContext(propertiesPath); ``` 이렇게 생성한 ApplicationContext 객체는 프론트 컨트롤러에서 사용할 수 있게 ContextLoaderListenr의 클래스 변수 applicationContext에 저장된다 ###### getApplicationContet() 클래스 메소드 이 메소드는 ContextLoaderListerner에서 만든 ApplicationContext 객체를 얻을 때 사용하며, 당장 프론트 컨트롤러에서 사용해야 한다. 클래스 이름만으로 호출할 수 있게 static으로 선언했다 ```java public static ApplicationContext getApplicationContext(){ return applicationContext; } `` #### Wenb.xml 파일에 프로퍼티 경로 정보 설정 ContextLoaderListener 가 프로퍼티 파일을 찾을 수 있도록 web.xml 파일에 프로퍼티에 대한 파일 경로 정보를 설정하자 > web.xml 에 컨택스트 매개변수를 추가 ```xml <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/application-context.properties</param-value> </context-param> ``` #### DispatcherServlet 변경 > spms.servlets.DispatcherServlet ```java protected void service( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html; charset=UTF-8"); String servletPath = request.getServletPath(); try { - ServletContext sc = this.getServletContext(); + ApplicationContext ctx = ContextLoaderListener.getApplicationContext(); // 페이지 컨트롤러에게 전달할 Map 객체를 준비한다. HashMap<String,Object> model = new HashMap<String,Object>(); model.put("session", request.getSession()); - Controller pageController = (Controller) sc.getAttribute(servletPath); + Controller pageController = (Controller) ctx.getBean(servletPath); if (pageController == null){ throw new Exception("요청한 서비스를 찾을 수 없습니다.");ㅇ } if (pageController instanceof DataBinding) { prepareRequestData(request, model, (DataBinding)pageController); } ``` 변경된 소스를 살펴보면 ApplicationContext 를 도입하면서 ServletContext 를 제거했다. ```java - ServletContext sc = this.getServletContext(); + ApplicationContext ctx = ContextLoaderListener.getApplicationContext(); ``` 대신 ContextLoadListener의 getApplicationContext()를 호출하여 ApplicationContext 객체를 꺼냈다. 페이지 컨트롤러를 찾을 때도 ServletContext에서 찾이 않기 때문에 해당 코드를 역시 제거했다 ```java - Controller pageController = (Controller) sc.getAttribute(servletPath); + Controller pageController = (Controller) ctx.getBean(servletPath); ``` 대신 ApplicationContext의 getBean()을 호출해서 페이지 컨트롤러를 찾는다 만약 차지 못한다면 오류를 발생시킨다. ```java if (pageController == null){ throw new Exception("요청한 서비스를 찾을 수 없습니다.");ㅇ } ``` > ### 파일점검해보기 ### 어노테이션을 이용한 객체 관리 프로퍼티 파일을 이용해 DAO나 페이지컨트롤러 등을 관리해 봤는데, 예전보다는 DAO나 페이지 컨트롤러를 추가하더라도 손이 덜 가는 구조이지만, 그럼에도 이런 객체들을 추가할 때 마다 프로퍼티 파일에 한줄 추가해야 하는 약간의 번거로움이 남아있다. 이번 절에서는 이런 약간의 번거로움 마저도 없애보자. 이를 위해서 `어노테이션`을 사용하여 처리한다 > `어노테이션`은 컴파일이나 배포, 실행할 때 참조할 수 있는 아주 특별한 주석이다. > 어노테이션을 사용하면 클래스나 필드, 메소드에 대해 부가 정보를 등록할 수 있다. #### 어노테이션 활용 시나리오 1. 웹에플리케이션이 시작되면 서블릿 컨테이너는 ContextLoadListener에 대해 contextInitialized()를 호출한다. 2. contextInitialized()는 ApplicationContext를 생성한다. 생성자의 매개변수 값으로 프로퍼티 파일의 경로를 넘긴다. 3. ApplicationContext 생성자는 프로퍼티 파일을 로딩하여 내부 맵에 보관한다. 4. ApplicationContext 는 맵에 저장된 정보를 껕내 인스턴스를 생성하거나 또는 톰캣 서버에서 객체를 가져온다 5. 또한, 자바 classpath를 뒤져서 어노테이션이 붙은 클래스를 찾는다. 그리고 어노테이션에 지정된 정보에 따라 인스턴스를 생성한다. 6. 객체가 모두 준비되었으면, 각 객체에 대해 의존 객체를 찾아서 할당한다. 이전의 `프로퍼티`를 이용한 객체관리 시나리오와 같지만 중간에 어노테이션이 선언된 클래스를 탐색하는 부분이 추가되었다. #### 어노테이션 정의 이제 DAO나 페이지 컨트롤러에 붙일 어노테이션을 정의해보자 다음과 같이 클래스 선언에 붙일 @Component 어노테이션이고 어노테이션의 기본값은 객체 이름이다 > @Component 어노테이션의 사용 예 ```java @Component("memberDao") //어노테이션 class MemberDao{ ... } ``` > spms.annotation 패키지 생성후 Component 어노테이션 생성 ```java package spms.annotation; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy;; @Retention(RetentionPolicy.RUNTIME) public @interface Component { String value() default ""; } ``` 보다시피 어노테이션 문법은 인터페이스와 비슷하다. 단 interface 키워드 앞에 `@`가 붙는다. ```java public @interface Component { ``` 객체 이름을 저장하는 용도로 사용할 `value`라는 기본 속성을 정의했다. value속성은 값을 설정할 때 이름을 생략할 수 있는 특별한 기능이 있다. ```java String value() default ""; ``` 어노테이션의 속성을 선언하는 문법은 인터페이스에서 메소드를 선언하는 문법과 비슷하다. 그러나 인터페이스의 메소드와 달리 `기본값`을 지정할 수 있다. 속성 선언 다음에 오늘 `default`키워드가 기본값을 지정하는 문법이다. 즉 value 속성의 값을 지정하지 않으면 default로 지정한 값(예시에서는 빈문자열)이 할당되는 것이다 ###### 어노테이션 유지 정책 어노테이션을 정의할 때 잊지 말아야 할 것은 어노테이션의 유지 정책을 지정하는 것이다. 이것을 깜박 잊고 개발하다가 한참을 헤매는 개발자들도 많으니 유의하자! `어노테이션 유지 정책`이란 어노테이션 정보를 언제까지 유지할 것인지 설정하는 문법이다. ```java @Retention(RetentionPolicy.RUNTIME) ``` 앞의 코드는 `RUNTIME`으로 지정했기 때문에, 실행 중에도 언제든지 `@Componetn` 어노테이션의 속성값을 참조할 수 있다. 정책 | 설명 -----|----| RetentionPolicy.SOURCE | 소스 파일에서만 유지, 컴파일할 때 제거됨, 즉 클래스 파일에 어노테이션 정보가 남아 있지 않음 CLASS | 클래스 파일에 기록됨, 실행 시에는 유지되지 않음, 즉 실행 중에서는 클래스에 기록된 어노테이션 값을 꺼낼 수 없음(기본정책) RUNTIME | 클래스 파일에 기록됨. 실행 시에도 유지됨. 즉, 실행 중에 클래스에 기록된 어노테이션 값을 참조할 수 있음 어노테이션 유지 정책을 지정하지 않으면 기본으로 `RetentionPolicy.CLASS` 가 된다. #### 어노테이션 적용 어노테이션을 정의했으면 이제 DAO나 페이지 컨트롤러에 적용해 보자 (MySqlMemberDao 파일부터) > spms.dao.MySqlMemberDao 클래스 ```java @Component("memberDao") public class MySqlMemberDao implements MemberDao { ``` > 나머지 컨트롤러들도 어노테이션을 적용하자 #### 프로퍼티 파일 변경 어노테이션을 적용했다고 프로퍼티 파일이 필요없는 것은 아니다. 우리가 만든 클래스에 대해서는 어노테이션을 적용할 수 있지만 **DataSource와 같은 톰캣 서버가 제공하는 객체에는 어노테이션을 적용할 수 없다. 그래서 프로퍼티를 이용한 객체 관리 방법은 그대로 유지**해야 한다 톰캣 서버가 관리하는 JNDI객체나 외부 라이브러리에 들어있는 개체는 우리가 만든 어노테이션을 적용할 수 없기 때문에 프로퍼티 파일에 등록해야 한다 #### ApplicationContext 변경 `@Component` 어노테이션이 붙은 클래스에 대해서도 객체를 생성하도록 ApplicationContext를 변경하자 > spms.context.ApplicationContext 클래스를 다음과 같이 변경하자 ```java ``` ___ > 궁금한점 1. `import javax.servlet.http.*` 형식으로 사용 가능한가? 2. 소스작성간 뭘 import 해야하는지는 소스 작성후에 에러 메시지를 통해서 아는 방법 말고 다른 방법은 외우는것 말고는 없는지? 3. 이클립스에서 자동생성안되는 것들은 외워서 작성해야하는지? 가령 `javax.servlet.RequestDispatcher` <file_sep>/Front-End/Webfont/README.md ## 웹폰트 Guide ### 1) 웹폰트 기본 개념 1. 인터넷에 떠도는 폰트파일들을 보면 기본적으로 eot, woff, otf 등이 존재한다. > 이는 브라우져, 혹은 OS 별로 지원하는 폰트의확장자로 기본적으로 eot, otf, woff등은 지원을 해줘야 한다. > woff2 같은 경우는 woff2 의 확장버전으로 압축율이 더 좋으므로 보통 woff 보다 상단에 선언한다. 2. 확장자별 지원범위 | 확장자 | IE | 파폭 | 크롬 | 사파리 | 오페라 |--------|--------|----|---|---| | .eot |ie4 ~ ie8 | X | X | X | X | | .woff |ie9 ~ | 지원 | 지원 | 지원 | 지원 | **otf 파일은 OS X 에서 사용** ### 2) CDN 1. 기본적인 웹폰트는[Google Webfont](https://www.google.com/fonts)에서 지원여부 확인가능 - 한글 폰트의 경우 earlyaccess 항목 참고 - 구글 CDN URl ```css @ import url(http://fonts.googleapis.com/earlyaccess/nanumbrushscript.css); @ import url(http://fonts.googleapis.com/earlyaccess/nanumgothic.css); @ import url(http://fonts.googleapis.com/earlyaccess/nanumgothiccoding.css); @ import url(http://fonts.googleapis.com/earlyaccess/nanummyeongjo.css); @ import url(http://fonts.googleapis.com/earlyaccess/nanumpenscript.css); ``` 2. 그외 CDN은[jsdelivr](http://www.jsdelivr.com/) 참조 - 사용자가 서브셋 제거 버전이나 임의로 올린 버전들이 있다.(쉽게말해 공식지원이 아님) - 공식지원이 아닌만큼 커스텀 된 경량화 버전등이 존재할 수 있음 (존재여부는 `jsdelivr` 사이트에서 검색) - jsdelivr CDN URl ```css 나눔고딕 //cdn.jsdelivr.net/font-nanum/1.0/nanumgothic/nanumgothic.css 나눔바른고딕 //cdn.jsdelivr.net/font-nanum/1.0/nanumbarungothic/nanumbarungothic.css 나눔고딕(코딩) : //cdn.jsdelivr.net/font-nanum/1.0/nanumgothiccoding/nanumgothiccoding.css 나눔명조 //cdn.jsdelivr.net/font-nanum/1.0/nanummyeongjo/nanummyeongjo.css 나눔펜(손글씨) //cdn.jsdelivr.net/font-nanum/1.0/nanumpenscript/nanumpenscript.css 나눔브러시(손글씨) //cdn.jsdelivr.net/font-nanum/1.0/nanumbrushscript/nanumbrushscript.css ``` 3. 응답장애시 CDN 서버에 영향을 받고 속도가 느리므로 비추천 ### 3) 서브셋 1. 서브셋이란? > 웹폰트에는 서브셋이라는 개념이 있으며, 서브셋은 말 그대로 특정폰트의 하위 집합을 말한다. 따라서, 필요한 하위 집합만을 추려서 용량을 엄청 줄일 수 있다. (기본적으로 구글웹폰트 역시 서브셋을 지원한다.) 2. 서브셋 지정하기 - 완성형일 경우 `엄청난 양의 한글`이 필요하지만, 사실 모든 문자셋을 사용할 경우는 극히 드물다. - [KS X 1001 표준](https://ko.wikipedia.org/wiki/KS_X_1001)에는 자주 쓰이는 한글 2,350자를 정의하고 있는데 이 한글만 추려내면 용량을 많이 줄일 수 있다. 3. 서브셋 프로그램 - [서브셋 폰트메이커](http://opentype.jp/subsetfontmk.htm) - [WOFF 컨버터](http://opentype.jp/woffconv.htm) ### 4) 사용법 #### font.css > 보통 아래와 같이 weight로 구분하여 사용한다. > **단 IE8에서 weight 값이 제대로 렌더링 되지 않는 경우가 있는데 이때는 각 weight 별로 별도의 `@font-face`를 만들어서 사용한다** > ** 예) Noto Sans Regular, Noto Sans Medium .....** ```css @charset "utf-8"; @font-face { font-family: 'Noto Sans'; //font-family css 로 사용할 이름을 지정(마음대로 지정가능) font-style: normal; font-weight: 100; src: local('※'), local('Noto Sans Thin'); src: url(NotoSans-Thin.eot); src: url(NotoSans-Thin.eot?#iefix) format('embedded-opentype'), url(NotoSans-Thin.woff2) format('woff2'), // woff 보다 상위에 선언 url(NotoSans-Thin.woff) format('woff'), url(NotoSans-Thin.otf) format('truetype'); } @font-face { font-family: 'Noto Sans'; font-style: normal; font-weight: 400; src: local('※'), local('Noto Sans Regular'); src: url(NotoSans-Regular.eot); src: url(NotoSans-Regular.eot?#iefix) format('embedded-opentype'), url(NotoSans-Regular.woff2) format('woff2'), url(NotoSans-Regular.woff) format('woff'), url(NotoSans-Regular.otf) format('truetype'); } ``` ### style.css ```css // font.css 파일에서 지정한 font-family 이름으로 폰트를 사용한다. .font {font-family:'Noto Sans'} // 각 굵기(regular, bold 등등..)별 사용은 아래와 같이 font-weight 속성으로 구분하여 사용한다. .thin {font-weight:100} .light {font-weight:300} .regular {font-weight:400} .medium {font-weight:500} .bold {font-weight:700;} ``` ### HTML ```xml <div class="font"> <h1>Noto Sans</h1> <h2 class=" thin">Thin </h2> <p class=" thin">국회의 정기회는 법률이 정하는 바에 의하여 매년 1회 집회되며, 국회의 임시회는 대통령 또는 국회재적의원 4분의 1 이상의 요구에 의하여 집회된다. 모든 국민은 그 보호하는 자녀에게 적어도 초등교육과 법률이 정하는 교육을 받게 할 의무를 진다.</p> <h2 class=" light">Light </h2> <p class=" light">대통령의 선거에 관한 사항은 법률로 정한다. 국회는 의원의 자격을 심사하며, 의원을 징계할 수 있다. 군사법원의 조직·권한 및 재판관의 자격은 법률로 정한다.모든 국민은 고문을 받지 아니하며, 형사상 자기에게 불리한 진술을 강요당하지 아니한다. 군인은 현역을 면한 후가 아니면 국무총리로 임명될 수 없다.</p> <h2 class=" regular">Regular </h2> <p class=" regular">군인·군무원·경찰공무원 기타 법률이 정하는 자가 전투·훈련등 직무집행과 관련하여 받은 손해에 대하여는 법률이 정하는 보상외에 국가 또는 공공단체에 공무원의 직무상 불법행위로 인한 배상은 청구할 수 없다.</p> <h2 class=" medium">Medium </h2> <p class=" medium">헌법개정안이 제2항의 찬성을 얻은 때에는 헌법개정은 확정되며, 대통령은 즉시 이를 공포하여야 한다. 국무총리 또는 행정각부의 장은 소관사무에 관하여 법률이나 대통령령의 위임 또는 직권으로 총리령 또는 부령을 발할 수 있다.</p> <h2 class=" bold">Bold </h2> <p class=" bold">국회나 그 위원회의 요구가 있을 때에는 국무총리·국무위원 또는 정부위원은 출석·답변하여야 하며, 국무총리 또는 국무위원이 출석요구를 받은 때에는 국무위원 또는 정부위원으로 하여금 출석·답변하게 할 수 있다.</p> </div> ``` <file_sep>/git/README.md # Git hub ## Git 기본 ### 1.1 GitHub란? GitHub와 Git의 차이점은? Git 과 GitHub는 완전히 다른 것으로, Git은 Git리포지토리라고 불리는 데이터 저장소에 소스 코드 등을 넣어서 이용하는 것으로, 이러한 Git리포지토리를 인터넷상에서 제공하는 서비스가 GitHub다. - Git 리포지토리 - Organization - Issue - Wiki - Pull Request > - [GitHub 최근 트렌트살펴보기](http://github.com/trending) > - [Git 참고](https://backlogtool.com/git-guide/kr/reference/remote.html) ### 1.2 버전관리란? 기본적으로 버전관리 시스템은 변경내역을 관리한다. Git 이전에는 서브버전 등의 `집중형 버전관리` 시스템이 주류를 이루었지만 현재는 `분산형 버전 관리` 시스템 Git이 주류가 되었다. #### 1.2.1 집중형과 분산형 **집중형이란?** > 대표적인 집중형 버전관리 시스템으로는 서브비전이 있으며, 집중형은 말그대로 서버에 리포지토리를 집중시켜 배치한다. 따라서 하나의 소프트웨어를 개발할 때는 하나의 리포지토리만 존재한다. **집중형 정리** - 데이터가 중앙 서버에 집중되는 형태로, 덕분에 관리하기가 무척 단순하고 쉽다 - 서버에 접속할수 없거나 서버가 다운되는등 서버에 문제가 있을시 개발을 할 수 없다. - 서버가 고장나서 데이터가 사라지면 끝... *분산형이란?** > Git이 대표적인 분산형 버전관리 시스템으로, `Fork`라는 기능을 통해 특정 리포지토리를 자신의 계정으로 복제하여 사용가능하다. 이 복제된 리포지토리는 원본과는 완전히 다르며, 내마음대로 편집이 가능하다 (물론 라이센스는 논외로 치고) **분산형 정리** - 집중형과 달리 리포지토리가 여러 개 존재할 수 있으며, 그로인해 다소 복잡하다. - 개인마다 리포지토리를 가질 수 있으므로 서버에 종속되지 않는다.(즉 서버 접속없이도 개발가능) - github를 통하지 않아도 개발자끼리 리포지토토리를 직접 push,pull할경우 최신코드가 어디있는지 조차 알기 힘들 수 있다. #### 1.2.2 그래서 집중형과 분산형중에 어떤 것이 좋은가? 집중형 ,분산형 모두 장점과 단점이 있으므로 경우에 따라 다르지만 Git과 GitHub의 보급에 따라 분산형 버전관리 시스템이 압도적으로 많이 사용되는 것은 분명하다. 또한 분산형의 단점중의 하나인 복잡성도 규칙을 만든다면 얼마든지 분산형으로도 집중형 버전관리 시스템을 구현할 수 있다. > trending 섹션만 찾아봐도 요즈음 트렌드라 할만한 것들은 죄다 GitHub를 이용한다. > `node의 npm` ,`freecodecampus` ,`ruby on rails`, `lalavel`등 뭐 가리지 않고 GitHub를 통해 서비스한다. > 특히 요즘에는 국내 업체들도 GitHub를 쓰는 걸 꽤 찾아볼수 있다 (물론 아직까지는 유명한 대기업들..) > 얼마전에 새로 개편한(2016-03 기준) 네이버 개발자센터의 새로운 js라이브러리고 `gitHub`와 `codepen`를통해 서비스~ ### 1.3 설치 - 윈도우즈는 `mysysGit` - 리눅스는 종류별로 패키지가 다르므로 찾아서 (우분투,CentOs등..에 맞게) - 맥은 자동 설치되어있음 (업데이트정도만 해주자) 1. 컴포넌트는 기본설정 그대로 2. 환경변수 설정은 GitBash 사용(powershell이나 cmd는 사용법이 조금 달라서 너무 불편하다) `Use Git Bash Only` 항목 선택 3. 개행코드 설정은 (운영체제별로) `윈도우는 CRLF 맥이나 리눅스는 LF` 4. 설치가 완료되면 bash창에서 `git`명령어로 확인 ### 1.4 기본설정 및 사전준비 #### 사용자 이름과 메일 주소 설정 **가장 먼저 사용자 정보를 등록해줘야 한다.** > 소스트리 사용시에도 이 설정을 안해주면 에러가 났었다.(소스트리내의 커맨드창에서 간단히 입력가능) ```bash git config --global user.name "<NAME>" git config --global user.email "<EMAIL>" ``` #### 아래 명령어를 통해 설정파일 생성 확인 > 참고로 이때 설정한 이름과 메일주소로 Git Commit로그등에 사용되로 GitHub리포지토리를 공개할 경우에도 이때 설정한 정보가 사용된다. ```bash ~/.gitconfig ``` #### 출력되는 명령어를 쉽게 읽을수 있도록 설정 ```bash git config --global color.ui auto ``` #### SSH Key 설정 > 아래 명령어로 sshkey 생성하면 `id_rsa` 라는 파일이 `비밀키`고, `id_rsa.pub`이 `공개키`이다 > 경로는 `bash`창에 출력되니 그거 보고 확인 ```bash ssh-keygen -t rsa -C "<EMAIL>" ...명령어.. Enter file in which to save the key (파일경로..): //엔터키 입력 Enter passphrase (empty for no passphrase): //비밀번호 입력 Enter.... //비밀번호 재 입력 ``` #### GitHub에 공개키 등록 setting 창에 SSH key 메뉴에서 등록 Titlt은 키의 이름 key에는 `id_rsq.pub`의 내용을 복사해서 붙여넣자 `id_rsq.pub`의 내용은 아래 커맨드로 확인가능 ```bash cat ~/.ssh/id_rsa.pub ``` 등록이 완료되면 공개 키 등록완료와 관련된 메일이 발송된다. 실제로 동작하는지 아래 코드로 확인 ```bash ssh -T git@github.com ``` #### 리포지토리 clone Github사이트에서 생성한 레포지토리 주소를 복사해서 아래 명령어에 붙여 넣는다 ```bash git clone 리포지토리 주소 ``` #### 코드를 stage에 추가 commit을 하기 전에 스테이지에 파일을 등록해줘야 한다. 소스트리로 치면 체크박스 로 스테이징에 올리는 부분과 동일하다. ```bash git add 파일명 or 폴더/ ``` #### commit ```bash git commit -m "커밋 메시지" ``` #### commit log 확인 아래 명령어로 commit 로그를 확인 할 수 있다. ```bash git log ``` #### push ```bash git push ``` ### 1.5 기본적인 사용방법 #### 1) `git init` : 리포지토리 초기화 Git으로 버전관리를 하려면 리포지토리를 초기화해야 한다. 아래는 폴더를 생성하고 그 폴더내에서 리포지토리를 초기화 하는 예제다. ```bash mkdir git-test cd git-test git init ``` > 초기화가 성공적으로 완료되면 `git init`명령어를 실행한 폴더이 `.git`이라는 이름의 폴더가 만들어진다. > 이때 이 디렉토리 이하의 내용을 해당 리포지토리와 관련된 `working tree`라고 부르며, 이 안에서 파일준비, 등록된 파일 변경내역등을 관리하게 된다. #### 2) `git status` : 리포지토리 상태확인 `git status`명령어는 git 리포지토리의 상태를 표시하는 명령어다. 리포지토리에 대응되는 조작을 하면 상태가 차례대로 변경되는데, 이러한 변경내역들을 확인할 수 있다. ```bash git status ``` #### 3) `git add` : 스테이지 영역에 파일 추가 Git 리포지토리의 `working tree` 파일을 작성한 것 만으로는 Git 리포지토리의 버전관리 대응 시스템 파일이 등록되지 않는다. 즉 내가 `clone`한 경로에 새로운 파일을 추가 한후 ( 가령 README.md ) `git status`명령어를 실행해보면 추가한파일이 `Untracked files`로 출력되는걸 확인할 수 있다. 이렇게 변경(추가)된 파일을 Git 리포지토리에서 관리하도록 스테이지 영역에 등록하는 명령어 등록을 하면 `Untracked files` 가 `Changes to be committed`로 상태가 변경된걸 확인 할 수 있다. > 소스트리 툴에서 체크박스로 스테이징에 변경(추가포함)된 파일을 스테이지에 등록하는 단계와 동일하다 ```bash touch README.md git status // README.md 파일이 Untracked files 로 되어있는 것 확인 git add README.md git status // Changes to be committed : // new file : README.md ``` #### 4) `git commit` : 리포지토리 변경 내용을 기록 스테이지 영역에 기록된 시점의 파일들을 실제 리포지토리의 변경 내역에 반영하는 명령어 이 commit 기록을 기반으로 파일을 `working tree`에 복원하는 것이 가능하다. ```bash git commit -m "First commit" ``` <file_sep>/게시판만들기/struts1 게시판 만들기/WEB-INF/classes/my/bbs2/BbsDAO.java package my.bbs2; // Data Access Object : 업무처리 로직(비지니스 로직) // 을 가지는 클래스... DB에 insert, delete, update, select 등의 업무처리 로직 import java.sql.*; import javax.naming.*; import javax.sql.*; import java.util.*; import java.io.*; import javax.servlet.ServletContext; import javax.servlet.http.*; import my.bbs2.BbsDTO; import my.bbs2.ReplyDTO; import my.bbs2.controller.form.BbsEditForm; import com.oreilly.*; import com.oreilly.servlet.*; import com.oreilly.servlet.multipart.*; public class BbsDAO { static DataSource ds; Connection con; // #1. 글쓰기 관련 -writeOk 관련(bbs_writeOk.jsp) // 1_1. 글 그룹번호(refer)최대값 가져오기. PreparedStatement ps1, ps1_1; ResultSet rs1, rs1_1; // #2. 글목록 관련 -listAll 관련(bbs_list.jsp) PreparedStatement ps2; ResultSet rs2; // #2_1. 총 게시물 수 - getTotalGulCount관련 PreparedStatement ps2_1; ResultSet rs2_1; // #3. 글내용 보기 관련 --viewContent(bbs_content.jsp) PreparedStatement ps3, ps3_1; ResultSet rs3; // #4. 글 삭제 관련 --deleteOk PreparedStatement ps4, ps4_1; ResultSet rs4; // #5. 5_1 글 편집 성공 여부 관련 --- editOk PreparedStatement ps5, ps5_1; ResultSet rs5; // #6, 6_1, 6_2 답글 쓰기 관련 --- rewriteOk PreparedStatement ps6, ps6_1, ps6_2; ResultSet rs6; // #7 꼬리말 달기 관련 ---replySave PreparedStatement ps7; public BbsDAO(){ } static{ try{ Context initCtx = new InitialContext(); Context envCtx = (Context)initCtx.lookup("java:comp/env"); ds = (DataSource)envCtx.lookup("jdbc/struts"); System.out.println("DataSource 룩업 성공!"); }catch (NamingException e){ e.printStackTrace(); } } /** 1. 글쓰기 -- writeOk() */ public int writeOk(MultipartRequest mr) throws SQLException{ String writeOk_sql = "insert into jsp_board (writer, email, homepage, pwd, subject, content, writedate, readnum, filename, filesize, refer, lev, sunbun) values("+ "?,?,?,?,?,?," + "now(),?,?,?,?,?,?)"; try{ con = ds.getConnection(); ps1 = con.prepareStatement(writeOk_sql); String writer = mr.getParameter("writer"); String email = mr.getParameter("email"); String homepage = mr.getParameter("hpmepage"); String pwd = <PASSWORD>("pwd"); String subject = mr.getParameter("subject"); String content = mr.getParameter("content"); int readnum = 0; String filename = mr.getFilesystemName("filename"); String originFilename = mr.getOriginalFileName("filename"); System.out.println("filename : "+filename+" originFilename : "+originFilename); long filesize = 0; if(filename == null){ filename =""; }else{ filename = filename.trim(); File f = mr.getFile("filename"); if(f!=null) filesize = f.length(); else filesize =0; } // 답변형 게시판에서 사용할 필드 // 답변형 추가 - 글 그룹번호 증가 로직 int referMax = getMaxRefer(); int refer = referMax+1; int lev = 0; int sunbun = 0; ps1.setString(1, writer); ps1.setString(2,email); ps1.setString(3,homepage); ps1.setString(4,pwd); ps1.setString(5,subject); ps1.setString(6,content); ps1.setInt(7,readnum); ps1.setString(8,filename); ps1.setLong(9,filesize); ps1.setInt(10, refer); ps1.setInt(11,lev); ps1.setInt(12,sunbun); int n = ps1.executeUpdate(); return n; }finally{ if(ps1!=null)ps1.close(); if(rs1!=null)rs1.close(); if(con!=null)con.close(); } } /* # 1_1 refer(같은 글집단)의 최대값(max)구하기 */ public int getMaxRefer() throws SQLException{ String maxRefer_sql = "select max(refer) from jsp_board"; Connection con2 = null; try{ con2 = ds.getConnection(); ps1_1 = con2.prepareStatement(maxRefer_sql); rs1_1 = ps1_1.executeQuery(); if(rs1_1.next()){ int maxRefer = rs1_1.getInt(1); return maxRefer; } return -1; }finally{ if(rs1_1 != null)rs1_1.close(); if(ps1_1 != null)ps1_1.close(); if(con2 != null)con2.close(); } } /** 2. 글 목록 ---listAll() */ public ArrayList<BbsDTO> listAll(int cpage, int pageSize) throws SQLException{ String list_sql = "select * from jsp_board order by idx desc"; String list_sql2 = "select * from jsp_board order by refer desc, sunbun asc"; ArrayList<BbsDTO> arr = new ArrayList<BbsDTO>(); try{ con = ds.getConnection(); ps2 = con.prepareStatement(list_sql2, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); //위의 타입을 지정 안하면rs.next()외엔 수행하지 않음.. rs2 = ps2.executeQuery(); //특정한 행으로 커서를 이동... int startNo = (cpage-1)*pageSize+1; boolean isRs = rs2.absolute(startNo); int count = 0; if(isRs){ do{ if(count++ == pageSize) break; int idx = rs2.getInt(1); String writer = rs2.getString(2); String email = rs2.getString(3); String homepage = rs2.getString(4); String pwd = <PASSWORD>(5); String subject = rs2.getString(6); String content = rs2.getString(7); java.sql.Date writedate = rs2.getDate(8); int readnum = rs2.getInt(9); String filename = rs2.getString(10); long filesize = rs2.getLong(11); int refer = rs2.getInt(12); int lev = rs2.getInt(13); int sunbun = rs2.getInt(14); // BbsDTO 생성자 ArrayList에 초기화 BbsDTO dto = new BbsDTO(idx,writer,email,homepage, pwd,subject,content,writedate,readnum, filename,filesize,refer,lev,sunbun); arr.add(dto); }while(startNo >0 && rs2.next()); //do~while -------- } return arr; }finally{ if(rs2!=null) rs2.close(); if(ps2!=null) ps2.close(); if(con!=null) con.close(); } } /* 2_1 총 게시물 수 구하기 관련 */ public int getTotalGulCount() throws SQLException{ String total_sql = "select count(*) cnt from jsp_board"; try{ con = ds.getConnection(); ps2_1 = con.prepareStatement(total_sql); rs2_1 = ps2_1.executeQuery(); if(rs2_1.next()){ int cnt = rs2_1.getInt("cnt"); //rs2_1.getInt(1); return cnt; }else return -1; }finally{ if(rs2_1 != null) rs2_1.close(); if(ps2_1 != null) ps2_1.close(); if(con!=null) con.close(); } } /* 3. 글내용 보기 */ public BbsDTO viewContent(String idx) throws SQLException{ int idx2 = Integer.parseInt(idx.trim()); String content_sql = "select * from jsp_board where idx=?"; try{ con = ds.getConnection(); ps3 = con.prepareStatement(content_sql); ps3.setString(1,idx); rs3 = ps3.executeQuery(); if(rs3.next()){ String writer = rs3.getString(2); String email = rs3.getString(3); String homepage = rs3.getString(4); String pwd = <PASSWORD>(5); String subject = rs3.getString(6); String content = rs3.getString(7); java.sql.Date writedate = rs3.getDate(8); int readnum = rs3.getInt(9); String filename = rs3.getString(10); long filesize = rs3.getLong(11); int refer = rs3.getInt(12); int lev = rs3.getInt(13); int sunbun = rs3.getInt(14); BbsDTO dto = new BbsDTO(idx2,writer,email,homepage,pwd,subject,content,writedate, readnum, filename,filesize,refer,lev,sunbun); return dto; }else{ return null; } }finally{ if(rs3!=null)rs3.close(); if(ps3!=null)ps3.close(); if(con!=null)con.close(); } } /* * 3_1. 글내용(viewContent)관련 * 조회수 (readnum) 증가 메소드 */ public boolean getReadnum(String idx) throws SQLException{ String readnum_sql = "update jsp_board set readnum = readnum+1 where idx=?"; try{ con = ds.getConnection(); ps3_1 = con.prepareStatement(readnum_sql); ps3_1.setString(1, idx); int n =ps3_1.executeUpdate(); if(n>0){ return true; }else return false; }finally{ if(ps3_1 != null) ps3_1.close(); if(con!=null) con.close(); } } /* #4. 글 삭제 관련 --deleteOk */ public int deleteOk(String idx, String pwd) throws SQLException{ String selPwd_sql ="select pwd from jsp_board where idx=?"; String delOk_sql ="delete from jsp_board where idx=?"; //꼬리말 테이블을 삭제한 후 부모글을 삭제 String replyDel_idx_sql = "delete from reply where reply_idx_fk=?"; PreparedStatement ps4_2 = null; try{ con = ds.getConnection(); ps4 = con.prepareStatement(selPwd_sql); ps4.setString(1,idx); rs4 = ps4.executeQuery(); if(rs4.next()){ String dbPwd =rs4.getString("pwd"); System.out.println("dbPwd = "+dbPwd); System.out.println("pwd = "+pwd); System.out.print(idx); if(dbPwd!=null) dbPwd = dbPwd.trim(); if(dbPwd.equals(pwd)){ con.setAutoCommit(false); //꼬리글이 다 삭제된 다음에 삭제 // 꼬리글 삭제 ps4_2 = con.prepareStatement(replyDel_idx_sql); ps4_2.setString(1, idx); ps4_2.executeUpdate(); /// 원래글 삭제 ps4_1 = con.prepareStatement(delOk_sql); ps4_1.setString(1,idx); int n = ps4_1.executeUpdate(); if(n>0) con.commit(); else con.rollback(); return n; }else //비밀번호 불일치시 return -1; }else return -1; }finally{ con.setAutoCommit(true); if(rs4!= null) rs4.close(); if(ps4!=null) ps4.close(); if(ps4_1!=null) ps4_1.close(); if(ps4_2!=null)ps4_2.close(); if(con!=null)con.close(); } } /* 5. 글 내용 편집 관련 */ public BbsDTO edit(String idx) throws SQLException{ return this.viewContent(idx); } /* 5_1. 글 편집 성공 여부 관련 public int editOk(HttpServletRequest req) throws SQLException{ String selPwd_sql = "select pwd from jsp_board where idx=?"; String editOk_sql = "update jsp_board set writer=?,"+ "email=?,homepage=?,subject=?,content=? where idx=?"; try{ String idx = req.getParameter("idx"); String writer = req.getParameter("writer"); String pwd = req.getParameter("pwd"); String subject = req.getParameter("subject"); String content =req.getParameter("content"); String homepage = req.getParameter("homepage"); String email = req.getParameter("email"); con = ds.getConnection(); ps5 = con.prepareStatement(selPwd_sql); ps5.setString(1,idx); rs5 = ps5.executeQuery(); if(rs5.next()){ String dbPwd = rs5.getString("pwd"); if(dbPwd.equals(pwd.trim())){ ps5_1 = con.prepareStatement(editOk_sql); ps5_1.setString(1, writer); ps5_1.setString(2,email); ps5_1.setString(3,homepage); ps5_1.setString(4,subject); ps5_1.setString(5,content); ps5_1.setString(6,idx); int n = ps5_1.executeUpdate(); return n; } } return -1; }finally{ if(rs5 != null)rs5.close(); if(ps5 != null)ps5.close(); if(ps5_1 != null)ps5_1.close(); } } */ /* 5_2. 글 편집 성공 여부 관련 */ public int editOk(BbsEditForm req) throws SQLException{ String selPwd_sql = "select pwd from jsp_board where idx=?"; String editOk_sql = "update jsp_board set writer=?,"+ "email=?,homepage=?,subject=?,content=? where idx=?"; try{ String idx = req.getIdx(); String writer = req.getWriter(); String pwd = req.getPwd(); String subject = req.getSubject(); String content =req.getContent(); String homepage = req.getHomepage(); String email = req.getEmail(); con = ds.getConnection(); ps5 = con.prepareStatement(selPwd_sql); ps5.setString(1,idx); rs5 = ps5.executeQuery(); if(rs5.next()){ String dbPwd = rs5.getString("pwd"); if(dbPwd.equals(pwd.trim())){ ps5_1 = con.prepareStatement(editOk_sql); ps5_1.setString(1, writer); ps5_1.setString(2,email); ps5_1.setString(3,homepage); ps5_1.setString(4,subject); ps5_1.setString(5,content); ps5_1.setString(6,idx); int n = ps5_1.executeUpdate(); return n; } } return -1; }finally{ if(rs5 != null)rs5.close(); if(ps5 != null)ps5.close(); if(ps5_1 != null)ps5_1.close(); } } /* 6. 답글 쓰기 관련 */ public int rewriteOk(MultipartRequest mr) throws SQLException{ //1.사용자가 입력한 값 뽑아오기.... String idx = mr.getParameter("idx"); String subject = mr.getParameter("subject"); String content = mr.getParameter("content"); String writer = mr.getParameter("writer"); String email = mr.getParameter("emial"); String homepage = mr.getParameter("homepage"); String pwd = mr.getParameter("pwd"); String filename = mr.getFilesystemName("filename"); String origin = mr.getOriginalFileName("filename"); long filesize = 0; if(filename == null || filename.trim().equals("")){ filename=""; }else{ filename = filename.trim(); filesize = mr.getFile("filename").length(); } String refer_lev_sunbun_sql = "select refer, lev, sunbun from jsp_board where idx=?"; String update_sunbun_sql = "update jsp_board set sunbun = sunbun+1 where sunbun >? and refer=?"; String rewriteOk_sql = "insert into jsp_board ( writer, email, homepage, pwd, subject, content, writedate, readnum, filename, filesize, refer, lev, sunbun)" + " values(?,?,?,?,?,?,now(),"+ "?,?,?,?,?,?)"; try{ con = ds.getConnection(); ps6 = con.prepareStatement(refer_lev_sunbun_sql); ps6.setString(1, idx); rs6 = ps6.executeQuery(); int lev=0, refer=0,sunbun=0; if(rs6.next()){ refer = rs6.getInt("refer"); lev = rs6.getInt("lev"); sunbun = rs6.getInt("sunbun"); //같은 글그룹의 순번을 업데이트; ps6_1 = con.prepareStatement(update_sunbun_sql); ps6_1.setInt(1, sunbun); ps6_1.setInt(2, refer); ps6_1.executeUpdate(); //답글 insert 부분 ps6_2 = con.prepareStatement(rewriteOk_sql); ps6_2.setString(1, writer); ps6_2.setString(2, email); ps6_2.setString(3, homepage); ps6_2.setString(4, pwd); ps6_2.setString(5, subject); ps6_2.setString(6, content); ps6_2.setInt(7, 0); //조회수 처음에 0 ps6_2.setString(8, filename); ps6_2.setLong(9, filesize); ps6_2.setInt(10, refer); ps6_2.setInt(11, lev+1); ps6_2.setInt(12, sunbun+1); int n = ps6_2.executeUpdate(); return n; }else{ return -1; } }finally{ if(rs6 != null)rs6.close(); if(ps6 != null)ps6.close(); if(ps6_1 != null)ps6_1.close(); if(ps6_2 != null)ps6_2.close(); if(con!=null)con.close(); } } /* 7. content에 꼬리말 쓰기 관련 */ public int replySave(String idx, String writer, String content, String pwd) throws SQLException{ String replySave_sql ="insert into reply (writer, pwd, content, writedate, readnum, reply_idx_fk) values(?,?,?,now(),?,?)"; try{ con = ds.getConnection(); ps7 = con.prepareStatement(replySave_sql); ps7.setString(1, writer); ps7.setString(2,pwd); ps7.setString(3,content); ps7.setInt(4,0); ps7.setString(5,idx); return ps7.executeUpdate(); }finally{ if(ps7!=null)ps7.close(); if(con!=null)con.close(); } } /* #7_1. 꼬리말 목록 가져오기 ----replyList() */ public ArrayList<ReplyDTO> replyList(String idx) throws SQLException{ String replyList_sql = "select * from reply where reply_idx_fk =? order by no"; PreparedStatement ps7_1 = null; ResultSet rs7_1 = null; try{ con = ds.getConnection(); ps7_1 = con.prepareStatement(replyList_sql); ps7_1.setString(1,idx); rs7_1 = ps7_1.executeQuery(); ArrayList<ReplyDTO> arr = new ArrayList<ReplyDTO>(); while(rs7_1.next()){ int no =rs7_1.getInt(1); String writer = rs7_1.getString(2); String pwd = rs7_1.getString(3); String content = rs7_1.getString(4); java.sql.Date writedate = rs7_1.getDate(5); ReplyDTO rdto = new ReplyDTO(no,writer,pwd,content,writedate,0,idx); arr.add(rdto); } return arr; }finally{ if(rs7_1 !=null)rs7_1.close(); if(ps7_1!=null)ps7_1.close(); if(con!=null)con.close(); } } /* #7_2. content 꼬리말 삭제 ---- replyDelPwd() */ public int replyDelPwd(String no, String pwd) throws SQLException{ PreparedStatement ps7_2 = null, ps7_3 = null; ResultSet rs7_2 = null; String replydel_pwd_sql = "select pwd from reply where no=?"; String replydelok_sql = "delete from reply where no=?"; try{ con = ds.getConnection(); ps7_2 = con.prepareStatement(replydel_pwd_sql); ps7_2.setString(1,no); rs7_2 = ps7_2.executeQuery(); if(rs7_2.next()){ String dbPwd = rs7_2.getString(1); if(pwd.equals(dbPwd)){ ps7_3 = con.prepareStatement(replydelok_sql); ps7_3.setString(1, no); int n = ps7_3.executeUpdate(); return n; } } return -1; }finally{ if(rs7_2 != null)rs7_2.close(); if(ps7_2 != null)ps7_2.close(); if(ps7_3 != null) ps7_3.close(); if(con !=null)con.close(); } } } <file_sep>/C#.NET/라이브러리/2.어플리케이션.MD # C#.NET 라이브러리 ----------------- ##어플리케이션 1. ArrayInfo 2. Check.cs 3. Config.cs 4. DBHelper.cs 5. HTML.cs 6. Message.cs 7. Paging.cs 8. ResotreObj.cs 9. Util.cs 10. Validation.cs ----------------- ##### 1.ArrayInfo 프로젝트에서 사용되는 웹 코드값을 배열로 정의합니다. DB에 코드값으로 들어가 있는것과 연계해서 웹에서 표현할 때 키에 맞는 값으로 변경할 요지로 정의합니다. 명명규칙은 arr(배열)Mng(관리자)Tvcf(메뉴)UseYn(키코드명) ```css /// <summary> /// 노출여부 /// </summary> public static string[] arrMngTvcfUseYn = { "Y", "노출", "N", "미노출" }; ex) 키와 코드값의 따른 셀렉트 박스 생성 useYnSeletBox = Html.getSelectBox(ArrayInfo.arrMngTvcfUseYn, useYn, 2); ``` ----------------- ##### 2.Check.cs 체크에 관련한 함수나 프로세스를 정의합니다. 브라우저, ssl, session 등 주기적으로 체크하는 것이나 단편적으로 체크하는 모든 체크요소들을 정의합니다. ```css /// <summary> /// 브라우저 체크 /// </summary> public static void browser() { HttpContext.Current.Response.CacheControl = "no-cache"; HttpContext.Current.Response.AddHeader("Pragma", "no-cache"); HttpContext.Current.Response.AddHeader("X-XSS-Protection", "0"); HttpContext.Current.Response.Expires = -1; HttpContext.Current.Response.ContentType = "text/html"; } ex) 페이지 진입시 브라우저 체크 protected void Page_Load(object sender, EventArgs e) { Check.browser(); ``` ----------------- ##### 3.Config.cs 상수들을 정의합니다. 사이트 URL, 도메인, 업로드 경로 등 사이트 전반적인 환경설정변수들을 정의합니다. ```css /// <summary> /// 유튜브 URL /// </summary> public static string youtubeuUrl = "https://www.youtube.com/embed/"; /// <summary> /// 업로드 경로 /// </summary> /// <param name="host">업로드 경로</param> /// <returns>경로</returns> public static string getUploadPath(string host) { string uploadPath = ""; if (host.IndexOf("localhost") > -1 || host.IndexOf("192.168.0.46") > -1) { } // 개발 else if (host.IndexOf("dev2.doubleheart.co.kr") > -1 || host.IndexOf("dev3.doubleheart.co.kr") > -1) { uploadPath = "xxxxxxxxxxxxxxxxxxxxxxxxxx"; } return uploadPath; } ex) 업로드시 경로를 불러와 사용합니다. string SaveLocation = Config.getUploadPath(Request.Url.Host.ToString()) + "banner\\" + sysFn; ``` ----------------- ##### 4.DBHelper.cs DB관련 커넥션 및 함수들의 정의합니다. 웹 개발에 필요한 쿼리문을 각 상황에 맞는 파라미터에 따라 쿼리문을 변경해줍니다. ```css /// <summary> /// 커넥션 /// </summary> /// <param name="host">호스트</param> /// <returns>커넥션</returns> public static SqlConnection dbConnection(string host) /// <summary> /// 데이터 총 개수 /// </summary> /// <param name="table">테이블 명</param> /// <param name="where">검색배열</param> /// <param name="like">검색배열</param> /// <returns>테이터 총 개수</returns> public static string selectListCount(string table, string[] where, string[] like) /// <summary> /// 데이터 레코드 /// </summary> /// <param name="table">테이블 명</param> /// <param name="where">검색배열</param> /// <param name="like">검색배열</param> /// <param name="orderSeq">정렬순서</param> /// <param name="startNum">시작번호</param> /// <param name="endNum">끝번호</param> /// <returns></returns> public static string selectList(string table, string[] where, string[] like, string orderSeq, int startNum, int endNum) /// <summary> /// 저장 /// </summary> /// <param name="table">테이블 명</param> /// <param name="listSql">컬럼 리스트</param> /// <returns>SQL</returns> public static string insert(string table, List<string> listSql) /// <summary> /// 수정 /// </summary> /// <param name="table">테이블 명</param> /// <param name="listSql">컬럼 리스트</param> /// <returns>SQL</returns> public static string update(string table, List<string> listSql) ``` ----------------- ##### 5.HTML.cs 개발에 따른 HTML을 정의합니다. 웹 개발에 필요한 쿼리문을 각 상황에 맞는 파라미터에 따라 쿼리문을 변경해줍니다. ```css // 셀렉트박스 생성 public static string getSelectBox(string[] arrName, string selectValue, int intInterval) { string strHtml = ""; if (intInterval.ToString() == "") { intInterval = 1; } if (selectValue == null) { selectValue = ""; } for (int i = 0; i < arrName.Length; i = i + intInterval) { if (selectValue.Equals(arrName[i])) { strHtml = strHtml + "<option value='" + arrName[i] + "' selected>" + arrName[i + (intInterval - 1)] + "</option>"; } else { strHtml = strHtml + "<option value='" + arrName[i] + "'>" + arrName[i + (intInterval - 1)] + "</option>"; } } return strHtml; } ex) view페이지에서 사용되는 html을 개발값과 키값배열에 따라 변경되어 마크업이 구성됩니다. useYnSeletBox = Html.getSelectBox(ArrayInfo.arrMngTvcfUseYn, useYn, 2); ``` ----------------- ##### 6.Message.cs 프로그램단에서도 얼랏같은 메시지를 구현할 수 있도록 정의합니다. 메시지만 있는 얼랏을 출력하거나, 메시지 후 페이지 닫기, 메시지 후 페이지 이동 등 다양한 확장성이 있도록 정의합니다. ```css /// <summary> /// 부모창 새로고침 후 페이지 닫기 /// </summary> public static void goPageCloseParentReload() { message = "<script>"; message += "opener.location.reload();"; message += "self.close();"; message += "</script>"; HttpContext.Current.Response.Write(message); } ex) 프로세스 처리 후에 페이지에 대한 프로세스를 실행합니다. Message.goPageCloseParentReload(); ``` ----------------- ##### 7.Paging.cs 게시판 페이징을 정의합니다. 페이징에 필요한 요소들을 전달 받으면 페이징을 html로 만든것을 반환하며, 페이징의 속성중인 글번호, 시작페이지 등 페이징의 요소들을 정의합니다. ```css public class Paging { public static string pStrUrl; // URL public static int pTotalCount; // 총 개수 public static int pP; // 현재 페이지번호 public static int pPageNum; // 페이지 간격 public static int pPageListNum; // 페이지 리스트 간격 public static int pPrevPage; // 페이지 이전번호 public static int pNextPage; // 페이지 다음번호 public static int pStartNum; // 페이지 시작번호 public static int pEndNum; // 페이지 끝번호 public static int pTotalPage; // 총 페이지 수 public static string pPageTail = ""; // 페이지 꼬리 // 페이지 값 셋팅 public static void pageNavigation(string requestUrl, int totalCount, int p, int pageNum, int pageListNum, string pageTail) { ex) 페이징을 생성하는 필수 요소인 게시물 총카운트를 넣어 설정합니다. // 페이지 셋팅 Paging.pageNavigation(Request.Url.LocalPath, totalCount, p, 10, 10, pageTail); articleNum = Paging.getArticleNum(p, totalCount, 10); paging = Paging.getMngPaging(); ``` ----------------- ##### 8.ResotreObj.cs 사용중이거나 열려있는 객체를 반환하는 코드들을 정의합니다. ```css csspublic class ResotreObj { public static void resotreObjReturn(SqlConnection con, SqlDataReader dr) { if(dr != null) { if (!dr.IsClosed) { dr.Close(); } } if (con != null) { if (con.State.ToString() == "Open") { con.Close(); } } } } ex) 사용중인 객체 값 전달받아 제거 및 닫는 것을 적용합니다. // 객체반환 ResotreObj.resotreObjReturn(con, dr); ``` ----------------- ##### 9.Util.cs 문자나 숫자등을 변경하여 사용에 유용하도록 하는 함수들을 정의합니다. ```css /// <summary> /// 랜덤파일명 생성 /// </summary> /// <returns>랜덤파일명</returns> public static string randomFileName() { return DateTime.Now.AddHours(14).ToString("yyyyMMddHHmmss") + Path.GetRandomFileName(); } ex) 랜덤파일들을 생성합니다. // 객체반환 string sysFn = Util.randomFileName() + "." + fn.Split('.')[1]; ``` ----------------- ##### 10.Vaildatetion.cs 변수나 파라미터에 보안 및 null값 대체에 관한 체크를 정의합니다. ```css // Request 인젝션 체크 public static string requestValue(string str) { return sqlInjection(str).Trim(); } // Request 인젝션 체크 후 값 없을 시 대체 public static string requestValues(string str, string nvlstr) { return sqlInjection(nvl(str, nvlstr)).Trim(); } ex) 인젝션 체크를 진행한 변수만 전달받습니다. bannerName = Validation.requestValue(Request.Form["bannerName"]); ``` ----------------- <file_sep>/게시판만들기/c-cgi-mysql 게시판 만들기/cgi-bin/bak_160329/write.c #include "common.h" // gcc -o write.cgi write.c cgic.c -I/usr/include/mysql -L/usr/local/lib/mysql -lmysqlclient int cgiMain(void) { /* 헤더 속성 최상단에 위치 - 헤더위에 print 문등이 있으면 500 error 발생 */ printf("%s%c%c\n","Content-Type:text/html;charset=utf-8",13,10); int i; // 입력값 얻어냄 cgiFormString("seq", seq, MAX_LEN); // GET 전송 ( 수정할때 사용할 seq ) cgiFormString("title", title, MAX_LEN); cgiFormString("name", name, MAX_LEN); cgiFormString("content", content, MAX_LEN); // seq 값 있을시 if(strcheck(seq)){ // db 연결 mysqlDbConn(); sprintf(query, "SELECT * FROM bbsc WHERE seq='%s'", seq); if(mysql_query(connection, query) ){ fprintf(stderr, "%s\n", mysql_error(&conn)); exit(0); } res = mysql_store_result(connection); row = mysql_fetch_row(res); /* seq_val, title_val 등은 MAX_LENTH 를 지정한 "배열" 이기 때문에 문자열을 바로 대입할수 없다. 즉 seq_val = row[0] 식의 대입은 안된다. 따라서 배열에 문자열을 넣는 방법중의 하나인 문자열 복사 함수(strcpy)를 이용한다. */ strcpy(seq_val, row[0]); strcpy(title_val, row[1]); strcpy(name_val, row[2]); strcpy(content_val, row[3]); mysql_close(connection); } printf("<!doctype html>\n"); printf("<html lang=\"ko\">\n"); printf("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n"); printf("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n"); printf("<head> \n"); printf(" <title>CGI - board</title>\n"); //printf(" <link href=\"https://maxcdn.bootstrapcdn.com/bootswatch/3.3.6/paper/bootstrap.min.css\" rel=\"stylesheet\" > \n"); printf(" <link href=\"https://maxcdn.bootstrapcdn.com/bootswatch/3.3.6/slate/bootstrap.min.css\" rel=\"stylesheet\" > \n"); printf(" <script src=\"https://code.jquery.com/jquery-1.12.1.min.js\"></script> \n"); printf(" <script > \n"); printf(" //alert('123') \n"); printf(" function goList(){ \n"); printf(" location.href='list.cgi'; \n"); printf(" }; \n"); printf(" function goWrite(){ \n"); printf(" var form = document.update_frm \n"); printf(" form.submit(); \n"); printf(" }; \n"); printf(" </script> \n"); printf("<head>\n"); printf("<body>\n"); printf("<div class='container'>\n"); printf(" <div class='row'>\n"); printf(" <h2>CGI - board</h2>\n"); printf(" <form method='post' name='update_frm' id='update_frm' action='write_proc.cgi'> \n"); printf(" <input type='hidden' name='seq' id='seq' value='%s'>\n", seq_val); printf(" <table class='table'>\n"); printf(" <tr>"); printf(" <th class='active col-xs-1'>제목</th>\n"); printf(" <td><input name='title' id='title' class='form-control' value='%s'></td>\n", title_val); printf(" </tr>\n"); printf(" <tr>\n"); printf(" <th class='active col-xs-1'>이름</th>\n"); printf(" <td><input name='name' id='name' class='form-control' value='%s'></td>\n", name_val); printf(" </tr>\n"); printf(" <tr>\n"); printf(" <th class='active col-xs-1'>본문</th>\n"); printf(" <td><textarea name='content' id='content' class='form-control' cols='60' rows='10' >%s</textarea></td>\n", content_val); printf(" </tr>\n"); printf(" </table>\n"); printf(" </form>\n"); printf(" <button class='btn btn-default' onclick='goWrite();' >작성</button> \n"); printf(" <button class='btn btn-default' onclick='goList();' >리스트</button> \n"); printf(" </div>\n"); printf("</div>\n"); printf("</body>\n</html>"); /* // insert else{ cgiFormString("title", title, MAX_LEN); cgiFormString("name", name, MAX_LEN); cgiFormString("content", content, MAX_LEN); cgiFormString("update_seq", update_seq, MAX_LEN); cgiFormString("update_title", update_title, MAX_LEN); cgiFormString("update_name", update_name, MAX_LEN); cgiFormString("update_content", update_content, MAX_LEN); printf("<!doctype html>\n"); printf("<html lang=\"ko\">\n"); printf("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n"); printf("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n"); printf("<head> \n"); printf(" <title>CGI - board</title>\n"); //printf(" <link href=\"https://maxcdn.bootstrapcdn.com/bootswatch/3.3.6/paper/bootstrap.min.css\" rel=\"stylesheet\" > \n"); printf(" <link href=\"https://maxcdn.bootstrapcdn.com/bootswatch/3.3.6/slate/bootstrap.min.css\" rel=\"stylesheet\" > \n"); printf(" <script src=\"https://code.jquery.com/jquery-1.12.1.min.js\"></script> \n"); printf(" <script > \n"); printf(" function goList(){ \n"); printf(" location.href='list.cgi'; \n"); printf(" }; \n"); printf(" </script> \n"); printf("<head>\n"); printf("<body>\n"); printf("<div class='container'>\n"); printf(" <div class='row'>\n"); printf(" <h2>CGI - board</h2>\n"); printf(" <div class='panel panel-default'>"); printf(" <div class='panel-heading'>입력이 완료되었습니다.</div>"); printf(" <div class='panel-body'>"); printf(" 리스트 페이지로 이동하려면 확인버튼을 누르세요. \n"); printf(" </div>"); printf(" </div>"); printf(" <table width='600' class='table table-bordered'>\n"); printf(" </table>\n"); printf(" <button class='btn btn-default' onclick='goList();' >확인</button> \n"); printf(" </div>\n"); printf("</div>\n"); printf("</body>\n</html>"); //logView(title, name, content, update_title); if(!mysql_query(connection, query) ){ //printf("진입\n"); fprintf(stderr, "%s\n", mysql_error(&conn)); exit(0); } exit(1); } */ } <file_sep>/java/opentutorials/4. class_path/README.md ## 클래스 패스 IDE를 사용하지 않을 경우 (이클립스가 자동으로 클래스 위치및 임시 인스턴스 서버배치를 해주지 못할 상황..) > `/srcbin` 이라는 디렉토리에 `ClasspathDemo.java` 파일을 아래와 같이 생성한 후 컴파일 해보자 ```java class Item{ } class ClasspathDemo { } ``` > 아래와 같이 두개의 클래스 파일이 생성되는걸 알수 있다. - ClasspathDemo.class - Item.class > 이번엔 `ClasspathDemo2.java`파일을 작성 후 컴파일 해보자 ```java class Item2{ public void print(){ System.out.println("Hello world"); } } class ClasspathDemo2 { public static void main(String[] args){ Item2 i1 = new Item2(); i1.print(); } } ``` > 두개의 클래스가 정상적으로 생성됬다면 현재 디렉토리`(/srcbin)`하위에 `lib`을 만들고 > 여기로 `Item2.class` 파일을 이동한 후 `ClasspathDemo2`를 실행해보자 ``` Exception in thread "main" java.lang.NoClassDefFoundError: Item2 at ClasspathDemo2.main(ClasspathDemo2.java:9) Caused by: java.lang.ClassNotFoundException: Item2 at java.net.URLClassLoader$1.run(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) ... 1 more ``` > item.class 파일이 현재 디렉토리에 존재하지 않기 때문에 찾을 수 없다는 에러메시지를 확인할 수 있다. > 바로 이때 사용하는 것이 클래스 패쓰다..아래와 같이 실행해보자.. ``` java -classpath ".;lib" ClasspathDemo2 ``` > 리눅스 혹은 유닉스 계열이라면 아래와 같이 콜론을 사용해야 한다 ``` java -classpath ".:lib" ClasspathDemo2 ``` > 옵션 `-classpath`는 자바를 실행할 때 사용할 클래스들의 위치를 가상머신에게 알려주는 역할을 한다. -`classpath`의 값으로 사용된 ".;lib"를 살펴보자.<file_sep>/guide/개발 라이브러리 가이드/C#.NET/3.코드기본골격.MD # C#.NET 라이브러리 ----------------- ##코드 기본 골격 ----------------- ##### 상단 클래스 선언 ```css using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.IO; /// <summary> /// 더블하트 관리자 브랜드 스토리 /// </summary> namespace Doubleheart.dhmng.brandstory { /// <summary> /// 프린트 폼 /// </summary> public partial class printcfForm : System.Web.UI.Page { ``` 상단 선언부는 기본 C#클래스 생성 규칙과 다르지 않습니다. ----------------- ##### 변수 선언부분 ```css // 객체선언 SqlConnection con; SqlDataReader dr; // 파라미터 public int printcfSeq; // 인쇄CF순번 public string file; // 파일 public string fileName; // 파일명 public string sysFileName; // 시스템 파일명 // 오브젝트 public string title; // 제목 public string useYn; // 노출여부(Y:노출, N:미노출) public string delYn; // 삭제여부(Y:삭제, M:미삭제) public int regSeq; // 등록자순번 public string regDate; // 등록일 public string regTime; // 등록시간 public int updSeq; // 수정자 순번 public string updDate; // 수정일 public string updTime; // 수정시간 public string thumbImgName; // 썸네일 이미지 파일 public string sysThumbImgName; // 시스템 썸네일 이미지 파일 public string detailImgName; // 썸네일 이미지 파일 public string sysDetailImgName; // 시스템 썸네일 이미지 파일 // 커맨드 public string cmd; // 페이징 public string keywordValue; // 검색 키워드 값 public string pageTail; // 페이지 꼬리 ``` 변수 선언 부분에선 각 전역변수로 선언해야 하는 변수들을 전부 선언합니다. - 객체 선언 부분에선 DB객체에 대한 부분들을 정리합니다. - 파라미터 선언 부분에선 파라미터에 대한 변수를 정리합니다. - 오브젝트 선언 부분에선 DB컬럼이나 페이지에 사용되는 오브젝트들을 정리합니다. - 커맨드 선언 부분에선 커맨드(i:인서트, u:수정, d:삭제)에 대한 변수를 정리합니다. - 페이징 선언 부분에선 페이징속성에 대한 변수들을 정리합니다. 이 처럼 각 요소에 맞게 변수들을 선언합니다. ----------------- ##### 프로세스 부분 ```css protected void Page_Load(object sender, EventArgs e) { Check.browser(); Check.ssl(); Check.session(Session); // 처음 페이지를 읽었을 때 실행 할 코드 if (!IsPostBack) { // 폼 form(); } // 프로세스 else { try { // 파라미터 string cmd = Validation.requestValues(Request.Form["cmd"], ""); functionSeq = Convert.ToInt32(Validation.requestValue(Request.Form["functionSeq"])); functionName = Validation.requestValue(Request.Form["functionName"]); url = Validation.requestValue(Request.Form["url"]); useYn = Validation.requestValue(Request.Form["useYn"]); delFile = Validation.requestValues(Request.Form["delFile"], ""); delFileName = Validation.requestValues(Request.Form["delFileName"], ""); // DB 커넥션 con = DbHelper.dbConnection(Request.Url.Host.ToString()); con.Open(); // 등록 if (cmd == "i") { insert(); } // 수정 else if (cmd == "u") { update(); } // 삭제 else if (cmd == "d") { delete(); // 객체반환 ResotreObj.resotreObjReturn(con, dr); Response.Redirect("/dhmng/goods/functionList.aspx"); } // 파일삭제 else if (cmd == "fd") { fileDelete(); // 객체반환 ResotreObj.resotreObjReturn(con, dr); Response.Redirect("/dhmng/goods/functionForm.aspx?functionSeq=" + functionSeq); } // 객체반환 ResotreObj.resotreObjReturn(con, dr); Message.goPageCloseParentReload(); } catch (SqlException sqlException) { Response.Write(sqlException.Message); } finally { // 객체반환 ResotreObj.resotreObjReturn(con, dr); } } } ``` 프로세스 부분에선 페이지에서 실행되는 코드들을 큰단락씩 정리합니다. - 전달된 파라미터를 먼전 할당받습니다. - DB 를 사용하기 위해 커넥션오픈을 해줍니다. - 후에 커맨드에 따른 실행코드를 진행합니다. - 프로세스가 다 진행된 후엔 객체를 반환합니다. - 객체반환이 마지막 프로세스입니다. 그 후 페이지를 이동합니다. ----------------- ##### 프로세스 상세 부분 ```css /// <summary> /// 폼 /// </summary> public void form() { try { // 파라미터 functionSeq = Convert.ToInt32(Validation.requestValues(Request.QueryString["functionSeq"], "0")); // 수정 if (functionSeq > 0) { // DB 커넥션 con = DbHelper.dbConnection(Request.Url.Host.ToString()); con.Open(); // 셀렉트 string sql = "SELECT * FROM TB_FUNCTION WITH(NOLOCK) WHERE function_seq = " + functionSeq + " AND del_yn = 'N'"; SqlCommand com = new SqlCommand(sql, con); dr = com.ExecuteReader(); while (dr.Read()) { functionName = dr["function_name"].ToString(); imgName = dr["img"].ToString(); sysImgName = dr["sys_img"].ToString(); } // 커맨드 cmd = "u"; } // 등록 else { // 커맨드 cmd = "i"; } } catch (SqlException sqlException) { Response.Write(sqlException.Message); } finally { // 객체반환 ResotreObj.resotreObjReturn(con, dr); } } ``` 프로세스 상세부분에선 각 커맨드에 맞는 실제 프로세스들이 실행됩니다.<file_sep>/java/servlet_container_ebook/ch02/README.md ## 2. HTTP 프로토콜의 실제 <file_sep>/java/god_of_java/Vol.1/07. Array/README.md ## 7장. 여러 데이터를 하나에 넣을 수는 없을까요? ### 1. 하나에 많은 것을 담을 수 있는 배열이라는 게 있다는데... - PHP에서 가장 많이 다루고 제일 익숙한 만큼 차이점을 위주로 체크 - PHP로 구현했던 다차원배열 알고리즘 **Java**로 구현해보기 #### *참고사이트* - [coderbyte.com](http://coderbyte.com) - [checkio.org](http://checkio.org) _ _ _ Java에서 기본자료형의 배열은 다음과 같다. `int [] lottoNumbers` `int lottoNumbers[];` 이렇게 선언한 배열은 아직 몇 개의 데이터가 들어가는지 알 수가 없다. 100개가 들어가는지 1000개가 들어가는지 ...따라서 아래와 같이 초기화를 시켜줘야 한다. `int [] lottoNumbers = new int[7];` > 이때 `int` 자체는 기본 자료형이지만 , `int[]`와 같이 `int`를 배열로 만든 > `lottoNumbers`는 참조자료형이다. > 이전장에서 참조자료형의 객체를 생성할 때에는 반드시 **new** 를 사용해야한다고 했던것 기억 > 배열역시 참조 자료형이기때문에 일반적으로 *new*를 사용한다고 알아두자 (예외도 있다고 한다.) `int[] lottoNumbers;` `lottoNumbers = new int[7];` > 위와 같이 두줄로 선언해도 무방! - - - ### 2. 배열의 기본값 1. 기본 자료형 배열의 기본값은 각 자료형의 기본값과 동일하다. 2. 지역변수(메소드내에서 선언한 변수)의 경우에는 초기화를 하지 않으면 사용이 불가능하지만 배열에서는 지역변수라고 할지라도, 배열의 크기만 정해주면 에러가 발생하지 않는다.... ```java public void primitiveTypes() { byte[] byteArray = new byte[1]; short[] shortArray = new short[1]; int[] intArray = new int[1]; long[] longArray = new long[1]; float[] floatArray = new float[1]; double[] doubleArray = new double[1]; char[] charArray = new char[1]; boolean[] booleanArray = new boolean[1]; System.out.println("byteArray[0]=" + byteArray[0]); System.out.println("shortArray[0]=" + shortArray[0]); System.out.println("intArray[0]=" + intArray[0]); System.out.println("longArray[0]=" + longArray[0]); System.out.println("floatArray[0]=" + floatArray[0]); System.out.println("doubleArray[0]=" + doubleArray[0]); System.out.println("charArray[0]=[" + charArray[0] + "]"); System.out.println("booleanArray[0]=" + booleanArray[0]); } ``` > 위 내용을 돌려보면 기본자료형의 기본값이 잘 출력된다. > 다만 char의 경우엔 **space** 임을 상기.~ --- ### 추가 정리 (보충) 1. 배열 사용방법 1) 선언 2) 메모리 할당 3) 초기화 예1) `int a[];` -배열 선언 -- 이단계에서 크기정하면 안됨 주의 `a=new int[2]` - 메모리할당 -- **!!대괄호 주의** `a[0]=10` - 초기화 예2) 선언과 메모리 할당을 동시에 하는 방법 `int b[]=new int[3];` -배열 선언 + 메모리 할당 `b[0]=100` - 초기화 `b[3]=400` - 인덱스 초과오류 이미 초기화한 크기를 바꿀수 없음- **javascript와 다른점!** 예3) 선언과 메모리할당, 초기화를 동시에 하는 방법 `int [] c={1,2,3,4,5,}` > 또한 참조형 배열의 특징도 되새겨 보기 (스왑예제 생각) <file_sep>/guide/개발 라이브러리 가이드/CI/05. CI_PageNavigation.md <style>.blue {color:#2844de;font-size:18px;}.red {color:#dd4814;font-size:18px;}.ex {color:gray;}p.me{padding:10px 8px 10px;line-height:20px;border:1px solid black;}.center{text-align:center;}</style> ## 05 CI\_PageNavigation ──────────────────────순서────────────────────── 1. 사용 : controller/사용\_할\_클래스파일.php 2. 라이브러리 : libraries/CI\_PageNavigation.php ──────────────────────────────────────────────── CI\_PageNavigation은 pagenavigation을 이용하기 위해 비스톤스에서 작성한 라이브러리 입니다. #### 사용 : controller/사용\_할\_클래스파일.php ```js class 사용_할_클래스파일 extends CI_Controller{ function 사용_할_함수(){ // 페이징 검색조건에서 사용할 WHERE 설정 $sqlWhere = array( '컬럼명1'=>'값1', '컬럼명2'=>'값2' ); // 페이징 검색조건에서 사용할 LIKE 설정 $sqlLike = array( '컬럼명'=>'값' ); if($selectType == "") { // 전체 검색 $sqlLike = array('컬럼1' => '값1', '컬럼2' => '값2', '컬럼3' => '값3', ... , '컬럼5' => '값5'); } // 페이징 꼬리 설정 [페이징 꼬리 : URI에 떠다닐 값들로, 주로 검색조건이나 페이지번호에 해당합니다.] $arrTails = array( 'count' => $count, 'reserveBuilding' => $reserveBuilding, 'reserveNation' => $reserveNation, 'selectType' => $selectType, 'selectValue' => $selectValue ); // 총 레코드 [=행(row)] 수 $data['totRsCnt'] = $totRsCnt = $this->Board_dao->selectCount('tb_reserve', $sqlWhere, $sqlLike); // 출력할 리스트 내용 저장 $data['list'] = $list = $this->Board_dao->selectList('*','tb_reserve',$sqlWhere, $sqlLike , 'reserve_date desc', $count, $page); // =============================================== 페이지네비게이션 설정 =============================================== $this->ci_pagenavigation->pagenavigation($totRsCnt, $page, $count, 10, $arrTails); // ci_pagenavigation 라이브러리에 만들어져있는 pagenavigation()함수를 이용하여 pagenavigation을 셋팅합니다. // $totRsCnt = 게시물 총 갯수 // $page = 현재 페이지 // $count = 한 페이지에 보여줄 갯수 // 10 = 페이징 블럭 하나에 보여질 페이지 갯수 // $srrTails = 페이징 꼬리 $data['currentPageNum'] = $this->ci_pagenavigation->getCurrentPageNum(); // 현재 페이지 번호 : ci_pagenavigation 라이브러리에 만들어져있는 // getCurrentPageNum()함수를 이용하여 현재 페이지 번호를 알아냅니다. $data['allPageNum'] = $this->ci_pagenavigation->getAllPageNum(); // 전체 페이지 번호 : ci_pagenavigation 라이브러리에서 getAllPageNum()함수를 이용하여 전체 페이지 번호를 가져올 수 있습니다. $this->load->view('나타낼_view_페이지',$data); // 나타낼_view_페이지에 $data를 전달하여 view 페이지에서 $data의 값들을 사용할 수 있도록 합니다. } } ``` <br /> #### 라이브러리 : libraries/CI\_PageNavigation.php 라이브러리의 하단 부분에 용도별 페이지네비게이션 함수가 있습니다. <p class="me">1. <span class="red">관리자용</span> 페이징 설정 : <b class="red">getAdmin</b>PageNavigation()<br />2. <span class="red">프런트용</span> 페이징 설정 : <b class="red">Front</b>PageNavigation()<br />3. <span class="red">모바일용</span> 페이징 설정 : <b class="red">getMobile</b>PageNavigation()<br />4. <span class="red">부트스트랩을 사용한 관리자용</span> 페이징 설정 : <b class="red">getBootAdmin</b>PageNavigation()</p> 위의 함수중에서 해당되는 페이징을 뷰에 사용하시면 됩니다. ##### ex. front페이지.html `($totRsCnt != 0) ? $this->ci_pagenavigation->getFrontPageNavigation() : "" ;` -> $totRsCnt는 게시물 총 갯수임 ##### ex. admin페이지.html `($totRsCnt != 0) ? $this->ci_pagenavigation->getAdminPageNavigation() : "" ;` -> $totRsCnt는 게시물 총 갯수임 ##### ex. 부트스트랩 admin페이지.html `($totRsCnt != 0) ? $this->ci_pagenavigation->getBootAdminPageNavigation() : "" ;` -> $totRsCnt는 게시물 총 갯수임 ```js /** * @Class CI_PageNavigation * @Date 2015. 04. 27 * @Author 비스톤스 * <pre> * 페이지네비게이션 * </pre> */ class CI_PageNavigation { var $cnt,$page,$scale,$pageScale; # cnt = 총 레코드 갯수 # page = 현재 페이지 # scale = 페이지당 보여질 레코드 갯수 # pageScale = 한 블록요소당 보여질 페이지 갯수 var $DVS,$DVS_from,$DVS_to,$pageCount,$tails; # DVS = 한 블럭 요소당 레코드 갯수 # DVS\_from = 한블록에서 시작하는 레코드번호 # DVS\_to = 한블록에서 마지막으로 끝나는 레코드 번호 # $pageCount = 페이지 총 갯수 # $tails = 페이징 꼬리 var $phpSelf, $pageUrl; //======================================================================= // 함수설명 : 페이지 값을 셋팅 한다. //======================================================================= function PageNavigation($TotRsCnt,$page=0,$scale,$pageScale,$arr="") { $tailsString = ""; // 초기화 $this->page=$page; // page에 page값 저장 $this->scale=$scale; // scale에 scale값 저장 $this->pageScale=$pageScale; // pageScale에 pageScale 저장 $this->cnt=$TotRsCnt; // cnt에 TotRsCnt값 저장 $this->pageCount=ceil($TotRsCnt/$scale); // 페이지 갯수 저장 $this->DVS=$scale*$pageScale; // scale 곱하기 pageScale 저장 $this->DVS_from=(floor($page/$this->DVS))*$this->DVS; $page==0 ? $this->DVS_to=$this->DVS-1 : $this->DVS_to=(ceil(($page+1)/$this->DVS))*$this->DVS-1; // key 값의 비교연산자 있을시 제거 구문 추가 if (is_array($arr)) { while (list($key,$val)=each($arr)){ if(strpos($key, ' >=') || strpos($key, ' <=')){ $key = str_replace(' >=','',$key); $key = str_replace(' <=','',$key); }else{ $tailsString.="$key=$val&"; } } } // Codeigniter (index.php 제거) $this->phpSelf = explode("/index.php", strip_tags($_SERVER['PHP_SELF'])); $this->pageUrl = strip_tags($this->phpSelf[0].$this->phpSelf[1]); // normal php // $this->phpSelf = $_SERVER['PHP_SELF']; // $this->pageUrl = $this->phpSelf; $this->tails=$tailsString; } //======================================================================= // 함수설명 : 페이지 값을 얻는다. //======================================================================= # 총 페이지 수 function getAllPageNum() { return $this->pageCount ? $this->pageCount : 1; # $this->pageCount에 값이 있으면 $this->pageCount값을 반환하고, # $this->pageCount에 값이 없으면 1을 반환한다. } # 현재 페이지 위치 function getCurrentPageNum() { return ($this->page / $this->scale) + 1; # 현재페이지의 시작번호를 한블록당 페이지 갯수로 나눈뒤, 1을 더해주면 현재 페이지의 위치가 나옵니다. } //======================================================================= // 함수설명 : 페이지 하단에 표시 // 사 용 법 : $this -> getPageNavigation(); //======================================================================= // ------- 페이지 하단에 [1][2][3]... 표시 ------------ function getPageNavigation() { $output=""; for ($i=1;$i<ceil($this->cnt/$this->scale)+1;$i++) { # $i가 1에서 시작해서 총 페이지갯수 보다 크거나 같아질 때까지 반복 $j=($i-1)*$this->scale; # $j는 현재페이지까지의 페이지들의 첫번째 레코드의 값이다. if ($j<($this->DVS_from-1)) continue; # $j값이 현재블록의 첫번째 레코드-1 보다 작으면 계속 진행한다. if ($j>$this->DVS_to) break; # $j값이 현재블록의 마지막 레코드 보다 크면 멈춘다. if (($j>=$this->page)&&($j<($this->page+$this->scale))) { # $j가 현재페이지 번호보다 크거나 같고, 현재페이지까지의 레코드수를 더한값보다 작으면 [ == 현재페이지에 진하게 됨 ] $output.=" <li class='curr'><a style='background-color:gray; color:white; font-weight:bold; '>".$i."</a></li> "; # 현재 페이지 색상 표시 } else { $output.=" <li><a href='".$this->pageUrl."?$this->tails"."page=$j' >".$i."</a></li> "; # li 출력 } } return $output; } // 프런트용 페이징 function getFrontPage() { $output="&nbsp;&nbsp;"; for ($i=1;$i<ceil($this->cnt/$this->scale)+1;$i++) { # $i가 1에서 시작해서 총 페이지갯수 보다 적을때까지 반복 $j=($i-1)*$this->scale; # 이전페이지까지 레코드 수 if ($j<($this->DVS_from-1)) continue; # $j값이 현재블록의 첫번째 레코드-1 보다 작으면 계속 진행한다. if ($j>$this->DVS_to) break; # $j값이 현재블록의 마지막 레코드 보다 크면 멈춘다. if (($j>=$this->page)&&($j<($this->page+$this->scale))) { # $j가 현재페이지 번호보다 크거나 같고, 현재페이지까지의 레코드수를 더한값보다 작으면 [ == 현재페이지에 진하게 됨 ] $output.="<strong>$i</strong>"; } else { # $j가 현재페이지보다 작거나 $j가 현재페이지 마지막 레코드보다 크면 $output.="<a href='".$this->pageUrl."?$this->tails"."page=$j'>$i</a>"; # 페이지 숫자에 링크달아서 출력 } } return $output; } // 모바일용 페이징 function getMobilePage() { $output="&nbsp;&nbsp;"; for ($i=1;$i<ceil($this->cnt/$this->scale)+1;$i++) { # i가 1부터 페이지 총 갯수보다 작을때까지 1씩 증가하면서 반복 $j=($i-1)*$this->scale; # $j는 페이지 시작 번호 if ($j<($this->DVS_from-1)) continue; # $j가 블록의 마지막레코드 보다 작으면 계속 if ($j>$this->DVS_to) break; # $j값이 현재블록의 마지막 레코드 보다 크면 멈춘다. if (($j>=$this->page)&&($j<($this->page+$this->scale))) { # $j가 현재페이지 번호보다 크거나 같고, 현재페이지까지의 레코드수를 더한값보다 작으면 [ == 현재페이지에 진하게 됨 ] $output.="<li><a>$i</a></li>"; # 현재 페이지 숫자만 출력 } else { # $j가 현재페이지보다 작거나 $j가 현재페이지 마지막 레코드보다 크면 $output.="<li><a href='".$this->pageUrl."?$this->tails"."page=$j'>$i</a><li>"; # 페이지 숫자에 링크달아서 출력 } } return $output; } // ------- [이전 ??개] ----------- function getPageNavigation_Prev($icon) { # $icon은 용도를 분류 하는 기능을 한다. # 이미지가 없는 경우는 $icon에 no를 입력 받고, # mobile인 경우에 $icon에 mobile을, # $icon값이 no나 mobile이 아닌 경우 else구문을 실행한다. $output=""; if($icon == 'no'){ if ($this->DVS_from>=$this->DVS) { # 블록에서 시작하는 레코드 번호가 한 블록당 레코드 수보다 크거나 같으면 [ == 첫번째 블록이 아니면] $goBefore=$this->DVS_from-$this->scale; # [ 블록에서 시작하는 레코드번호 ] - [ 한 페이지에 보여지는 레코드 크기 ] # 해당 블록의 첫번째 페이지로 보내는 문장입니다. $output = " <li class='prev'><a href='".$this->pageUrl."?$this->tails"."page=$goBefore' class='btn_prev'>&#60;</a></li> "; # &#60;은 < 를 의미하는 HTML 특수문자코드입니다. } else { $output = " <li class='prev'><a href='".$this->pageUrl."?$this->tails"."page=0' class='btn_prev'>&#60;</a></li> "; # &#60; 은 < 를 나타내는 HTML 특수문자코드입니다. } } else if($icon == 'mobile'){ if ($this->DVS_from>=$this->DVS) { $goBefore=$this->DVS_from-$this->scale; $output = " <li class='prev'><a href='".$this->pageUrl."?$this->tails"."page=$goBefore' class='btn_prev'><img src='".SITE_URL."images/mobile/common/btn_prev.png' alt='이전페이지'/></a></li> "; } else { $output = " <li class='prev'><a href='".$this->pageUrl."?$this->tails"."page=0' class='btn_prev'><img src='".SITE_URL."images/mobile/common/btn_prev.png' alt='이전페이지'/></a></li> "; } }else{ if ($this->DVS_from>=$this->DVS) { $goBefore=$this->DVS_from-$this->scale; $output = " <li class='img prev'><a href='".$this->pageUrl."?$this->tails"."page=$goBefore' class='btn_prev'>$icon</a></li> "; } else { $output = " <li class='img prev'><a href='".$this->pageUrl."?$this->tails"."page=0' class='btn_prev'>$icon</a></li> "; } } return $output; } // ------- [다음 ??개] ----------- function getPageNavigation_Next($icon) { # $icon은 용도를 분류 하는 기능을 한다. # 이미지가 없는 경우는 $icon에 no를 입력 받고, # mobile인 경우에 $icon에 mobile을, # $icon값이 no나 mobile이 아닌 경우 else구문을 실행한다. $output=""; $pagePos = ($this->pageCount * $this->scale) - $this->scale; # (페이지 총 갯수 * 한페이지당 레코드 갯수) - 한페이지당 레코드 갯수 = 마지막 페이지를 가리키게 됩니다. if($icon == 'no'){ if ($this->cnt >= $this->DVS_to+$this->pageScale) { # 마지막-1번째 블록 이면 $goNext=$this->DVS_to+1; # 다음 블록의 첫번째 페이지를 가리키게 됩니다. $output = " <li class='next'><a href='".$this->pageUrl."?$this->tails"."page=$goNext' class='btn_next'>&#62;</a></li> "; } else { $output = " <li class='next'><a href='".$this->pageUrl."?$this->tails"."page=$pagePos' class='btn_next'>&#62;</a></li> "; } } else if($icon == 'mobile'){ if ($this->cnt >= $this->DVS_to + $this->pageScale) { $goNext=$this->DVS_to+1; $output = " <li class='next'><a href='".$this->pageUrl."?$this->tails"."page=$goNext' class='btn_next'><img src='".SITE_URL."images/mobile/common/btn_next.png' alt='다음페이지'/></a></li> "; } else { $output = " <li class='next'><a href='".$this->pageUrl."?$this->tails"."page=$pagePos' class='btn_next'><img src='".SITE_URL."images/mobile/common/btn_next.png' alt='다음페이지'/></a></li> "; } } else{ if ($this->cnt>=$this->DVS_to+$this->pageScale) { $goNext = $this->DVS_to+1; $output = "<li class='img next'><a href='".$this->pageUrl."?$this->tails"."page=$goNext' class='btn_next'>$icon</a></li> "; } else { $output = "<li class='img next'><a href='".$this->pageUrl."?$this->tails"."page=$pagePos' class='btn_next'>$icon</a></li> "; } } return $output; } // ------- 이전 페이지 ----------- function getPagePrev($icon_up) { $output=""; $pagePos = $this->page - $this->scale; // ----------- ------------- // page = 현재 페이지 게시물 시작번호 // scale = 페이지당 게시물 갯수 // $pagePos = 페이지당 [ 게시물 시작번호 - 게시물 갯수 ] // $pagePos 가 음수가 되면 이전페이지가 없는 것이므로 첫번째 페이지로 이동해야 한다. // // $pagePos 가 0이면 첫번째 페이지임. if ($pagePos >= -1) { if($icon_up == 'boots'){ $output = " <li><a href='".$this->pageUrl."?$this->tails"."page=0' aria-label='Previous'>&lt;</a></li> "; }else{ $output = " <li class='prev'><a href='".$this->pageUrl."?$this->tails"."page=$pagePos' class='btn_prev02'>$icon_up</a></li> "; } } else { if($icon_up == 'boots'){ $output = " <li><a href='".$this->pageUrl."?$this->tails"."page=0' aria-label='Previous'>&lt;</a></li> "; }else{ $output = " <li class='prev'><a href='".$this->pageUrl."?$this->tails"."page=0' class='btn_prev02'>$icon_up</a></li> "; } } return $output; } // ------- 다음 페이지----------- function getPageNext($icon_up) { $output=""; $pagePos1 = $this->page + $this->scale; // $pagePos1 = 현재페이지 게시물 시작번호 + 페이지당 게시물 갯수. // $pagePos1 = 다음페이지의 첫번째 게시물을 가리키게 됨. $pagePos = ($this->pageCount * $this->scale) - $this->scale; // $pagePos = (페이지 갯수 - 1) * 페이지당 게시물 갯수 // $pagePos = 마지막 페이지를 가리키게 됨 if ($pagePos1 <= $pagePos) { // $pagePos1이 마지막 페이지보다 작거나 같으면, // 다음페이지로 이동 // $pagePos1이 마지막 페이지보다 크면 마지막페이지로 이동 if($icon_up == 'boots'){ $output = " <li><a href='".$this->pageUrl."?$this->tails"."page=$pagePos1' aria-label='Next'>&gt;</a></li>"; }else{ $output = " <li class='next'><a href='".$this->pageUrl."?$this->tails"."page=$pagePos1' class='btn_next02 scale'>$icon_up</a></li> "; } } else { //$output = ""; if($icon_up == 'boots'){ $output = " <li><a href='".$this->pageUrl."?$this->tails"."page=$pagePos' aria-label='Next'>&gt;</a></li> "; }else{ $output = " <li class='next'><a href='".$this->pageUrl."?$this->tails"."page=$pagePos' class='btn_next02'>$icon_up</a></li> "; } } return $output; } // ------- 맨처음 ----------- function getPageFirst($icon) { // 첫페이지로 이동 $output=""; // echo $icon; // $pagePos = $this->DVS_to+$this->pageScale; if($icon == 'boots'){ $output = " <li><a href='".$this->pageUrl."?$this->tails"."page=0' aria-label='Fisrt'>&lt;&lt;</a></li> "; } else if($icon == 'no'){ $output = " <li class='first' ><a href='".$this->pageUrl."?$this->tails"."page=0'>&#60;&#60;</a></li> "; } else if($icon == 'mobile'){ $output = " <li class='first' ><a href='".$this->pageUrl."?$this->tails"."page=0'><img src='".SITE_URL."images/mobile/common/btn_first.png' alt='처음페이지'/></a></li> "; } else{ $output = " <li class='img'><a href='".$this->pageUrl."?$this->tails"."page=0'>$icon</a></li> "; } return $output; } // ------- 마지막 ----------- function getPageLast($icon) { $output=""; $pagePos = ($this->pageCount * $this->scale) - $this->scale; // 마지막 페이지로 이동 if($pagePos <= -1) { // 게시물이 하나도 없는 경우 // 첫번째 페이지로 이동 $pagePos = $pagePos + $this->scale; } if($icon == 'boots'){ $output = " <li><a href='".$this->pageUrl."?$this->tails"."page=$pagePos' aria-label='Last'>&gt;&gt;</a></li> "; } else if($icon == 'no'){ $output = " <li class='last'><a href='".$this->pageUrl."?$this->tails"."page=$pagePos'>&#62;&#62;</a></li> "; } else if($icon == 'mobile'){ $output = " <li class='last'><a href='".$this->pageUrl."?$this->tails"."page=$pagePos'><img src='".SITE_URL."images/mobile/common/btn_last.png' alt='마지막페이지'/></a></li> "; } else{ $output = " <li class='img'><a href='".$this->pageUrl."?$this->tails"."page=$pagePos'>$icon</a></li> "; } return $output; } ```<file_sep>/java/god_of_java/Vol.2/README.md ## VOL.2 주요 API 응용편<file_sep>/java/god_of_java/Vol.1/10. 자바는 상속이라는 것이 있어요/README.md ## 10장. 자바는 상속이라는 것이 있어요 ### 1. 자바에서 상속이란? 상속에대해 알아보기 전에 예제 코드를 먼저 보자. > Parent.java (부모클래스) ```java package c.inheritance; public class Parent { public Parent() { System.out.println("Parent Constructor"); } public void printName() { System.out.println("printName() - Parent"); } } ``` > Child.java (자식클래스) ```java package c.inheritance; public class Child extends Parent { public Child() { System.out.println("Child Constructor"); } } ``` > `extends` 는 자바의 예약어로 상속에 사용된다. > 이렇게 하면 **부모 클래스에 선언되어 있는 `public` 및 `protected`로 선언되어 있는 모든 변수와 메소드를 내가 갖고 있는 것처럼 사용할 수 있다.** > 즉 접근제어자가 없거나 `private`로 선언된 것들은 자식클래스에서 사용할 수 없다. UML의 클래스 다이어그램 -> 빈화살표로 상속 표시는 이고잉 강의 생각하면 될 듯 ```java package c.inheritance; public class Inheritance { public static void main(String[] args) { Child child = new Child(); child.printName(); } } ``` > 상속클래스까지 구현한 후 컴파일 실행해보면 부모클래스의 메소드를 호출하지도 않았는데, 확장을 한 클래스가 생성자를 호출하면, 자동으로 부모 클래스의 기본생성자(매개변수없는)가 호출되는 것을 알수 있다. 정리해보면 - 부모 클래스에서는 기본생성자를 만들어 놓는 것 이외에는 상속을 위해서 별도로 작업을 할 필요는없다. - 자식 클래스는 클래스 선언시 `extends`다음에 부모 클래스 이름을 적어준다 - 자식 클래스의 생성자가 호출되면, 자동으로 부모 클래스의 매개 변수 없는 생성자가 실행된다. - 자식 클래스에서는 부모 클래스에 있는 public, protected로 선언된 모든 인스턴스 및 클래스 변수와 메소드를 사용할 수 있다. - 또한 확장된 클래스(여기서는 자식클래스)는 추가적인 메소드를 만들어도 전혀 문제가 없다. ### 2. 상속과 생성자 앞 절에서 상속에 대해 정리할 때 다음과 같이 말했다. - 부모 클래스에서는 기본 생성자를 만들어 놓는 것 이외에는 상속을 위해서 아무런 작업을 할 필요는 없다. 만약 부모 클래스에 기본 생성자가 없다면 어떻게 될까? ```java public class Parent { /* public Parent() { System.out.println("Parent Constructor"); } */ public void printName() { System.out.println("printName() - Parent"); } } ``` > 위와 같이 부모클래스의 기본생성자를 주석처리하고 부모파일을 재컴파일한후 상속클래스를 실행하면 > 문제가 없다. > 다만 이때 만약 기본생성자가 아닌 매개변수가 필요한 생성자가 있을경우에는 이야기가 달라진다. 이건 자식클래스의 모든 생성자가 실행될 때 `Parent()`의 기본생성자를 찾는데, 이미 정의한 생성자의 경우 기본생성자가 없기 때문이다. > 해결방법은 다음과 같다 - 부모클래스인 `Parent` 클래스에 기본생성자를 만든다(매개변수가 없는) - 자식 클래스에서 부모클래스의 생성자를 명시적으로 지정하는 `super()`를 사용한다. > 메소드처럼 사용하지 않고 `super.printName()`으로 사용하면 부모클래스에 있는 `printName()`이라는 메소드를 호출한다는 의미다. 만약 여기서 참조자료형을 매개변수로 받는 생성자가 하나 더 있다면 어떻게 될까? > 일반적으로는 이렇게 부모클래스에 같은 타입을 매개 변수로 받는 생성자가 있으면 다음과 같이 처리한다 ```java package c.inheritance; public class Child extends Parent { public Child() { super(null); System.out.println("Child Constructor"); } public Child(String name) { super(name); /// 이부분 System.out.println("Child(String) Constructor"); } } ``` > 또한 `super()`의 위치는 반드시 **생성자 첫줄**에 있어야만 한다. 이번 절의 총정리 1. 생성자에서는 `super()`를 명시적으로 지정하지 않으면, 자동으로 super()가 추가된다 2. 만약, 부모클래스에 매개변수가 없는 생성자가 정의되어 있지 않고, 매개 변수가 있는 생성자만 정의되어 있을 경우에는 명시적으로 `super()`에서 매개변수가 있는 생성자를 호출하도록 해야만 한다. --- ### 3. 메소드 Overriding 자식클래스에서 부모클래스에 있는 메소드와 동일하게 선언하는 것을 **"메소드 Overriding"**이라고 한다. - 접근제어자,리턴타입, 메소드이름, 매개변수 타입 및 개수가 모두 동일해야만 **Overriding**이라고 부른다. > 먼저 부모클래스엔 다음과 같은 메소드가 있다. ```java public void printName() { System.out.println("printName() - Parent"); } ``` > 여기에 자식클래스에 위와 동일한 메소드를 생성해보자 그 후에 모든클래스를 컴파일하고 상속클래스를 실행하면 부모클래스의 메소드가 아닌 자식클래스에 똑같이 선언한 메소드가 호출된 것을 알수 있다. > 다시말해서 부모클래스보다 자식클래스의 메소드가(동일한) 우선시된다는 뜻이다. -> 동일한 시그네쳐를 가진다 라고 한다. - 생성자의 경우 자동으로 부모클래스에 있는 생성자를 호출하는 `super()`가 추가되지만, 메소드는 그렇지 않다. 이게 바로 **"메소드 Overriding"**이다 - 이때 오버라이딩이 제대로 동작하려면 부모클래스를 오버라이딩한 메소드의 리턴타입을 다르게 리턴하면 안 된다. - 또한 접근제어자는 범위가 확대대는것은 문제가 안되지만 축소되는 것은 문제가 된다. > `Overriding`에 대한 정리 1. 메소드 Overriding은 부모 클래스의 메소드와 동일한 시그네쳐를 갖는 자식 클래스의 메소드가 존재할 때 성립된다. 2. Overriding된 메소드는 부모클래스와 동일한 리턴 타입을 가져야만 한다. 3. Overriding된 메소드의 접근 제어자는 부모 클래스에 있는 메소드와 달라도 되지만, 접근 권한이 확장되는 경우에만 허용된다. 접근 권한이 축소될 경우에는 컴파일 에러가 발생한다. 용어가 비슷해서 헷갈릴수 있는 `Overloading`, `Overriding`을 구별해보자 1. Overloading : 확장 (메소드의 매개 변수들을 확장하기 때문에, 확장) 2. Overriding : 덮어씀 (부모 클래스의 메소드 시그니쳐를 복제해서 자식클래스에서 새로운 것을 만들어 내어 부모 클래스의 기능은 무시하고, 자식 클래스에서 덮어씀) ### 4.참조 자료형의 형 변환 > Parent 클래스 ```java public class Parent2{ public Parent(){ } pubilc Paretn2(String name){ } public void printName(){ System.out.println("printName() - Parent"); } } ``` > Child 클래스 ```java public class Child2 extends Parent2{ public Child2(){ } pubilc Child2(String name){ } public void printName(){ System.out.println("printName() - Parent"); } public void printAge(){ System.out.println("printAge() - 18 month"); } } ``` 이렇게 부모 자식간의 상속관계가 성립될 경우 다음과 같은 객체 선언이 가능하다. ```java Parent2 p2 = new Chile2(); ``` > Parent 클래스에서는 Child 클래스에 있는 모든 변수와 메소드를 사용할 수도 있고 그렇지 않을 수도있다. > 즉, Chile클래스에 추가된 메소드나 변수가 없을 경우 가능하다 참조 자료형은 자식 클래스의 타입을 부모클래스의 타입으로 형 변환하면 부모 클래스에서 호출할 수 있는 메소드들은 자식 클래스에서도 호출 할 수 있으므로 전혀 문제가 안된다. 따라서 형 변환을 우리가 명시적으로 해 줄 필요가 없다. > 소스를 통해 알아보자 ```java public class Inheritance2{ public void objectCas(){ Parent parent =new Parent(); Child child=new child(); Parent paretn2=child; Child child2=(Child)parent2; } } ``` 그럼 이런 형변환은 왜 이렇게 머리아프게 써야하는 걸까? > 다음의 메소드를 보자 ```java public Class Inheritance3{ public void objectCast2(){ Parent[] parentArray=new Parent[3]; parentArray[0]=new Child(); parentArray[2]=new Parent(); parentArray[2]=new Child(); } } ``` > Parent 배열은 3개의 값을 저장할 수 있는 공간을 가진다. 그런데, 0번째 배열과 2번째 배열은 Child 클래스의 객체를 할당한 것을 볼 수 있다. > 이렇게 코딩해도 전혀 문제는 없다 이와 같이 일반적으로 여러개의 값을 처리하거나, 매개변수로 값을 전달 할 때에는 보통 부코 클래스의 타입으로 보낸다. 이렇게 하지 않으면 배열과 같이 여러 값을 한번에 보낼 때 각 타입별로 구분해서 메소드를 만들어야 하는 문제가 생길수도 있기 때문이다. 그럼 여기서 `parentArry` 라는 배열의 타입이 Child 인지 Parent 인지 어떻게 구분할 수 있을까? > 이런 경우에 사용하라고 있는 것이 바로 `instanceof` 라는 예약어다. > 이 objectCast2()메소드에 instanceof를 사용하여 타입을 구분하는 코드를 넣으면 다음과 같다 ```java public void objectCast2(){ // 생락 for(Parent tempParent:parentArray){ if(tempParent instanceof Child){ // 1 System.out.println("Child"); } else if(tempParent instanceof Parent){ //2 System.out.println("Parent"); } } } ``` `instanceof`의 앞에는 객체를 , 뒤에는 클래스(타입)를 지정해 주면 > 그러면 이 문장은 true나 false와 같이 boolean 형태의 결과를 제공한다. > 그래서 parentArray의 0번재 갑은 child 클래스의 객체이므로 1번 조건에서 true > 2번 조건에서 true 2번째 값은 true 여야 한다. `instanceof`의 유의할 점 > `instanceof`를 사용하여 타입을 점검할 때에는 가장 하위에 있는 자식 타입부터 확인을 해야 제대로 타입점검이 가능하다. - 참조자료형도 형 변환이 가능하다. - 자식 타입의 객체를 부모 타입으로 형 변환 하는 것은 자동으로 된다. - 부모 타입의 객체를 자식 타입으로 형 변환을 할 때에는 명시적으로 타입을 지정해 주어야 한다. 이때, 부모타입의 실제 객체는 자식 타입이어야 한다. - `instanceof`예약어를 사용하면 객체의 타입을 확인할 수 있다. - `instanceof`로 타입 확인을 할 때 부모 타입도 true라는 결과를 제공한다. 객체의 형 변환은 매우 중요하다. ### 5.Polymorphism Polymorphism(폴리몰피즘)이란 말은 우리나라말로 다형성이이다. 다형성이란 말은 "형태가 다양하다"라는 말이다. ```java public class ChildOther extends Parent{ public ChildOther(){ } public void printName(){ System.out.println("printName() - childOther"); } } ``` > 자바의 자식 클래스는 백개를 만들든, 만개를 만들든 상관없다. ```java public void callPrintName(){ Parent2 parent1=new Parent2(); Parent2 parent2=new Child2(); Parent2 parent3=new ChildOther(); parent1.printName(); parent2.printName(); parent3.printName(); } ``` > 위 소스를 main()메소드해서 불러와서 실행해 보면 각 객체의 타입은 모두 Parent 타입으로 선언되어 있는데도 불구하고 > `printName()` 의 결과는 상의하다 > 다시 말해 선언시에는 모두 Parent 타입으로 선언했지만, 실제 메소드 호출된 것은 생성자를 사용한 클래스에 있는 것이 호출되었다. > 이와 같이 **"형 변환을 하더라도, 실제 호출되는 것은 원래 객체에 있는 메소드가 호출된다"**는 것이 바로 **다형성**이다. ### 6. 자식 클래스에서 할 수 있는 일들을 다시 정리해보자 1. 생성자 - 자식 클래스의 생성자가 호출되면 자동으로 부모클래스의 매개변수가 없는 기본생성자가 호출된다.명시적으로 `super()`라고 지정할 수도 있다. - 부모 클래스의 생성자를 명시적으로 호출하려면 `super()`를 사용하면 된다. 2. 변수 - 부모 클래스에 `private`로 선언된 변수를 제외한 모든 변수가 자신의 클래스에 선언된 것처럼 사용할 수 있다. - 부모 클래스에 선언된 변수와 동일한 이름을 가지는 변수를 선언할 수도 있다. 하지만, 이렇게 엎어 쓰느 것은 권장하지 않는다. - 부모 클래스에 선언되어 있지 않는 이름의 변수를 선언할 수 있다. 3. 메소드 - 변수처럼 부모 클래스에 선언된 메소드들이 자신의 클래스에 선언된 것처럼 사용할 수 있다. - 부모 클래스에 선언된 메소드와 동일한 시그니쳐를 사용함으로써 메소드를 `Overriding`할 수 있다. - 부모 클래스에 선언되어 있지 않은 이름의 새로운 메소드를 선언할 수 있다. ==직접해봅시다.(p. 312)== ```java public class Animal { String name; String kind; int legCount; int iq; boolean hasWing; public void move(){ System.out.println("움직였다."); } public void eatFood(){ System.out.println("음식을 먹었다."); } public static void main(String[] args) { Animal a = new Animal(); Animal ad = new Dog(); Animal ac = new Cat(); System.out.println("=======Animal======="); a.move(); a.eatFood(); System.out.println("=======Dog======="); ad.move(); ad.eatFood(); System.out.println("=======Cat======="); ac.move(); ac.eatFood(); } } class Dog extends Animal { int age; String color; public void move(){ System.out.println("개가 움직였다."); } public void eatFood(){ System.out.println("개가 사료를 먹었다."); } } class Cat extends Animal { int jumpDistance; public void move(){ System.out.println("고양이가 움직였다."); } public void eatFood(){ System.out.println("고양이가 우유를 먹었다."); } } ``` #### 정리해 봅시다. 1. 상속을 받는 클래스의 선언문에 사용하는 예약어는 무엇인가요? -> extends 2. 상속을 받은 클래스의 생성자를 수행하면 부모의 생성자도 자동으로 수행되나요? -> 예 => 확장을 한 클래스가 생성자를 호출하면, 자동으로 부모 클래스의 "기본 생성자"가 호출된다. 3. 부모 클래스의 생성자를 자식 클래스에서 직접 선택하려고 할 때 사용하는 예약어는 무엇인가요? -> super() 4. 메소드 Overriding과 Overloading을 정확하게 설명해 보세요. ->오버라이딩은 덮어쓰는 개념으로 부모클래스의 메소드를 재선언하여 확장성을 높힐수 있다. 부모의 기능은 가져오면서 추가적인 메소드를 구현할 수 있다. 오버로딩은 확장의 의미로 매개변수를 달리 받는 메소드나 생성자를 구현할수 있다. **=> Overriding은 자식 클래스에서 부모 클래스에 선언된 메소드의 선언 구문을 동일하게 선언하여 사용하는 것을 의미한다. 즉, public void printName()이라는 메소드가 부모클래스에 있고, 자식 클래스에도 동일한 메소드를 선언한다는 것이다. 혼동되기 쉬운 Overloading은 상속관계와 거의 상관 없이 메소드의 이름을 동일하게 하고, 매개변수만 다르게 하는 것을 의미한다.** 5. A가 부모, B가 자식 클래스라면 A a=new B(); 의 형태로 객체 생성이 가능한가요? -> 가능하다 6. 명시적으로 형변환을 하기 전에 타입을 확인하려면 어떤 예약어를 사용해야 하나요? -> instanceof 7. 6번 문제에서 사용한 예약어의 좌측에는 어떤 값이, 우측에는 어떤 값이 들어가나요? -> 좌측에는 객체를 우측에는 클래스타입을 => 좌측에는 확인하고자 하는 변수를, 우측에는 클래스 이름이 위치 8. 6번 문제 예약어의 수행 결과는 어떤 타입으로 제공되나요? ->boolean 9. Polymorphism이라는 것은 도대체 뭔가요? -> 다형성으로 형변환을 하더라도 실제 객체의 메소드를 불러오는걸 말한다. => 자식 클래스는 자신만의 "행위"를 가질 수 있지만, 부모 클래스에 선언된 메소드들도 공유 가능하다는 것을 의미한다. 다시 말해, 부모 클래스의 타입으로 변수를 선언하고, 자식 클래스의 생성자를 사용할 경우 overriding된 메소드를 호출하면 자식 클래스에 선언된 메소드가 호출되고, 부모 클래스의 메소드도 공유 가능하다는 것을 의미한다. <file_sep>/java/diskstaion_java_lec/05 Interface/README.md ### 인터페이스 | 일반클래스의 멤버| 추상클래스 | 인터페이스 |--------|--------| --- | | 1. 멤버변수 | 1~6가 다 멤버로 들어가고 이에 추가로 7. 추상메소드가 추가됨 | 1.final변수와 2.추상메소드로만 구성됨 | 2. 클래스변수 | | 3. 생성자 | | 4. 일반메소드 | | 5. 클래스메소드 | | 6. final변수등 | <file_sep>/guide/개발 라이브러리 가이드/C#.NET/1.라이브러리.MD # C#.NET 라이브러리 1. 개요 2. 폴더구성 3. 어플리케이션 3. 개발 툴 4. 기본문법 --- ##### 1.개요 C#.NET 프로젝트에 도입할 수 있도록 비스톤스에서 개발할 라이브러리입니다. C#.NET 프로그래밍에 효율적인 코드와 향후 유지보수를 위해 최적화된 코드들로 구성했습니다. --------------- ##### 2. 폴더구성 project - application - xxx.cs - bin - xxx.dll - css - css - images - 이미지 - js - js - mng - 관리자 - uploads - 파일 - web.config - ajaxView.aspx - default.aspx | 폴더 및 파일 명 | 내용| |--------|--------| | application| 라이브러리의 핵심 cs파일들이 있는 폴더입니다. | | bin | 컴파일한 dll이나 기타 다른 dll을 모아두는 폴더입니다. | | css | css 모아두는 폴더입니다. | | jd | js를 모아두는 폴더입니다. | | images | 이미지를 모아두는 폴더입니다. | | mng | 관리자 파일들을 모아두는 폴더입니다. | | uploads | 업로드되는 파일들을 모아두는 폴더입니다. | | web.cof | 웹 설정 파일 입니다. | | ajaxView | Ajax를 사용할 시 사용되는 파일입니다. | | default | 기본파일 입니다. | --------------- <file_sep>/게시판만들기/c-cgi-mysql 게시판 만들기/cgi-bin/test/hashTableTest.c #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_HASH_BUCKET 10 #define MAX_HASH_KEY MAX_HASH_BUCKET-1 #define HASH_KEY_GET(data) data % MAX_HASH_BUCKET; #define IS_SAME_NODE(a, b) ( a->data == b ) /* * Return code. */ typedef enum { RET_OK = 0, RET_NOK } ret_code_t; /* * hash node */ typedef struct _hash_node { int data; struct _hash_node *next; } hash_node_t; /* * hash hash table */ typedef struct _hash_table { int key; hash_node_t *right; struct _hash_table *next; } hash_table_t; /* * MFG HASH TABLE */ hash_table_t hash_table[MAX_HASH_BUCKET]; /* * add node */ void add_node(int data, int key) { hash_node_t *tmp_node; tmp_node = hash_table[key].right; if(tmp_node != NULL) { while(tmp_node->next != NULL) { tmp_node = tmp_node->next; } tmp_node->next = (hash_node_t *)malloc(sizeof(hash_node_t)); tmp_node->next->data = data; tmp_node->next->next = NULL; } else { tmp_node = (hash_node_t *)malloc(sizeof(hash_node_t)); tmp_node->data = data; tmp_node->next = NULL; hash_table[key].right = tmp_node; } } /* * delete node */ int delete_node(int data, int key) { hash_node_t *first_node = hash_table[key].right; hash_node_t *cur_node = first_node; hash_node_t *pre_node = NULL; if ( first_node == NULL ) return RET_NOK; while ( cur_node ) { if( IS_SAME_NODE(cur_node, data)) { if( cur_node == first_node ) hash_table[key].right = cur_node->next; else pre_node->next = cur_node->next; free(cur_node); return RET_OK; } pre_node = cur_node; cur_node = cur_node->next; } return RET_NOK; } /* * lookup node */ void *lookup_node(int data, int hash_key) { hash_node_t *cur_node; int ii; cur_node = hash_table[hash_key].right; while(cur_node != NULL) { if (IS_SAME_NODE(cur_node, data)) return cur_node; cur_node = cur_node->next; } return NULL; } /* * display data */ void display_data() { hash_node_t *tmp_node; int ii; printf("\n"); for(ii=0; ii<MAX_HASH_BUCKET; ii++) { tmp_node = hash_table[ii].right; printf("hash_table[%3d] : ", ii); while(tmp_node!=NULL) { printf("%d ",tmp_node->data); tmp_node = tmp_node->next; } printf("\n"); } } /* * init hash table */ void create_hash_table() { int ii; memset(hash_table, 0, sizeof(hash_table)); /* hash bucket except the last one */ for(ii=0; ii<MAX_HASH_KEY; ii++) { hash_table[ii].key = ii; hash_table[ii].right = NULL; hash_table[ii].next = &hash_table[ii+1]; } /* set last bucket */ hash_table[MAX_HASH_KEY].key = MAX_HASH_KEY; hash_table[ii].right = NULL; hash_table[ii].next = NULL; } /* * main */ void main() { int number; int data, key; ret_code_t rc; /* init hash table */ create_hash_table(); for(;;) { printf("\n\n"); printf("Command = {1(inseart)|2(delete)|3(display)|4(exit)}\n"); printf("Enter Command : "); scanf("%d", &number); switch(number) { case 1: printf("insert data : "); scanf("%d", &data); key = HASH_KEY_GET(data); if ( lookup_node(data, key) != NULL ) { printf("alread exist!!\n"); continue; } add_node(data, key); break; case 2: { printf("delete data : "); scanf("%d", &data); key = HASH_KEY_GET(data); rc = delete_node(data, key); if ( rc != RET_OK ) { printf("not found\n"); } break; } case 3: display_data(); break; case 4: exit(1); default: printf("Oops Wrong Number Entered!!\n\n"); break; } } } ///////////////////////////////////////// /* (17:26:46 AM) $ ./hash Command = {1(inseart)|2(delete)|3(display)|4(exit)} Enter Command : 1 insert data : 11 Command = {1(inseart)|2(delete)|3(display)|4(exit)} Enter Command : 1 insert data : 1111 Command = {1(inseart)|2(delete)|3(display)|4(exit)} Enter Command : 2 delete data : 1 not found Command = {1(inseart)|2(delete)|3(display)|4(exit)} Enter Command : 3 hash_table[ 0] : hash_table[ 1] : 11 1111 hash_table[ 2] : hash_table[ 3] : hash_table[ 4] : hash_table[ 5] : hash_table[ 6] : hash_table[ 7] : hash_table[ 8] : hash_table[ 9] : Command = {1(inseart)|2(delete)|3(display)|4(exit)} Enter Command : 4 */<file_sep>/java/god_of_java/Vol.2/07. 자바랭 다음으로 많이 쓴느애들은 컬렉션-Part3(Map)/README.md ## 7장. 자바랭 다음으로 많이 쓰는 애들은 컬렉션-Part3(Map) ### Map이란? `Map`은 `키` 와 `값`으로 이루어져 있다. - 모든 데이터는 키와 값이 존재한다. - 키가 없이 값만 저장될 수는 없다. - 값이 없이 키만 저장할 수도 없다. - 키는 해당 Map에서 고유해야만 한다. - 값은 Map에서 중복되어도 전혀 상관없다. - Map은 java.util 패키지의 Map이라는 이름의 인터페이스로 선언되어 있고, 구현해 놓은 클래스들도 많이 있다. > 여러가지 메소드가 있지만 꼭 기억해야할 메소드는 `put()`, `get()`, `remove()` 가 있다 ### Map을 구현한 주요 클래스들을 살펴보자 Map 인터페이스를 구현한 클래스들은 매우 다양하고 많다. 그 중에서 HashMap, TreeMap, LinkedHasMap 등이 가장 유명하고 애용하는 클래스다 그리고, Hashtable 클래스라는 것도 있는데, Map인터페이스를 구현하기는 했지만 일반적인 Map인터페이스를 구현한 클래스들과는 다르다 - Map은 컬렉션 뷰를 사용하지만, Hashtable은 Enumeration객체를 통해서 데이터를 처리한다. - Map은 키,값, 키-값 쌍으로 데이터를 순환하여 처리할 수 있지만, Hashtable은 이중에서 키-값 쌍으로 데이터를 순환하여 처리할 수 없다. - Map은 이터레이션을 처리하는 도중에 데이터를 삭제하는 안전한 방법을 제공하지만, Hashtable은 그러한 기능을 제공하지 않는다. 또한, HashMap 클래스와 Hashtable 클래스는 다음과 같은 차이가 있다. | 기능 | HashMap | Hashtable |--------|--------| | 키나 값에 nul 저장 가능 여부 | 가능 | 불가능 | 여러 쓰레드에 동시 접근 가능 여부 | 불가능 | 가능 ### HashMap 클래스에 대해서 자세히 알아보자 > HashMap의 상속관계 ```java java.lang.Object java.util.AbstractMap<K,V> java.util.HashMap<K,V> ``` - 대부분의 주요 메소드는 부모 클래스인 AbstractMap 클래스가 구현해 놓았다. ##### HashMap의 생성자는 4개가 있다. 이중 HashMap객체를 생성할 때에는 대부분 매개변수가 없는 생성자를 사용한다. 하지만, 담을 데이터 개수가 많은 경우에는 초기 크기를 지정해주는 것을 권장한다. > HashMap의 키는 기본자료형과 참조자료형 모두 될 수 있다. > 그래서 보통은 int나 long같은 숫자나 String클래스를 키로 많이 사용한다. > 하지만, 직접 어떤 클래스를 만들어 그 클래스를 키로 사용할 때에는 Object클래스의 hashCode()메소드와 equals()메소드를 잘 구현해 놓아야만 한다. ### HashMap 객체에 값을 넣고 확인해보자 Map에서는 데이터를 추가한다고 표현하지 않고, 데이터를 넣는다고 표현한다. 따라서 `add()`가 아닌 `put()`이라는 메소드를 사용한다. ```java import java.util.HashMap; public class MapSample { public static void main(String[] args) { MapSample sample=new MapSample(); sample.checkHashMap(); } public void checkHashMap(){ HashMap<String, String> map=new HashMap<String,String>(); map.put("A", "a"); System.out.println(map.get("A")); System.out.println(map.get("B")); } } ``` > 출력결과 ```java a null ``` Collection에서는 해당 위치에 값이 없을 때에는 `ArrayIndexOutOfBoundsException`이라는 예외가 발생하지만 Map에서는 `null`을 리턴한다. > 그렇다면 HashMap 객체에 put()메소드를 사용하여 이미 존재하는 키로 값을 넣을때에는 어떻게 될까? ArrayList 클래스가 add(), set()으로 이용했던것과는 달리 HashMap과 같이 Map관련 클래스에서는 새로운 값을 추가하거나, 수정할 때 모두 put()을 사용한다. ### HashMap 객체의 값을 확인하는 다른 방법들을 알아보자 HashMap에 어떤 키가 있는지를 확인하려면 어떻게 해야 할까? 그럴때 사용하는 것이 `keySet()`메소드다. > 메소드 이름에서 알 수 있듯이 keySet()메소드의 리턴 타입은 `Set`이다 > 그러므로, Set의 제네릭 타입은 "키"의 제네릭 타입과 동일하게 지정해 주면 된다. ```java import java.util.Collection; import java.util.Set; import java.util.HashMap; public class MapSample { public static void main(String[] args) { MapSample sample=new MapSample(); sample.checkHashMap(); } public void checkHashMap(){ HashMap<String, String> map=new HashMap<String,String>(); map.put("A", "a"); //System.out.println(map.get("A")); //System.out.println(map.get("B")); map.put("C", "c"); map.put("D", "d"); Set<String> keySet=map.keySet(); for (String tempKey : keySet) { System.out.println(tempKey+"="+map.get(tempKey)); } } } ``` > 출력결과 ```java D=d A=a C=c ``` > 위 결과와 달리 "값"만 필요할 경우에는 이렇게 keySet() 메소드를 사용하여 키목록을 얻어내고, 하나 하나 받아올 필요는 없다. > 왜냐하면, values()라는 메소드가 있기 때문이다. ```java import java.util.Collection; import java.util.Set; import java.util.HashMap; public class MapSample { public static void main(String[] args) { MapSample sample=new MapSample(); sample.checkHashMap(); } public void checkHashMap(){ HashMap<String, String> map=new HashMap<String,String>(); map.put("A", "a"); map.put("C", "c"); map.put("D", "d"); Collection<String> values=map.values(); for (String tempValue : values) { System.out.println(tempValue); } } } ``` > values()라는 메소드를 사용하면 HashMap에 담겨 있는 값의 목록을 Collection 타입의 목록으로 리턴해준다. > Map에 저장되어 있는 모든 값을 출력할 때에는 values()메소드를 사용하는 것이 편하다. > 이렇게 데이터를 꺼내는 방법 외에 entrySet()메소드를 사용하는 방법도 있다. ```java public void checkHashMapEntry(){ HashMap<String,String> map=new HashMap<String,String>(); map.put("A", "a"); map.put("B", "b"); map.put("C", "c"); map.put("D", "d"); Set<Entry<String,String>> entries=map.entrySet(); for (Entry<String,String> tempEntry : entries) { System.out.println(tempEntry.getKey()+"="+tempEntry.getValue()); } } ``` > 출력결과 ```java D=d A=a B=b C=c ``` 이번에는 Map에 어떤 키나 값이 존재하는지를 확인하는 `containsKey()`와 `containsValue()`메소드에 대해 살펴보자 ```java public void checkHashMapEntry2() { HashMap<String,String> map=new HashMap<String,String>(); map.put("A", "a"); map.put("B", "b"); map.put("C", "c"); map.put("D", "d"); System.out.println(map.containsKey("A")); System.out.println(map.containsKey("Z")); System.out.println(map.containsKey("a")); System.out.println(map.containsKey("z")); } ``` > 출력결과 ```java true false true false ``` ### 정렬된 키의 목록을 원한다면 TreeMap을 사용하자 만약 HashMap 객체의 키를 정렬하려면 어떻게 해야 할까? - 가장 간단한 방법은 Arrays 라는 클래스를 사용하는 것이다. 하지만 불필요한 객체가 생긴다는 단점이 있다. 이러한 단점을 보완하는 TreeMap이라는 클래스가 있다. - `TreeMap`은 저장하면서, 키를 정렬한다. - 정렬되는 기본적인순서는 "숫자> 알파벳 대문자 > 소문자 > 한글" 순이다. - 이는 String(문자열)이 저장되는 순서를 말하며, 객체나 숫자가 저장될때는 그 순서가 달라진다. ```java public void checkTreeMap(){ TreeMap<String,String> map=new TreeMap<String,String>(); map.put("A", "a"); map.put("B", "b"); map.put("C", "c"); map.put("D", "d"); map.put("가", "e"); map.put("1", "f"); map.put("a", "g"); Set<Entry<String,String>> entries=map.entrySet(); for (Entry<String,String> tempEntry : entries) { System.out.println(tempEntry.getKey()+"="+tempEntry.getValue()); } } ``` > 출력결과 ```java 1=f A=a B=b C=c D=d a=g 가=e ``` > 이와 같이 TreeMap은 키를 정렬하여 저장함을 알 수 있다. > 따라서, 매우 많은 데이터를 TreeMap을 이용하여 보관하여 처리할 때에는 HashMap보다는 느릴 것이다. > 하지만 100건, 1,000건 정도의 데이터를 처리하고, 정렬을 해야 할 필요가 있다면 HashMap보다는 TreeMap을 사용하는 것이 더 유리하다 > 이렇게 TreeMap이 키를 정렬하는 것은 SortedMap 인터페이스를 구현했기 때문이다. ### Map을 구현한 Properties 클래스는 알아두면 편리하다. System 클래스에 대해서 살펴보면서, Properties라는 클래스가 있다고 간단하게 소개했었다. 이 클래스는 Hashtable 클래스를 확장 했다고 살펴봤었는데 따라서, Map인터페이스에 제공하는 모든 메소드를 사용할 수 있다. > 기본적으로 자바에서는 시스템의 속성을 이 클래스르 사용하여 확인할 수 있다. 그럼 시스템의 속성 값들을 확인하는 방법을 살펴보자 ```java public void checkProperties() { Properties prop = System.getProperties(); Set<Object> keySet = prop.keySet(); for (Object tempObject : keySet) { System.out.println(tempObject + "=" + prop.get(tempObject)); } } ``` > 출력결과 ```java java.runtime.name=Java(TM) SE Runtime Environment sun.boot.library.path=C:\Program Files\Java\jdk1.7.0_80\jre\bin java.vm.version=24.80-b11 java.vm.vendor=Oracle Corporation java.vendor.url=http://java.oracle.com/ // 이하생략 ``` Hashtable을 확장한 클래스이기 때문에 키와 값 형태로 데이터가 저장되어 있다. > 그런데 왜 Properties 클래스를 사용할까? 그냥 Hashtable이나 HashMap에 있는 속성을 사용하면 편할텐데... 그 이유는 Properties 클래스에서 추가로 제공하는 메소드들을 보면 알 수 있다. - load() - loadFromXML() - store() - storeToXML() 당연히 이 외에도 여러가지 메소드가 존재하지만 Properties 클래스를 이용하는 주된 이유는 여기에서 제공하는 메소드들 때문이다. ```java public void saveAndLoadProperties() { try { //String fileName = "test.properties"; String fileName="text.xml"; File propertiesFile = new File(fileName); FileOutputStream fos = new FileOutputStream(propertiesFile); Properties prop = new Properties(); prop.setProperty("Writer", "<NAME>"); prop.setProperty("WriterHome", "http://www.GodOfJava.com"); //prop.store(fos, "Basic Properties file."); prop.storeToXML(fos, "Basic XML Property file."); fos.close(); FileInputStream fis = new FileInputStream(propertiesFile); Properties propLoaded = new Properties(); //propLoaded.load(fis); propLoaded.loadFromXML(fis); fis.close(); System.out.println(propLoaded); } catch (Exception e) { e.printStackTrace(); } } ``` > 시스템 속성중 `user.dir`경로에 프로퍼티확장자를 가진 파일과 XML파일이 생성된걸 볼수 있다. > 이 절에서 살펴본 Properties 클래스를 사용하면 여러 속성을 저장하고, 읽어 들이는 작업을 보다 쉽게 할 수 있다. ### 직접해 봅시다 ```java import java.util.Hashtable; import java.util.Random; import java.util.Set; public class RandomNumberStatistics { private final int DATA_BOUNDARY = 50; Hashtable<Integer,Integer> hashtable=new Hashtable<Integer,Integer>(); public static void main(String[] args) { RandomNumberStatistics sample=new RandomNumberStatistics(); sample.getRandomNumberStatistics(); } public void getRandomNumberStatistics(){ Random random=new Random(); for (int i = 0; i < 5000; i++) { putCurrentNumber(random.nextInt(50)+1); } printStatistics(); } public void putCurrentNumber(int tempNumber){ if(hashtable.containsKey(tempNumber)){ hashtable.put(tempNumber, hashtable.get(tempNumber)+1); } else{ hashtable.put(tempNumber, 1); } } public void printStatistics(){ Set<Integer> keySet=hashtable.keySet(); for (int key : keySet) { int count = hashtable.get(key); System.out.println(key+"="+count+"\t"); if(key%10-1==0) System.out.println(); } } } ``` --- ### 정리해 봅시다 1. Map은 키(Key)와 값(Value)로 구성된다. 2. Map에서 데이터를 저장하는 메소드는 put()이다. 이 메소드의 첫 매개변수는 키이고, 두번째 매개변수는 값이다. 3. 특정 키에 할당된 값을 가져오는 메소드는 get()이다. 이 메소드의 매개변수로 찾고자 하는 키를 지정해 주면 된다. 4. 데이터를 지우는 메소드는 remove()이며, 매개변수에는 지우고자하는 키를 지정해 주면 된다. 5. keySet() 메소드를 호출하면 키의 목록을 Set 구조로 리턴한다. 6. size() 메소드는 저장되어 있는 데이터의 개수를 리턴한다. 7. Hashtable은 null을 저장할 수 없다. 8. Hashtable은 Thread에 안전하게 만들어져 있다. 9. containsKey()메소드를 사용하면 해당 키를 갖는 값이 존재하는지 확인할 수 있다. 10. TreeMap을 사용하면 키를 정렬하면서 데이터를 저장한다. 순서는 숫자, 대문자, 소문자, 한글 순이다. 11. Properties 클래스는 Hashtable을 확장한 클래스이다. 12. Properties 클래스의 store() 메소드를 사용하면 데이터를 파일로 저장한다. <file_sep>/Front-End/Webfont/fontTest.html <!DOCTYPE html> <html lang="ko"> <head> <meta http-equiv="X-UA-Compatible" content="IE=Edge"> <meta charset="UTF-8"> <link rel="stylesheet" href="font.css"> <title>문서 제목</title> <style> .font1 {float:left;width:50%; font-family:'Noto Sans'} .font2 {float:left;width:50%; font-family:'Nanum-G'} .thin {font-weight:100} .light {font-weight:300} .regular {font-weight:400} .medium {font-weight:500} .bold {font-weight:700;} </style> </head> <body> <div class="font1"> <h1>Noto Sans</h1> <h2 class=" thin">Thin </h2> <p class=" thin">국회의 정기회는 법률이 정하는 바에 의하여 매년 1회 집회되며, 국회의 임시회는 대통령 또는 국회재적의원 4분의 1 이상의 요구에 의하여 집회된다. 모든 국민은 그 보호하는 자녀에게 적어도 초등교육과 법률이 정하는 교육을 받게 할 의무를 진다.</p> <h2 class=" light">Light </h2> <p class=" light">대통령의 선거에 관한 사항은 법률로 정한다. 국회는 의원의 자격을 심사하며, 의원을 징계할 수 있다. 군사법원의 조직·권한 및 재판관의 자격은 법률로 정한다.모든 국민은 고문을 받지 아니하며, 형사상 자기에게 불리한 진술을 강요당하지 아니한다. 군인은 현역을 면한 후가 아니면 국무총리로 임명될 수 없다.</p> <h2 class=" regular">Regular </h2> <p class=" regular">군인·군무원·경찰공무원 기타 법률이 정하는 자가 전투·훈련등 직무집행과 관련하여 받은 손해에 대하여는 법률이 정하는 보상외에 국가 또는 공공단체에 공무원의 직무상 불법행위로 인한 배상은 청구할 수 없다.</p> <h2 class=" medium">Medium </h2> <p class=" medium">헌법개정안이 제2항의 찬성을 얻은 때에는 헌법개정은 확정되며, 대통령은 즉시 이를 공포하여야 한다. 국무총리 또는 행정각부의 장은 소관사무에 관하여 법률이나 대통령령의 위임 또는 직권으로 총리령 또는 부령을 발할 수 있다.</p> <h2 class=" bold">Bold </h2> <p class=" bold">국회나 그 위원회의 요구가 있을 때에는 국무총리·국무위원 또는 정부위원은 출석·답변하여야 하며, 국무총리 또는 국무위원이 출석요구를 받은 때에는 국무위원 또는 정부위원으로 하여금 출석·답변하게 할 수 있다.</p> </div> <div class="font2"> <h1>Nanum-G</h1> <h2 class=" thin">Thin </h2> <p class=" thin">국회의 정기회는 법률이 정하는 바에 의하여 매년 1회 집회되며, 국회의 임시회는 대통령 또는 국회재적의원 4분의 1 이상의 요구에 의하여 집회된다. 모든 국민은 그 보호하는 자녀에게 적어도 초등교육과 법률이 정하는 교육을 받게 할 의무를 진다.</p> <h2 class=" light">Light </h2> <p class=" light">대통령의 선거에 관한 사항은 법률로 정한다. 국회는 의원의 자격을 심사하며, 의원을 징계할 수 있다. 군사법원의 조직·권한 및 재판관의 자격은 법률로 정한다.모든 국민은 고문을 받지 아니하며, 형사상 자기에게 불리한 진술을 강요당하지 아니한다. 군인은 현역을 면한 후가 아니면 국무총리로 임명될 수 없다.</p> <h2 class=" regular">Regular </h2> <p class=" regular">군인·군무원·경찰공무원 기타 법률이 정하는 자가 전투·훈련등 직무집행과 관련하여 받은 손해에 대하여는 법률이 정하는 보상외에 국가 또는 공공단체에 공무원의 직무상 불법행위로 인한 배상은 청구할 수 없다.</p> <h2 class=" medium">Medium </h2> <p class=" medium">헌법개정안이 제2항의 찬성을 얻은 때에는 헌법개정은 확정되며, 대통령은 즉시 이를 공포하여야 한다. 국무총리 또는 행정각부의 장은 소관사무에 관하여 법률이나 대통령령의 위임 또는 직권으로 총리령 또는 부령을 발할 수 있다.</p> <h2 class=" bold">Bold </h2> <p class=" bold">국회나 그 위원회의 요구가 있을 때에는 국무총리·국무위원 또는 정부위원은 출석·답변하여야 하며, 국무총리 또는 국무위원이 출석요구를 받은 때에는 국무위원 또는 정부위원으로 하여금 출석·답변하게 할 수 있다.</p> </div> </body> </html><file_sep>/javascript/inside_javascript/chapter01/README.md ##1. 자바스크립트 기본개요 - 자바스크립트의 거의 모든 것은 객체이다 (예외도 있다) - 기본 데이터 타입인 boolean, number, string - 특별한 값인 null, undefined - 이를 제외한 나머지는 모두 객체이다. - 또한 세가지 기본 데이터 타입은 모두 객체처럼 다룰 수도 있다. - 자바스크립트에서는 함수도 객체로 취급한다. - 일반적인 객체보다 조금 더 많은 기능이 있는 객체라고 할 수 있다. - 함수가 중요한 이유는 일급객체~Firstclassobject~ 로 다뤄지기 때문이다 - 모든 객체는 숨겨진 **링크**인 **프로토타입**을 가진다. 이 링크는 해당 객체를 생성한 생성자의 프로토타입 객체를 가리킨다. - 자바스크립트는 자신만의 독특한 과정으로 실행 컨텍스트를 만들고 그 안에서 실행이 이루어진다. - 실행 컨텍스트는 자신만의 유효범위~Scope~를 갖는데, 이 과정에서 클로저를 구현할 수 있다. - 자바스크립트는 `클래스` 를 지원하지 않지만 객체지향 프로그래밍이 가능하다 - 프로토타입 체인과 클로저로 객체지향 프로그래밍에서 제시하는 상속, 캡슐화, 정보 은닉등의 개념을 소화할 수 있다 - 자바스크립트의 단점 - 유연한 언어의 특성으로 디버깅에 어려움을 유발한다 - 느슨한 타입 체크로 컴파일에서 못잡은 오류는 고스란히 런타임 오류로 발견된다. - 전역객체의 존재 - 최상위 레벨의 객체들은 모두 전역 객체 안에 위치하는데, 이는 이름 충돌의 위험성이 있다<file_sep>/php/03. 입출력 그리고 폼과 HTTP.md ## 입출력 그리고 폼과 HTTP ** << 목록 >> ** 1 . php 에플리케이션이 데이터를 입력받는 방법 2 . HTML Form 3 . GET VS POST 방식 4 . 전송된 데이터의 처리 --------------- ##### php 에플리케이션이 데이터를 입력받는 방법 프로그램은 입력값을 가질 수 있다 . 그리고 입력 값에 따라서 동작 방법이 달라지거나 입력된 값을 저장/ 삭제/ 출력 할 수 있다. ```PHP <?php echo $_GET['id']; ?> ``` 위의 코드가 들어있는 파일을 실행하여 주소창의 맨 뒤에 ?id=8805라고 입력한다. 예를 들면 다음과 같다. > ``` localhost/25.php?id=8805 ``` > 주소창에 입력을하고 나면 결과는 8805라고 나올 것이다. > $_GET['id']는 URL의 내용 중에서 '?id='뒤에 따라오는 데이터로 치환된다는 것을 추정할 수 있다. 조금 더 복잡한 아래의 코드를 보자 ```PHP <?php echo $_GET['id'].','.$_GET['password']; ?> ``` > 주소장에 id와 password의 값을 아래와 같이 입력을 해주고 나면 > ``` localhost/25.php?id=8805&password=<PASSWORD> ``` > 결과는 8805 , 1234567890 라고 나올 것이다. `?`는 25.php와 데이터를 구분해주는 구분자이다. `&`는 값과 값을 구분해주는 구분자이다. `=`은 값과 값 사이의 구분자이다. --------------- ##### HTML Form * 위의 방식으로 데이터를 직접 입력하는 것은 불편하다. 그래서 고안된 방법이 HTML폼이다. * form이란 사용자가 입력한 정보를 받아서 서버로 전송하기 위한 HTML의 태그이다. * 사용자가 입력한 정보를 받는 UI를 입력 컨트롤이라고 하는데, 위의 코드에는 id와 password를 입력 받는 입력 컨트롤이 포함되어 있다. * 입력 컨트롤에 입력된 정보는 해당 컨트롤의 속성 name의 값을 이름으로 데이터가 서버로 전송된다. * 정보 입력을 마치면 사용자가 입력한 정보를 서버로 전송할 수 있도록 해야하는데 그때 사용하는 컨트롤이 submit버튼이다. * 사용자가 submit버튼을 누르면 입력 컨트롤에 입력된 정보는 form태그의 action속성에 지정된 URL로 전송된다. 이 때 `method에 지정된 방식에 따라서 get/psot방식으로 데이터가 전송된다.` 위에서 살펴본 `URL에 데이터를 첨부해서 전송하는 방식`을 <font color='red'><b>GET방식</b></font>이라고 부르고, <font color='red'><b>POST방식</b></font>은 `HTTP메시지의 본문에 데이터를 포함해서 전송한다.` --------------- ##### Get VS Post * `get방식`으로 데이터를 전송할때 URL에 데이터를 포함시키는 것이 비해서 `POST방식`으로 데이터를 전송할 때는 전송하는 데이터를 URL에 포함시키지 않고 전송할 수 있다. * 이러한 차이로 인해서 `GET`방식은 <font color='red'>정보에 대한 링크로 많이 사용</font>되고, `POST`방식은 <font color='red'>사용자의 아이디나 비밀번호와 같은 데이터를 전송하는 방식</font>으로 주로 사용한다. <br> ** << html >> ** ```XML <html> <body> <form method="POST" action="4.php"> id: <input type="text" name="id" /> password: <input type="text" name="password" /> <input type="submit" /> </form> </body> </html> ``` <br> ** << php >> ** ```PHP <?php echo $_POST['id'].','.$_POST['password']; ?> ``` --------------- ##### 전송된 데이터의 처리 * form 태그의 action 속성의 URL이 가르키는 에플리케이션은 사용자가 전송한 데이터를 받는다. 그리고 그 정보를 간단하게는 위에서 살펴본 예제처럼 화면에 출력 할 수도 있고, 데이터베이스에 저장할 수도 있다. 이에 대한 구체적인 방법은 다음장에서 알아본다. <file_sep>/C#.NET/2. Visual Studio.md # Visual Studio --------------- ##### 비쥬얼 스튜디오 C#.NET을 개발하기위한 가장 최적화된 툴이며 비쥬얼 스튜디오 자체는 안드로이드에서 부터 웹 기타 어플리케이션까지 모두 개발 할 수 있는 도구다. [www.visualstudio.com](https://www.visualstudio.com/) --------------- ##### [다운로드](https://www.visualstudio.com/downloads/download-visual-studio-vs) 비쥬얼 스튜디오 최신버전을 다운로드 할 수 있으며 다양한 언어별 컨버전이 가능하다. --------------- <file_sep>/java/servlet_container_ebook/README.md ## 웹프로그래머를 위한 서블릿 컨테이너의 이해 (한빛미디어) ### 1. 서블릿컨테이너를 학습해야 하는 이유 ### 2. HTTP 프로토콜의 실제 ### 3. 서블릿의 이해 ### 4. HTTP 프로토콜 분석기 ### 5. 서블릿 관리자 ### 6. 병렬처리 ### 7. BIO와NIO의 비교 ### 8. 서버 프로그램으로서의 서블릿 컨테이너 ### 9. Comet - HTTP 알림 ### 10. 남은 이야기들<file_sep>/java/diskstaion_java_lec/02/VarTest.java // 패키지 설정 및 import 를 먼저 해줘야 하지만 기본과정은 주로 lang패키지를 사용하고 // lang 패키지의 경우 자동으로 생성되기때문에 생략해도 된다. /* 변수(variable, field, property, parameter) 1. 클래스 변수 : static 변수 -> 메소드 바깥에서 선언된 변수 2. 멤버변수 : instance 변수 -> 메소드 바깥에서 선언된 변수 3. 지역변수 : local 변수, automatic변수 -> 메소드 블럭 안, 또는 인스턴스 블럭안에서 선언된 변수 */ public class VarTest { int a = 10; // 멤버변수, 인트턴스 변수 -> static이 안들어간 변수 static int b = 20; // 클래스 변수, static변수 public VarTest() { int c = 30; // 지역변수, 로컬변수 System.out.println("VarTest()생성자"); System.out.println("지역변수 c: "+c); } public static void main(String[] args) { //1. 클래스변수 b의 값을 출력해보자 // 클래스명.변수 System.out.println("클래스변수 b : "+VarTest.b); //2. 멤버변수 a의 값을 출력해보자 // 먼저 객체를 생성한뒤, 객체명.변수 VarTest v = new VarTest(); System.out.println("멤버변수 a : " + v.a); //3. 지역변수 c의 값을 출력해보자 //System.out.println("지역변수 c: "+ v.c); //지역변수는 선언된 블럭 안에서만 사용 가능 // 지역변수를 사용하려면 생성자 안에서 사용해야 함 int c = 300; System.out.println("지역변수 c : "+ c); } } <file_sep>/java/god_of_java/Vol.2/04. 실수를 방지하기 위한 제네릭이라는 것도 있어요/README.md ## 4장. 실수를 방지하기 위한 제네릭이라는 것도 있어요 ### 실수를 방지할 수 있도록 도와주는 제네릭 - 이클립스를 사용하면 코딩단계에서 자잘한 오타등을 매우 쉽게 걸러낼 수 있다. - 메소드 개발과 함께 `JUnit`과 같은 테스트 코드를 작성하는 것이 좋다 > JUnit 이란? > 메소드나 클래스 같은 작은 단위를 쉽게 테스트할 수 있도록 도와주는 프레임워크다. - 그런데, 테스트를 열심히 해도 개발자가 미처 생각지 못한 부분에 대해서는 테스트 케이스를 만들지 못할 수도 있다. - 특히 자바는 여러 타입들이 존재하기 때문에, 형 변환을 하면서 예외가 발생할 수 있다. ```java import java.io.Serializable; public class CastingDTO implements Serializable{ private Object object; public void setObject(Object object){ this.object=object; } public Object getObject(){ return object; } } ``` > 이처럼 private변수, getter, setter, Serializable 구현을 해야만 제대로 된 DTO 클래스라고 할 수 있다. ```java public class GenericSample { public static void main(String[] args) { GenericSample sample = new GenericSample(); sample.checkCastingDTO(); } public void checkCastingDTO(){ CastingDTO dto1=new CastingDTO(); dto1.setObject(new String()); CastingDTO dto2=new CastingDTO(); dto2.setObject(new StringBuilder()); CastingDTO dto3=new CastingDTO(); dto3.setObject(new StringBuffer()); } } ``` > 위 코드는 문제 없이 컴파일 되지만 문제는 저장되어 있는 값을 꺼낼 때 발생한다. > 각 객체의 getObject()메소드를 호출했을 때 리턴 값으로 넘어오는 타입은 Object다. 그래서 다음과 같이 형변환을 해야한다. ```java String temp1=(String)dto1.getObject(); StringBuffer temp2=(StringBuffer)dto2.getObject(); StringBuilder temp3=(StringBuilder)dto3.getObject(); ``` > 그런데 dto2의 인스턴스 변수의 타입이 StringBuffer인지 , StringBuilder 인지 혼동될 경우는 어떻게 할까? 그럴때는 다음과 같이 instanceof라는 예약어를 사용하여 타입을 점검해야 한다. ```java Object tempObject=dto2.getObject(); if(tempObject instanceof StringBuilder){ System.out.println("StringBuilder"); } else if(tempobject instanceof StringBuffer){ System.out.println("StringBuffer"); } ``` > 그런데, 꼭 이렇게 타입을 점검해야 할까? 이러한 단점을 보완하기 위해서 JDK 5부터 새롭게 추가된 `제네릭`이라는 것이 있다. --- ### 제네릭이 뭐지? - 제네릭은 앞에서 살펴본 타입 형 변환에서 발생할 수 있는 문제점을 "사전"에 없애기 위해서 만들어졌다. - 여기서 "사전"이라고 하는 것은 실행시에 예외가 발생하는 것을 처리하는 것이 아니라, 컴파일할 때 점검할 수 있도록 한 것을 말한다. > 위에서 다뤘던 클래스를 제네릭으로 선언하면 다음과 같다. ```java package d.generic; import java.io.Serializable; public class CastingGenericDTO<T> implements Serializable { private T object; public void setObject(T obj) { this.object = obj; } public T getObject() { return object; } } ``` - 여기서 T는 아무런 이름이나 지정해도 된다. - `<>`안에 선언한 그 이름은 클래스 안에서 하나의 타입이름처럼 사용하면 된다. - 가상의 타입 이름이라고 생각하자 > 그렇다면, 이렇게 선언한 클래스를 어떻게 사용하면 될까? ```java public void checkGenericDTO() { CastingGenericDTO<String> dto1=new CastingGenericDTO<String>(); dto1.setObject(new String()); CastingGenericDTO<StringBuffer> dto2=new CastingGenericDTO<StringBuffer>(); dto2.setObject(new StringBuffer()); CastingGenericDTO<StringBuilder> dto3=new CastingGenericDTO<StringBuilder>(); dto3.setObject(new StringBuilder()); } ``` > 얼핏보면 객체 선언시 각 타입도 `<>`안에 명시해줘야 하고 귀찮아지고 번거로워진것 같지만 > 이 객체들을 `getObject()`메소드로 가져올때는 다음과 같이 간단해진다. ```java String temp1=dto1.getObject(); StringBuffer temp2=dto2.getObject(); StringBuilder temp1=dto3.getObject(); ``` > 소스를 보면 형 변환을 할 필요가 없어진 것을 알수 있다. > 왜냐하면 해당객체에 선언되어 있는 dto1~3의 제네릭 타입은 각각 String, StringBuffer, StringBuilder이기 때문에 > 만약 잘못된 타입으로 치환하면 컴파일 자체가 안된다. > 따라서, "실행시"에 다른 타입으로 잘못 형 변환하여 예외가 발생하는 일은 없다. 이와 같이 명시적으로 타입을 지정할 때 사용하는 것이 제네릭이라는 것이다. --- ### 제네릭 타입의 이름 정하기 제네릭 타입을 선언할 때 `<>`안에 어떤 단어가 들어가도 상관없지만 자바에서 정의한 기본규칙은 있다. - E : 요소(Element, 자바 컬렉션(Collection)에서 주로 사용됨) - K : 키 - N : 숫자 - T : 타입 - V : 값 - S, U, V : 두번째, 세번째, 네번째에 선언된 타입 --- ### 제네릭에 ?가 있는 것은 뭐야? > 간단한 제네릭 클래스다 ```java public class WildcardGeneric<W> { W wildcard; public void setWildcard(W wildcard) { this.wildcard=wildcard; } public W getWildcard() { return wildcard; } } ``` > 위 클래스를 사용하는 클래스다 ```java public class WildcardSample { public static void main(String[] args) { WildcardSample sample = new WildcardSample(); // sample.callWildcardMethod(); // sample.callBoundedWildcardMethod(); sample.callGenericMethod(); } public void callWildcardMethod() { // WildcardGeneric 이라는 클래스에 String을 사용하는 제네릭한 객체를 생성한다. WildcardGeneric<String> wildcard = new WildcardGeneric<String>(); wildcard.setWildcard("A"); // 생성한 객체로 wildcardMethod()를 호출할때 넘겨준다. wildcardMethod(wildcard); } public void wildcardMethod(WildcardGeneric<?> c) { Object value=c.getWildcard(); System.out.println(value); } } ``` > 이렇게 String등 대신에 `?`를 적어주면 어떤 타입이 제네릭 타입이 되더라도 상관없다. - 매소드 내부에서는 해당 타입을 정확히 모르기 때문에 앞서 사용한 것처럼 String으로 갑을 받을 수는 없고, Object로 처리해야만 한다. > 여기서 `?`로 명시한 타입을 영어로는 `wildcard` 타입이라고 부른다. - 만약 넘어오는 타입이 두 세가지로 정해져 있다면, 메소드 내에서 instanceof 예약어를 사용하여 해당 타입을 확인하면 된다. > 이렇게 사용한 `widlcard`는 메소드의 매개변수로만 사용하는 것이 좋다. --- ### 제네릭 선언에 사용하는 타입의 범위도 지정할 수 있다. - 제네릭을 사용할 때 `<>`안에는 어떤 타입이라도 상관 없다고 했지만, wildcard로 사용하는 타입을 제한할 수는 있다 - `?`대신 `? extends 타입`으로 선택하는 것이다. ```java public class Car { protected String name; public Car(String name) { this.name=name; } public String toString() { return "Car name="+name; } } ``` > Car 클래스를 상속받은 Bus 클래스를 보자 ```java public class Bus extends Car { public Bus(String name) { super(name); } public String toString() { return "Bus name="+name; } } ``` ```java public void callBoundedWildcardMethod() { WildcardGeneric<Car> wildcard=new WildcardGeneric<Car>(); wildcard.setWildcard(new Car("BMW")); wildcardMethod(wildcard); } public void boundedWildcardMethod(WildcardGeneric<? extends Car> c) { Car value=c.getWildcard(); System.out.println(value); } ``` > 앞서 사용했던 `?`라는 wildcard는 어떤 타입이 오더라도 상관이 없었다. > 하지만 `boundedWildcardMethod()`에는 `?`대신 `? extends Car`라고 적어 준것을 확인하자 > 이렇게 정의한 것은 제네릭 타입으로 Car를 상속받은 모든 클래스를 사용할 수 있다는 의미다. > 따라서, `boundedWildcardMethod()`의 매개변수에는 다른 타입을 제네릭 타입으로 선언한 객체가 넘어올 수 없다. > 즉, 컴파일시에 에러가 발생하므로 반드시 Car 클래스를 확장한 클래스가 넘어와야만 한다. --- ### 메소드를 제네릭하게 선언하기 앞에서 알아본 `wildcard`로 메소드를 선언하는 방법은 큰 단점이 있다. 이렇게 선언된 객체에 값을 추가할 수가 없다는 것이다. 그 방법을 알아보자 ```java public <T> void genericMethod(WildcardGeneric<T> c, T addValue) { c.setWildcard(addValue); T value=c.getWildcard(); System.out.println(value); } ``` 메소드 선언부를 보면 리턴타입앞에 `<>`로 제네릭타입을 선언해 놓았다. 그리고, 매개변수에는 그 제네릭 타입이 포함된 객체를 받아서 처리한 것도 알 수 잇다. 그리고 메소드 첫문장에는 `setWildcard()`메소드를 통해 값을 할당까지 했다. > 이처럼 메소드 선언시 리턴 타입 앞에 제네릭한 타입을 선언해 주고, 그 타입을 매개 변수로 사용하면 문제가 없다. > 게다가 값도 할당할 수 있다. `?`를 사용하는 `Wildcard`처럼 타입을 두리뭉실하게 하는 것보다는 명시적으로 메소드 선언시 타입을 지정해 주면 보다 더 견고한 코드를 작성할 수 있다. --- ### 정리해 봅시다 1. 제네릭은 타입 형 병환에서 발생할 수 있는 문제점을 "사전"에 없애기 위해서 만들어졌다. 2. 제네릭의 선언시 타입 이름은 예약어만 아니면 어떤 단어도 사용할 수 있다. 단, 일반적으로 대문자로 시작한다. 3. ? 를 제네릭 선언 꺽쇠 사이에 넣으면 Wildcard로 어떤 타입도 올 수 있다. 4. 특정 타입으로 제네릭을 제한하고 싶을 때에는 "? extends 타입"을 제네릭 선언 안에 넣으면 된다. 5. Wildcard 타입을 Object 타입으로만 사용해야 한다. 6. 꺽쇠 안에 원하는 제네릭 타입을 명시함으로써 제네릭한 메소드를 선언할 수 있다. <file_sep>/java/god_of_java/Vol.1/09. 패키지와 접근제어자/b/array/Array.java package b.array; public class Array { }<file_sep>/useFull site/README.MD # 참고사이트 ## 1. JAVA ### Basic Java 1. [점프 투 자바](https://wikidocs.net/281) > java의 생성자(Constructor)에 대해서 (점프투 자바) --- ### JSP 1. [JAVA와 놀자 - 개인블로그](http://sararing.tistory.com/217) > JSP 페이징 참고 --- ### MyBatis 1. [hyeonstorage - 개인블로그](http://hyeonstorage.tistory.com/112) > JDBC 연동 방법 및 사용예제 2. [과일가게 개발자 - 개인블로그](http://fruitdev.tistory.com/29) > JSP와 MyBatis3 기본환경 셋팅 3. [CUBRID](http://www.cubrid.org/manual/93/ko/sql/jsp.html) > CUBRID 소개 및 사용 방법등 메뉴얼 --- ### MVC 1. [http://netframework.tistory.com/388](http://netframework.tistory.com/388) > Mode2 방식의 Controller 인터페이스와 Spring 그리고 MVC 모델에 대해 ### Struts 1. [http://viralpatel.net/blogs/tutorial-creating-struts-application-in-eclipse/](http://viralpatel.net/blogs/tutorial-creating-struts-application-in-eclipse/) > 스트럿츠 Action 및 튜토리얼 ### SPRING 1. [http://www.wiz.center/category/software_development/SPRING](http://www.wiz.center/category/software_development/SPRING) > 스프링 동영상 강의와 샘플소스까지 제공. 또한 [유튜브 채널 - https://www.youtube.com/user/WizcenterSeoul](https://www.youtube.com/user/WizcenterSeoul)도 제공해서 모바일 기기에서도 시청가능 > 스프링 외에도 JAVA ~ HTML등 강의 제공 ### Tool & Library 1. [https://code.google.com/p/mockito/wiki/MockitoFeaturesInKorean](https://code.google.com/p/mockito/wiki/MockitoFeaturesInKorean) > Mockito 한글 번역 문서 ## 2. HTML / CSS ### HTML 1) [코드카데미 HTML/css - 한글](https://www.codecademy.com/en/tracks/korean-web) > HTMl 기초 + CSS 개요에서 포지셔닝 까지 > 더 많은 내용은 한글번역된 주소 말고 원 주소 방문 [코드카데미 - 영문](http://codecademy.com) 2) [더미 이미지 생성](http://lorempixel.com/) > 옵션값은 홈페이지 참조 > 사이즈,카테고리,흑백 등등 지원 ## 3. Javascript ### Javascript 1) [코드카데미 javascript - 한글](https://www.codecademy.com/en/tracks/javascript-ko) > 프론트 단 javasciprt 2) [코드카데미 jQuery - 한글](https://www.codecademy.com/en/tracks/jQuery-ko) > web jQuery 개요 ~ 이펙트 3) [jQery touch.js](https://code.google.com/p/jquery-ui-for-ipad-and-iphone/) > jQeury UI 사용시에 dragable 등 이벤트가 모바일에서는 작동 안한다 이럴때 jQuery.us.js 밑에 위 터치 js 삽입시 해결 <file_sep>/python/algorithm/sum_n2.py def sum_n(n): return n*(n+1)//2 print(sum_n(10)) print(sum_n(100)) <file_sep>/javascript/front_end_javascript/3장 언어의 기초/README.md ## 3장 언어의 기초 - 문법 훑어보기 - 데이터 타입 - 제어문 - 함수 이해 #### 3.1.4 스트릭트 모드 ECMAScript 5에서는 '스트릭트 모드'라는 개념을 도입했다. 스트릭트 모드는 기존과는 다른 방식으로 자바스크립트를 파싱하고 실행하라고 지시하는 것인데 ECMAScript 3판의 문제를 해결했으며 안전하지 않은 동작에는 에러를 반환하도록 합니다. 전체 스크립트에 스트릭트 모드를 적용하려면 다음 문장을 스크립트 맨 위에 추가하면 된다. ```javascript "use strict"; ``` > 이 선언은 스트릭트 모드를 지원하는 자바스크립트 엔진은 이를 인식하고 스트릭트 모드로 전환하라는 뜻으로, > 이 문법은 ECMAScript 3 문법과 호환되도록 만든 것이다. #### 3.1.5 문장 ECMAScript에서 각 문장은 세미콜론으로 종료한다. 이때 세미콜론을 생략 할 수 있지만, 에러를 파악하거나 여분의 공백해서 migration 시킬때 오류등, 여러가지 문제들이 생길 여지가 있으므로 가급적 사용하자 ### 3.4 데이터 타입 ECMAScript에는 다섯 가지 기본적인 데이터 타입이 있다. 이를 `원시 데이터 타입`이라고 부르는데 이 다섯가지는 다음과 같다. - Undefined - Null - boolean - 숫자 - 문자열 또한 원시 데이터 타입 외에 `객체`라는 데이터 타입도 존재한다. ECMAScript의 데이터 타입은 동적이므로 한 가지 데이터 타입이 여러 특성을 가질 수 있다. #### 3.4.1 typeof 연산자 ECMAScript는 느슨한 타입을 채택했으므로 변수의 데이터 타입을 알아내야 할 때가 있는데 이때 typeof 연산자를 통해 데이터 타입을 알 수 있다. 그 예는 다음과 같다 - 정의되지 않은 변수 : `undefined` - 불리언 : `boolean` - 문자열 : `string` - 숫자 : `number` - 함수를 제외한 객체 또는 null : `object` - 함수 : `function` #### 3.4.2 undefined 타입 `undefined`라는 값은 특별한 값이다 var를 써서 변수를 정의했지만 초기화 하지 않았다면 해당 변수에는 다음과 같이 `undefined`가 할당된다. ```javascript var message; alert(message == undefined); //true ``` > 참고로 리터럴값 `undefined`는 빈 객체를 가리키는 포인터인 null과 초기화되지 않은 변수를 비교할 목적으로 ECMA-263 3판에 추가되었다. #### 3.4.3 Null 타입 Null 타입 역시 값 하나만을 갖는다. Null타입의 값은 특별한 값인 null로, 빈 객체를 가리키는 포인터이므로 null에 typeof를 호출하면 다음 예제처럼 `object`를 반환한다. ```javascript var car = null; alert(typeof car); //object ``` > 변수를 정의할 때 해당 변수가 객체를 가리키게 할 생각이라면 해당 변수에는 다른 값을 쓰지말고 null로 초기화하길 권한다. > 그렇게 하면 해당변수가 객체를 가리키는지 명시적으로 확인할 수 있기 때문이다. ```javascript if(car != null){ //car를 사용하는 코드 } ``` `undefined`는 `null`에서 파생했으므로 ECMA-262에서는 두 값이 다음과 같이 표면적으로는 동일한 것으로 정의한다. ```javascript alert(null == undefined); //true ``` 위와 같이 두값이 같다고 나오는 이유는 `==` 연산자가 피연산자를 비교할 때 암시적으로 타입 변환을 하기 때문인데, 이에 대한 내용은 뒤에서 자세히 알아보자 두 값은 서로 관련되어 있긴 하지만 아주 다르게 쓰인다. 일례로 **변수의 값에 명시적으로 undefined를 할당해서는 안되지만 null은 좀 다르다** **==객체를 사용해야 하지만 해당 객체를 이용할 수 없을 때에는 항상 그 자리에 null이 와야 한다.==** 이렇게 하면 null이 빈 객체를 가리키는 포인터라는 점을 늘 숙지할 수 있고 undefined와 구별할 수 있게 된다. #### 3.4.4 불리언 타입 불리언 타입은 ECMAScript에서 가장 많이 쓰이는 데이터 타입 중 하나이며, 단 두 가지 리터럴 값만 있지만 ECMAScript에서는 모든 타입을 불리언 값으로 표현할 수 있다. 각 데이터 타입별로 어떻게 형변환이 이루어지는지는 다음 표를 참고하자 | 데이터 타입 | true로 변환되는 값 | false로 변환되는 값 |--------|--------| | 불리언 | true | false | 문자열 | 비어 있지 않은 문자열 모두 | `""`(빈 문자열) | 숫자 | 0이 아닌 모든 숫자, 무한대 포함 | 0, NaN | 객체 | 모든 객체 | null | Undefined | 해당없음 | undefined #### 3.4.6 문자열 타입 문자열 데이터 타입은 16비트 유니코드 문자의 연속으로 큰따옴표(`""`) 나 작은따옴표(`''`)로 감싸서 표현한다. PHP와 달리 ECMAScript에서는 둘을 구분하지 않는다. **문자열의 성질** ECMAScript에서 문자열은 `불변`이다. 즉 문자열이 일단 만들어지면 그 값을 바꿀 수 없다는 말이다. 변수에 저장한 문자열을 바꾸려면 기존의 문자열을 파괴하고 다음과 같이 해당 변수에 새 문자열을 채워야 한다 ```javascript var lang = "Java" lang = lang + "Script"; ``` **문자열로 변환** 값을 문자열로 바꾸는 방법은 두 가지로 - `toString()`메소드를 사용하는 방법 그중 첫번째 방법은 ==거의 모든 값에 존재하는== `toString()` 메소드를 사용하는 방법이다. `toString()`메소드가 하는 일은 값에 해당하는 문자열을 반환하는것 뿐이다 다음 에제를 보자 ```javascript var age = 11; var ageAsString = age.toString(); //the string "11" var found = true; var foundAsString = found.toString(); //the string "true" ``` > toString()메소드는 숫자와 불리언, 객체, 문자열 값에 존재한다.(문자열에도 toString()메소드가 있는데 이를 호출하면 단순히 자신을 복사해 반환한다.) > 단 `null`과 `undefined`에는 이 메소드가 존재하지 않는다. 또한 숫자를 호출할때 매개변수를 하나 줄수 있는데 이는 진법을 나타낸다(8진수, 16진수등...) #### 3.4.7 객체 타입 ECMAScript에서 객체는 데이터와 기능의 집합이다. 객체는 `new` 연산자 다음에 새로 만들 객체 타입의 이름을 써서 만든다. 다음과 같이 `Object`타입의 `인스턴스`를 만들고 프로퍼티나 메소드를 추가하여 객체를 만들 수 있다 ```javascript var o = new Object(); ``` 이 문법은 자바와 비슷하긴 하지만 ECMAScript에서는 생성자에 매개변수를 넘기지 않는다면 괄호를 생략해도 된다. 매개변수가 없다면 다음 예제 처럼 괄호를 생략해도 안전하긴 하지만 권장하지는 않는다. ```javascript var o = new Object; //유효하지만 권장하지 않음 ``` > ECMAScript의 `Object` 타입은 자바의 `java.lang.Object`처럼 이 타입에서 파생하는 모든 객체의 원형이다. > Object 타입의 인스턴스는 Object 타입의 프로퍼티와 메소드를 전부 상속한다. Obejct 의 인스턴스는 다음 프로퍼티와 메소드를 가진다. - constructor : 해당 객체를 만드는 데 쓰인함수. 위 예제로 치면 `Object()`함수가 생성자다 - hasOwnProperty(propertyName) : 해당 프로퍼티가 객체 인스턴스에 고유하며 프로토타입에서 상속하지 않았음을 확인하며, 프로퍼티 이름은 반드시 문자열이어야 한다. 예를 들어 o.hasOwnProperty("name")같은 형식으로 호출한다. - isPrototypeOf(object) : 해당 객체가 다른 객체의 프로토타입인지 확인한다. - propertyIsEnumerable(propertyName) : 해당 프로퍼티를 `for-in` 문에서 나열할 수 있는지 확인한다. 위 메소드와 마찬가지로 프로퍼티 이름에는 반드시 문자열을 써야 한다. - toLocaleString() : 객체를 지역에 맞게 표현한 문자열을 반환한다. - toString() : 객체를 문자열로 변환해 반환한다. - valueOf() : 객체를 나타내는 문자열이나 숫자, 불리언을 반환한다 > ECMAScript에서는 모든 객체가 `Object`에 기반해 만들어지므로 이들 프로퍼티와 메소드는 모든 객체에 존재한다. ### 3.7 함수 함수는 문장을 캡슐화하여 어디서든, 언제든 실행할 수 있게 하므로 모든 언어의 핵심이다. ECMAScript 의 함수는 꼭 값을 반환하지 않아도 된다. 스트릭트 모드에서는 함수에 다음과 같은 제한이 있다. - 함수 이름에 `eval`이나 `arguments`는 사용할 수 없다. - 매개변수 이름에도 `eval`이나 `arguments`를 쓸 수 없다. - 서로 다른 매개벼니수에 결고 같은 이름을 쓸 수 없다. #### 3.7.1 매개변수의 이해 ECMAScript의 함수의 매개변수는 다른 언어와 다르게 동작한다. - 매개변수 숫자를 따지지 않는다. - 데이터 타입도 체크하지 않는다. 가령 함수에서 매개변수를 두 개 받도록 만들었더라도, 매개변수를 한개, 세개, 또는 아예 넘기지 않더라도 인터프리터는 이를 에러로 간주 하지 않는데, > 이는 ECMAScript의 매개변수가 내부적으로는 배열로 표현되기 때문이다. > 이 배열은 항상 함수에 전달되지만 함수는 배열에 어떤 값이 들어 있는지 체크하지 않습니다. 빈 배열이 들어와도 상관없고, 필요한 매개변수보다 많이 들어와도 괜찮다. > 함수는 `arguments`라는 객체를 하나 갖는데, 이 객체를 통해 매개변수의 값에 접근할 수 있다. `arguments` 객체는 각 매개변수를 대괄호 표기법, 즉 첫번째 매개변수는 arguments[0]와 같은 형태로 접근하며, 매개변수를 `length` 프로퍼티를 통해 알 수 있다는 면에서 배열처럼 동작하기는 하지만 `Array`의 인스턴스는 아니다. 가령 아래와 같이 함수에 명시적으로 매개변수를 표현하지 않고도 사용가능하다. 매개변수로 넘김 값을 사용가능하다. ```javascript function sayHi(){ alert("Hello" + arguments[0]); } ``` > 위 예제는 ECMAScript 함수의 중요한 특징을 묘사하는데 > 이름 붙은 매개변수는 편리하긴 하지만 반드시 필요한건 아니고, 다른언어와 달리 매개변수에 이름을 붙인다 해서 함수 시그니처를 만들고 나중에 검사하지 않는다. > 다시 말해 이름 붙은 매개변수의 유효성 검사를 하지 않는다는 뜻이다. `arguments` 객체의 `length`프로퍼티를 통해 함수에 매개변수가 몇 개 전될되었는지 알 수 잇다. 다음 예제를 통해 살펴보자 ```javascript function howManyArgs(){ alert(arguments.length); } howManyArgs("string", 45); //2 howManyArgs(); //0 howManyArgs(12); //1 ``` 이런 방법을 통해 함수가 받는 매개변수 숫자에 제한을 두지 않고 넘겨받은 매개변수 개수에 맞게 반응할 수 있다. ```javascript function doAdd(){ if(arguments.length == 1){ alert(arguments[0] + 10); } else if(arguments.length == 2){ alert(arguments[0] + arguments[1]); } } doAdd(10); //20 doAdd(30,20); //50 ``` 위 예제와 같은 방식은 오버로딩만큼 좋지는 않지만 ECMAScript의 제한을 경감하기에 충분하다. **매개변수에서 또 다른 중요한 점은 다음과 같이 `arguments`객체를 이름 붙은 매개변수와 함께 쓸 수 있다는 것이다.** ```javascript function doAdd(num1, num2){ if(arguments.length == 1){ alert(num1 + 10); } else if(arguments.length == 2){ alert(arguments[0] + num2); } } ``` `arguments` 객체에서 한 가지 더 재미있는 점은 이 객체의 프로퍼티 값을 이에 대응하는 이름 붙은 매개변수에서 자동으로 반영한다는 점이다. 예를 들면 다음과 같다. ```javascript function doAdd(num1, num2){ arguments[1] = 10; alert(arguments[0] + num2); } ``` 위의 함수는 항상 두번째 매개변수의 값을 10으로 바꾼다. 즉 `arguments[1]`의 값을 바꾸면 num2도 바뀌며 결국 둘 모두 10이 된다. > 여기서 이 둘이 같은 메모리 공간을 쓰는 건 아니다. 둘은 각각 다른 메모리 공간을 사용하지만 값은 반영된다. > 그런데 이는 동기화가 아니라 단방향 반영이다. > 즉 이름 붙은 매개변수의 값을 바꾸더라도 arguments의 해당 프로퍼티는 바뀌지 **않는다** 또 하나 기억해야 할 것은 매개변수를 하나만 넘기면 arguments[1]의 값을 바꾸더라도 이름붙은 매개변수에는 아무 영향도 없다는 것이다. 이렇게 되는 이유는 arguments 객체의 length 프로퍼티가 함수 정의에서 정의한 매개변수 숫자를 따르지 않고 함수를 호출할 때 넘긴 이름 붙은 매개변수 목록을 따르기 때문이다. 함수를 정의할 때 함께 정의한 매개변수를 넘기지 않으면 해당 매개변수에는 자동으로 `undefined`가 할당된다. 이는 변수를 정의하기만 하고 초기화하지는 않은 것과 비슷하다. > 스트릭트 모드는 arguments 객체의 동작방식을 여러가지로 바꿨다. 먼저 바로 이전 예제에서 보인 할당 방식은 동작하지 않는다. 즉 arguments[1]의 값을 10으로 바꾸더라도 num2는 계속 undefined 상태로 남는다. #### 3.7.2 오버로딩 없음 ECMAScript 함수에는 다른 언어에서 사용하는 오버로딩이 없다. 예를 들어 자바에서는 함수 이름ㅁ이 같더라도 시그니처(매개변수의 타입과 개수)만 다르면 서로 다르게 동작하도록 정의할 수 있다. 이미 언급했듯 ECMAScript 함수에는 시그니처가 없는데 매개변수는 그저 배열일 뿐이며 그 값에 제한이 없기 때문이다. <file_sep>/java/diskstaion_java_lec/04 OOP/Inheritance.java public class Inheritance { public static void main(String[] args) { /* 아래 소스는 부모클래스의 getInfo()메소드에 power가 없기때문에 이름과 키만 찍어주고 power는 안찍어준다 */ Superman s1 = new Superman(); s1.name="슈퍼맨1"; s1.height=190; s1.power=2000; String info = s1.getInfo(); System.out.println(info); String info2 = s1.getInfo("----슈퍼맨 정보-----"); System.out.println(info2); System.out.println("================="); Human h1 = new Human(); h1.name="사람1"; h1.height=188; String str2 = h1.getInfo(); System.out.println(str2); System.out.println("================="); Aquaman a1 = new Aquaman(); a1.name="아쿠아맨1"; a1.height=190; a1.speed=1200; String infoa = a1.getInfo(); System.out.println(infoa); a1.getInfo("-----아쿠아맨 정보-----",50); System.out.println("================="); } } // 부모 클래스 - Super Class class Human { String name; int height; public String getInfo() { String str="이름: "+name+"\n키: "+height; return str; } } class Superman extends Human { int power; // 메소드 Overriding(재정의) 부모 // 1. 부모의 것과 동일한 메소드명 // 2. 매개변수도 동일하게 // 3. 반환타입도 동일하게 // 4. 접근지정자는 부모의 것과 동일하거나 더 넓은 범위의 지정자를 사용 // 5. Exception의 경우 부모 클래스의 메소드와 동일하거나 // 더 구체적인 Exception을 발생시켜야한다. //오버라이딩 public String getInfo() { //String str="이름: "+name+"\n키: "+height+"\n힘: "+power; String str = super.getInfo()+"\n파워: "+power; return str; } //오버로딩 public String getInfo(String title) { String str = title+"\n"+this.getInfo(); return str; } } class Aquaman extends Human { int speed; public String getInfo() { //String str="이름: "+name+"\n키: "+height+"\n속도: "+speed; String str=super.getInfo()+"\n속도: "+speed; return str; } //오버로딩 public void getInfo(String title, int speed) { System.out.println(title); System.out.println(this.getInfo()); System.out.println("--- 스피드 ---"); this.speed += speed; System.out.println("속도: "+this.speed); } }<file_sep>/java/god_of_java/Vol.2/02. String/StringSample.java public class StringSample { public static void main(String[] args) { StringSample sample=new StringSample(); sample.constructors(); } public void constructors(){ try{ //"한글"이라는 값을 갖는 String객체 str생성 String str="한글"; // str을 byte배열로 만듬 byte[] array1=str.getBytes(); for(byte data:array1){ System.out.print(data + " "); } System.out.println(); // byte배열(array1)을 매개변수로 갖는 String객체 생성후 출력 String str1=new String(array1); System.out.println(str1); } catch(Exception e){ e.printStackTrace(); } } }<file_sep>/java/java_web_develop_workBook/2장. 웹 프로그래밍의 기초 다지기/README.md ## 2. 웹 프로그래밍의 기초다지기 #### 1) HTTP 프로토콜이란? - `HTTP`프로토콜은 웹 브라우저와 웹 서버 사이의 데이터 통신 규칙이다. - 우리가 링크를 클릭하면 웹브라우저는 `HTTP`요청 형식에 따라 웹 서버에 데이터를 보낸다. - 이때 보내는 데이터는 `HTTP`응답 형식에 맞추어 보내면 된다. > `HTTP 프로토콜`은 단순이 `HTML`페이지나 이미지 파일을 전송하는 차원을 넘어서, > 원격 컴퓨터에 로딩되어 있는 함수나 객체의 메서드를 호출할 때도 사용된다. > 특히 웹 어플리케이션을 개발하다 보면 `SOAP(Simple Object Access Protocol)` 나 `RESTful(REpresentational State Transfer)`이라는 용어를 만나게 되는데 이것은 클라이언트와 서버 사이에 서비스를 요청하고 응답을 하는 방식을 말한다. > 이 두가지 모두 `HTTP프로토콜`을 응용하거나 확장한 기술이다. > 특히 아마존의 클라우드나 KT의 클라우드는 자신들의 서비스와 연동할 도구로 `RESTful` 방식의 API를 제공하고 있다. > `HTTP` 프로토콜 응용 기술 몇가지를 더 소개하자면 > `WebDAV(World Wide Distributed Authoring and Versioning)`를 들 수 있다. > 이는 웹상에서 여러사람이 문서나 파일을 더 쉽게 편집하고 다룰 수 있게 협업을 도와주는 기술이다. > `WebDAV`를 응용한 `CalDAV`기술도 있다 이것은 캘린더 데이터를 보다 쉽게 편집하고 공유할 수 있도록 `WebDAV`를 확장한 기술이다. --- #### 2) HTTP 모니터링 웹 브라우저와 웹 서버 사이에 주고받는 데이터를 들여다보려면 HTTP 프록시 프로그램이 필요하다. > fiddler를 사용하자 웹 브라우저가 웹 서버에게 요청을 하면 HTTP프록시가 그 요청을 대신 받아서 서버에 전달한다. 서버에서 응답이 오면 HTTP프록시가 그 응답을 대신 받아서 웹 브라우저에게 전달한다. 이렇게 웹 브라우저와 웹 서버의 중간에서 요청이나 응답 내용을 중계해 주기 때문에 둘사이에서 주고받는 내용이 무엇인지 엿볼 수 있다. > [프록시 서버란? (검색바로가기)](https://www.google.co.kr/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=%ED%94%84%EB%A1%9D%EC%8B%9C%EC%84%9C%EB%B2%84) fidller를 이용해 `daum.net` 요청데이터를 살펴보자 ``` GET / HTTP/1.1 Host: www.daum.net Connection: keep-alive Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36 Accept-Encoding: gzip, deflate, sdch Accept-Language: ko-KR,ko;q=0.8,en-US;q=0.6,en;q=0.4 ``` 요청라인(Request-Line) 요청메시지의 첫 라인은 메서드와 요청하는 자원, 프로토콜 버전으로 구성된다. > 메서드에는 GET,POST, HEAD, PUT, DELETE, TRACE, CONNECT, OPTIONS 등이 있으며 > 요청URI는 요청하는 자원의 식별자이다. > 즉 HTML이나 이미지, 동영상, 어플리케이션 등이 있는 가상의 경로라고 생각하면 된다. > 웹 서버는 이 식별자를 이용하여 해당 자원을 찾습니다. > `HTTP`버전은 요청 정보가 어떤 버전에 맞추어 작성했는지 웹 서버에게 알려주기 위함이다. 요청헤더 HTTP 요청 내용중에 2~7번 라인은 서버가 요청을 처리할 때 참고하라고 클라이언트에서 웹서버에게 알려주는 정보다. 이정보를 `헤더` 라고 말한다. > 헤더에는 세가지 종류가 있는데 요청이나 응답 모두에 적용할 수 있는 `일반헤더(General-header)`와 요청 또는 응답 둘 중 하나에만 적용할 수 있는 `요청 헤더 또는 응답헤더(Request-header/Response-header)`, 보내거나 받는 본문 데이터를 설명하는 `엔티티헤더(Entity-header)`가 있다. 요청 헤더 중에서 `User-Agent`는 클라이언트의 정보를 서버에게 알려주는 헤더로, 웹 서버는 이 헤더를 분석하여 요청자의 Os와 브라우저를 구분한다. PHP의 Referer 함수나 서버변수에 저장되는 정보와 무슨 관계인지 알아보기! --- #### 3)HTTP 클라이언트 만들기 클라이언트와 서버가 주고받는 데이터 형식만 안다면 누구나 클라이언트나 서버를 개발할 수 있다. ```java package client; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.Socket; public class SimpleHttpClient { public static void main(String[] args) throws Exception { // 1. 소켓 및 입출력 스트림 준비 Socket socket=new Socket("www.daum.net",80); BufferedReader in=new BufferedReader( new InputStreamReader(socket.getInputStream())); PrintStream out=new PrintStream(socket.getOutputStream()); // 2. 요청라인 출력 out.println("GET / HTTP/1.1"); // 3. 헤더정보 출력 out.println("Host: www.daum.net"); out.println("User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0)" + " AppleWebKit/537.36 (KHTML, like Gecko)" + " Chrome/30.0.1599.101 Safari/537.36"); // 4. 공백라인 출력 out.println(); // 5. 응답 내용 출력 String line=null; while((line = in.readLine()) != null){ System.out.println(line); } in.close(); out.close(); socket.close(); } } ``` > 위 코드`(SimpleHttpClient 클래스)`를 살펴보자 1. 접속할 웹서버는 '다음' 사이트. 웹 서버의 기본 포트번호는 80이기 때문에 접속할 서버의 포트번호를 80으로 지정한 후, 소켓으로 입/출력을 하기 위한 객체를 준비한다. 2. 먼저 서버에게 수행할 작업을 알려주는 요청라인을 보낸다. 요청형식은 GET, 원하는 자원은 웹 서버 루트 폴더에 있는 기본문서(/), 사용할 프로토콜은 HTTP, 버전은 1.1 이다 3. 웹서버에 부가 정보를 보낸다. 접속하려는 웹 서버의 주소는 `www.daum.net` 요청자의 정보는 크롬브라우저라고 설정한다. '다음' 웹 서버는 Host, User-Agent 이렇게 두 가지 헤더만 보내도 정상적으로 응답해준다. 4. 요청의 끝을 표시하기 위해 공백라인을 보낸다. 5. 서버로부터 받은 데이터를 라인 단위로 읽어서 출력한다. > 널리 알려진 프로토콜 몇 가지를 간단히 살펴보자 1) FTP (File Transfer Protocol) - 클라이언트와 서버 간에 파일을 주고받기 위해 만든 통신 규약 2) Telnet 프로토콜 - 인터넷이나 LAN 상에서 문자 기반으로 원격의 컴퓨터를 제어하기 위해 만든 통신 규약이다. - 요즘은 보안 때문에 SSH 프로토콜 기반 원격 접속 프로그램을 주로 사용한다. 3) XMPP (Extensible Messaging and Presence Protocol) - 인스턴스 메시지 및 사용자의 접속 상태 정보를 교환할 목적으로 만든 통신 규약이며 Google Talk가 이 프로토콜을 기반으로 통신합니다. 4) SMTP (Simple Mail Transfer Protocol) - 인터넷 상에서 메일을 보내기 위한 통신 규약 - POP3(Post Office Protocol version 3)는 이메일을 가져오는 데 사용하는 통신규약이며 POP3는 이메일으르 가져온 후 서버의 메일을 삭제한다. 5) IMAP(Internet Message Access Protocol) - POP3와 달리 이메일을 가져온 뒤에 서버의 메일을 지우지 않으며 요즘처럼 여러 대의 장비에서 이메일을 조회하는 경우에 적합하다. 단, POP3에 비해 통신 트래픽이 높은 것이 단점이다. 6) LDAP(Lightweight Directory Access Protocol) - 디렉터리 서비스에 등록된 자원들을 찾는 통신 규약 7) IRC(Internet Relay Chat) - 실시간 채팅을 위해 만든 통신 규약 --- #### 4) GET 요청 > GET 요청의 특징 - URL 에 데이터를 포함 -> 데이터 조회에 적합 - 바이너리 및 대용량 데이터 전송불가 - 요청라인과 헤드 필드의 최대크기 - HTTP 사양에는 제한사항 없음 - 대용량 URL로 인한 문제 발생 -> 웹 서버에 따라 최대 크기 제한 - Microsoft IIS 6.0_: 16KB - Apache 웹서버 : 8KB > GET 요청의 문제점과 개선방안 - 보안에 좋지않다. - 바이너리 데이터를 전송할 수 없다. HTTP 사양에서는 요청라인이나 헤더 필드의 최대 크기를 제한하지 않는다. 그러나 대부분의 웹 서버는 대용량 URL을 사용할 때 발생할 수 있는 보안 문제 때문에 요청라인이나 헤더필드의 최대 크기를 제한하고 있다. 가령 IIS는 버전4.0은 2MB였고, 5.0에서는 128KB로 줄였고, 6.0부터는 16KB로 제한하고 있다. 아파치 웹서버는 8KB --- #### 5) POST 요청 > POST 요청의 특징 - URL에 데이터가 포함되지 않음 -> 외부 노출방지 - 메시지 본문에 데이터 포함 -> 실행 결과 공유 불가 - 바이너리 및 대용량 데이터 전송가능 > POST 요청의 단점 - 요청결과를 공유할 수 없다. - > POST 요청의 문제점과 개선방안 - GET 메서드와 마찬가지로 데이터를 전달할 때 "이름=값&이름=값" 형태를 사용한다. - 문자데이터를 보낼 때는 문제 없지만, 이미지나 동영상과 같은 바이너리 데이터를 보낼 때는 문제가 발생할 수 있다. - 바이너리 데이터 안에 `=`이나 `&`의 문자코드를 포함할 수 있기 때문이다. - 이런 문제를 해결하기 위해 바이너리 데이터를 보낼 때는 아주 특별한 형식으로 작성하여 보내야하며, 서버에서도 이 형식에 맞추어 데이터를 분리한다. <file_sep>/java/toby_spring/Vol.2/1장/README_2.md ## 1장 IoC 컨테이너와 DI ##### 2) 어노테이션 : @Autowired/@Inject 어노테이션을 이용한 의존관계 설정 방법의 두 번째는 @Autowired와 @Inject를 이용하는 것이다. 이 두 가지 어노테이션은 기본적으로 타입에 의한 자동와이어링 방식으로 동작한다. 그 의미나 사용법은 거의 동일하다. @Autowired는 스프링 2.5부터 적용된 스프링 전용 어노테이션이고, @Inject는 JavaEE 6의 표준 스펙인 `JSR-330(줄려서 DIJ라고 부른다)`에 정의되어 있"는 것으로, 스프링 외에도 JavaEE 6의 스펙을 따르는 여타 프레임워크에서도 동일한 의미로 사용되는 DI를 위한 어노테이션이다. > 즉 스프링으로 개발한 POJO를 앞으로 다른 환경에서도 사용할 가능성이 있다면 @Inject와 DIJ에서 정의한 어노테이션을 사용하는게 좋다. @Autowired는 XML의 타입에 의한 자동와이어링 방식을 생성자, 필드, 수정자 메소드, 일반 메소드의 네 가지로 확장한 것이다. **1) 수정자 메소드와 필드** 필드와 수정자 메소드는 @Resource와 사용 방법이 비슷하다. @Autowired 어노테이션이 부여된 필드나 수정자를 만들어주면 스프링이 자동으로 DI 해주도록 만드는 것이다. @Resource와 다른점은 이름 대신 필드나 프로퍼티 타입을 이용해 후보 빈을 찾는다는 것이다. 이 점에서는 XML의 타입 자동와이어링과 비슷하다 다음 소스를 보면 필드의 타입의 Printer이므로 현재 등록된 빈에서 Printer타입에 대입가능한 빈을 찾는다. 대입 가능한 빈 후보가 하나 발견되면, printer 필드에 자동으로 DI될 것이다. ```java public class Hello{ @Autowired private Printer printer; } ``` 또한 수정자 메소드에 도 적용할 수 잇다. ```java public class Hello{ private Printer printer; @Autowired public void setPrinter(Printer printer){ this.printer=printer; } } ``` **2) 생성자** @Autowired는 @Resource와 다르게 생성자에도 부여할 수 있다. 이때는 생성자의 모든 파라미터에 타입에 의한 자동와이어링이 적용된다. 가력 두개의 프로퍼티를 갖고 있는 메소드가 있다고 가정했을때, 이를 수정자를 이용해 DI하려면 두개 의 수정자 메소드가 필요하고 어노테이션 설정을 사용하면 @Autowired도 두 개가 필요할테지만 생성자를 이용한다면 하나의 @Autowired로 가능하다 ```java public class BasSqlService implements SqlService{ protected SqlReader sqlReader; protected SqlRegistry sqlRegistry; @Autowired public BaSqlService(SqlReader sqlReader, SqlRegistry sqlRegistry){ this.sqlReader = sqlReader; this.sqlRegistry = sqlRegistry; } } ``` @Autowired는 단 하나의 생성자에만 사용할 수 있다는 제한이 있다. 여러 개의 생성자에 @Autowired가 붙으면 어느 생성자를 이용해서 DI 해야 할 지 스프링이 알 수 없기 때문이다. **3) 일반 메소드** @Autowired는 수정자, 생성자 외의 일반 메소드에도 적용할 수 있다. XML을 이용한 의존관계 설정에서는 가능하지 않은 어노테이션 방식의 고유한 기능이다 생성자 주입과 수정자 주입은 각기 장 단점이 있는데 바로 그래서 등장한 DI 방법이다. 파라미터를 가진 메소드를 만들고 @Autowired를 붙여주면 각 파라미터의 타입을 기준으로 자동와이어링을해서 DI 해줄 수 있다. 생성자 주입과 달리 일반 메소드는 오브젝트 생성 후에 차례로 호출이 가능하므로 여러 개를 만들어도 된다. 한 번에 여러개의 오브젝트를 DI 할수 잇음믐로 코드도 상대적으로 깔끔해진다. 수정자 메소드 주입과 생성자 주입의 장점을 모두 갖춘 방식이다. ++단 이렇게 만들어진 클래스는 XML을 통해서는 의존관계를 설정할 방법이 없다는 점에 주의해야 한다.++ **4)@Qualifier** Qualifier 는 타입 외의 정보를 추가해서 자동와이어링을 세밀하게 제어할 수 있는 보조적인 방법이다. 타입에 의한 자동와이어링은 안전하고 편리하지만 타입만으로 원하는 빈을 지정하기 어려운 경우가 종종 발생한다. 만약 DataSource 타입의 빈이 하나 이상 등록됐다고 생각해보자. ```xml <bean id="oracleDataSource" class="...XxxDataSouce">...</bean> <bean id="mysqlDataSource" class="...YyyDataSouce">...</bean> ``` 각기 다른 DB를 사용하지만 모두 Datasource라는 같은 타입의 빈을 사용하고 있다. 여기서는 `@Resource("oracleDatasource")` 같은 형식으로 사용하는데는 문제가 없다 하지만 @Autowired 를 사용해서 타입에 의한 자동와이어링을 시도하면 에러가 발생한다. > 그렇다면 이럴때는 어떻게 해야 할까? 바로 이럴때 `@Qualifier`을 이용해서 빈 선정을 도와주는 부가정보를 이용하는 게 좋다. 먼저 자바 소스에 아래와같이 한정자~qualifier~ 값을 설정해주고 ~ ```java @Autowired @Qualifier("mainDB") DataSource dataSource; ``` XML의 빈태그에 위에서 등록한 한정자 정보를 등록해주면 된다. ```xml <bean id="oracleDataSource" class="...XxxDataSource" > <qualifier value="mainDB" /> </bean> ``` ##### 3) @Autowired 와 getBean(), 스프링 테스트 <file_sep>/javascript/front_end_javascript/4장 변수와 스코프, 메모리/README.md ## 4장 변수와 스코프, 메모리 - 변수의 원시 값과 참조 값 - 실행 컨텍스트의 이해 - 가비지 컬렉션의 이해 ### 4.1 원시 값과 참조 값 ECMAScript의 변수는 원시 값과 차조 값 두 가지 타입의 데이터를 저장할 수 있다. `원시 값`은 단순한 데이터이며 `참조 값`은 여러 값으로 구성되는 객체를 가리킨다. 참조 값은 메모리에 저장된 객체를 의미하며, 여타 언어와는 달리 자바스크립트는 메모리 위치에 직접 접근하는 것을 허용하지 않으므로 객체의 메모리 공간을 직접 조작하는 일은 불가능하다. 객체를 조작할 때는 사실 객체 자체가 아니라 해당 객체에 대한 `참조`를 조작하는 것이다. > 이런 이유로 객체를 가리키는 값은 `참조로 접근한다`고 한다. ++참고로 다른 언어들은 대두수 문자열을 객체로 표현됨므로 참조타입으로 간주한다. (자바스크립트는 문자열은 원시타입으로 간주)++ #### 4.1.1 동적 프로퍼티 참조 값을 다룰 때는 언제든 프로퍼티와 메소드를 추가하거나 바꾸고 삭제 할 수 있다. ```javascript var person = new Object(); person.name = "Nicholas"; console.log(person.name); //"Nicholas" ``` 위 예제에서는 객체를 생성한 후 person이란 변수에 저장했다. 다음에는 name이란 프로퍼티를 추가하고 문자열 값을 할당했다. 이 시점부터 객체가 파괴되거나 프로퍼티를 명시적으로 제거하기 전까지는 해당 프로퍼티에 접근할 수 있다. #### 4.1.2 값 복사 원시 값과 차조 값은 저장되는 방식 외에도 변수에서 다른 변수로 값을 복사할 때도 다르게 동작한다. 원시 값을 다른 변수로 복사할 때는 현재 저장된 값을 새로 생성한 다음 새로운 변수에 복사한다. ```javascript var num1 = 5; var num2 = num1; ``` 1. 여기에서 num1에는 값 5가 저장되어 있다. 2. num2를 num1로 초기화하면 num2에도 값 5가 저장된다. 3. 이 값은 복사된 것이믐로 num1에 저장된 값과는 완전히 분리되어있다. > 즉 num2값을 변경하더라도 num1과는 아무 상관이 없다. 반면, 참조 값을 변수에서 다른 변수로 복사하면 원래 변수에 들어있던 값이 다른 변수에 복사되기는 마찬가지다. 차이는 그 값이 **객체 자체가 아니라 `힙(heap)`에 저장된 객체를 가리키는 포인터라는 점이다.** 조작이 끝나면 두 변수는 정확히 같은 객체를 가리킨다. 따라서 다음 예제처럼 한쪽을 조작하면 다른 쪽에도 반영된다. ```javascript var obj1 = new Object(); var obj2 = obj1; obj1.name = "Nicholas"; alert(obj2.name); //Nicholas ``` #### 4.1.3 매개변수 전달. ECMAScript의 함수 매개변수는 모두 값으로 전달된다. 함수 외부에 있는 값은 함수 내부의 매개변수에 복사되는데, 이는 변수 사이에서 값을 복사하는 것과 마찬가지다 값이 원시 값이라면 변수 사이에서 원시 값을 복사하는 것과 마찬가지이며 참조 값일 때도 변수 사이에서 참조 값을 복사하는 것과 마찬가지다. > 개발자들이 자주 혼란스러워 하는 부분이므로 주의하자 매개변수를 값 형태로 넘기면 해당 값은 지역변수에 복사된다. 즉 이르 붙은 매개변수로 복사되며 ECMAScript에서는 arguments 객체의 한 자리를 차지한다. 매개변수를 참조형태로 넘기면 메모리 상의 값의 위치가 지역 변수에 저장되므로 지역 변수를 변경하면 함수 바깥에도 해당 변경 내용이 반영된다. 다음예제를 보자 ```javascript function addTen(num) { num += 10; return num; } var count = 20 var result = addTen(count); console.log(count); //20 console.log(result); //10 ``` 함수 addTen()은 매개변수 num을 넘겨받는데 이 변수는 기본적으로는 지역변수다. 이 코드를 실행하면 변수 count가 매개변수로 전달된다. 변수의 값은 20이었는데 이 값이 매개변수 num에 10을 더해 값을 바꾸지만 함수 외부에 있는 변수 count는 바뀌지 않는다. 매개변수 num과 변수 count는 이제 상관없는 값이다. 만약 num을 참조로 전달했다면 함수 내부의 변화를 반영해 count의 값도 30으로 바뀌었을 것이다. 이런 사실은 숫자 같은 원시 값에서는 분명히 드러나지만 객체에서는 그닥 명확하지 않다. 예를 들어 다음의 코드를 보자 ```javascript function setName(obj){ obj.name="Nichols"; } var person = new Object(); setName(person); alert(person.name); // "Nicholas" ``` 이 코드에서는 객체를 만들어 변수 person에 저장했다. 이 객체를 setName()함수에 넘기면 함수는 해당 객체를 obj에 복사한다. 함수 내부에서는 obj와 person이 모두 같은 객체를 가리킨다. 결과적으로 obj는 함수에 값 형태로 전달되었지만 참조를 통해 객체에 접근한다. 함수 내부에서 obj객체에 name 프로퍼티를 추가하면 하수 외부의 객체에도 반영되는데 obj가 가리키는 것은 힙에 존재하는 전역 객체이기 때문이다. > 흔히 많은 개발자들이 함수 안에서 객체를 조작했을때 외부에도 반영됨을 보고 매개변수가 참조 형태로 전달되었다고 오해한다. 객체가 값으로 전달됨을 명확히 하기 위해 이전 코드를 다음과 같이 수정해보자 ```javascript function setName(obj){ obj.name="Nicholas"; obj = new Object(); obj.name = "Greg"; } var person = new Object(); setName(person); alert(person.name); ``` 이 예제가 이전과 다른 점은 setName()에 코드를 두 줄 추가해서 obj를 새로운 객체로 재정의했다는 점인데. 만약 person이 참조로 전달됐다면 person이 가리키는 객체는 자동으로 name 프로퍼티가 "Greg"인 새 객체로 바뀌었을 것이다. 하지만 person.name에 다시 접근하면 그 값은 "Nicholas"다. 함수에 값을 전달했기 때문에 함수 내부에서 매개변수의 값이 바뀌었음에도 불구하고 원래 객체에 대한 참조를 그대로 유지한 것이다. **함수 내부에서 obj를 덮어쓰면 obj는 지역객체를 가리키는 포인터가 되며 이 지역객체는 함수가 실행을 마치는 즉시 파괴된다.** #### 4.1.4 타입판별 이전 장에서 소개한 typeof연산자는 변수가 원시타입인지 파악하기에 최상이다. 만약 값이 객체이거나 null이면 typeof는 `object`를 반환한다. 이처럼 `typeof`는 원시 값에 대해서는 잘 동작하지만 참조 값에 대해서는 별 쓸모가 없다. 이럴때 사용하는 것이 instanceof 연산자는 이런 상황에 도움이 되며 다음 문법에 따라 사용한다. `'result' = 'variable' instanceof 'constructor'` instanceof 연산자는 변수가 주어진 참조 타입의 인스턴스일 때 (프로토타입 체인으로 판단) true를 반환한다. ```javascript alert(person instanceof Object); //person 함수가 Object의 인스턴스인가? alert(colors instanceof Array); //colors 변수가 Array의 인스턴스인가? alert(pattern instanceof RegExp); //pattern 변수가 RegExp의 인스턴스인가? ``` ### 4.2 실행 컨텍스트와 스코프 `실행 컨텍스트(execution context)`는 짧게 '컨텍스트'라고 부르며 자바스크립트에서는 비할 바 없이 중요한 개념이다. 변수나 함수의 실행 컨텍스트는 다른 데이터에 접근할 수 있는지, 어떻게 행동하는지를 규정한다. 각 실행 컨텍스트에는 변수 객체(variable object)가 연결되어 있으며 해당 컨텍스트에서 정의된 모든 변수와 함수는 이 객체에 존재한다. 이 객체를 코드에서 접근할 수는 없지만 이면에서 데이터를 다룰 때 이 객체를 이용한다. **가장 바깥쪽에 존재하는 실행 컨텍스트는 전역 컨텍스트다.** ECMAScript를 구현한 환경에 따라 이 컨텍스트를 부르는 이름이 다르다. 웹브라우져는 이 컨텍스트를 `window`라 부르므로 전역 변수와 함수는 모두 window 객체의 프로퍼티 및 메소드로 생성된다. - 실행 컨텍스트는 포함된 코드가 모두 실행될 때 파괴된다. - 해당 컨텍스트 내부에서 정의된 변수와 함수도 함께 파괴된다. - 전역 컨텍스트는 애플리케이션이 종료될때, 예를 들어 웹페이지에서 나가거나 브라우져를 닫을 때 까지 계속 유지된다. - 함수를 호출하면 독자적인 실행 컨텍스트가 생성된다. - 코드 실행이 함수로 들어갈 때마다 함수의 컨텍스트가 컨텍스트 스택에 쌓인다. - 함수 실행이 끝나면 해당 컨텍스트를 스택에서 꺼내고 컨트롤을 이전 컨텍스트에 반환한다. > 컨텍스트에서 코드를 실행하면 변수 객체에 `스코프 체인(scope chain)`이 만들어 진다. 이 스코프 체인의 목적은 실행 컨텍스트가 접근할 수 있는 모든 변수와 함수에 순서를 정의하는 것이다. 1. 스코프 체인의 앞쪽은 항상 코드가 실행되는 컨텍스트의 변수 객체다. 2. 변수객체 다음 순서는 해당 컨텍스트를 포함하는 컨텍스트(부모컨텍스트)이다. 3. 그 다음에는 다시 붐모의 부모 컨텍스트로 순서가 진행된다.. 위와 같은 순서로 계속 진행하여 전역 컨텍스트에 도달할 때 까지 계속한다. 즉 전역 컨텍스트의 변수객체는 항상 스코프 체인의 마지막에 존재한다. ```javascript var color = "blue"; function changeColor(){ var anotherColor = "red"; function swapColors(){ var tempColor = anotherColor; anotherColor = color; color = tempColor; // color, anotherColor, tempColor 모두 접근 가능 } // color, anotherColor 접근가능 , tempColor 는 불가능 swapColors(); } //color 만 접근가능 changeColor(); ``` 위 예제에는 실행 컨텍스트가 세 개 있다. 전역 컨텍스트, changeColor()의 로컬컨텍스트, swapColors()의 로컬 컨텍스트 세 개다 1. 전역컨텍스트에는 color변수와 changeColor()함수가 포함 2. changeColor()의 로컬 컨텍스트에는 anotherColor 변수와 swapColors()만 있지만 전역 컨텍스트의 color변수에도 접근가능하다 3. ..... 각 컨텍스트는 스코프 체인을 따라 상위 컨텍스트에서 변수나 함수를 검색할 수 있지만 스코프 체인을 따라 내려가며 검색할 수는 없다. #### 4.2.1 스코프 체인 확장 실행 컨텍스트에는 전역 컨텍스트와 함수 컨텍스트 두 가지 타입만 있지만(eval()을 호출할 때 생성되는 세 번째 타입이 있긴 하다.) 스코프 체인을 확장할 수 있는 방법도 있다. 특정 문장은 스코프 체인 앞부분에 임시로 변수 객체를 만들며 변수 객체는 코드 실행이 끝나면 사라진다. 이렇게 임시 객체가 생성되는 경우는 다음 두 가지다. - try ~catch 문의 catch 블록 - with ㅁ문 두 문장은 모두 스코프 체인 앞에 변수 객체를 추가한다. #### 4.2.2 자바스크립트에는 블록 레벨 스코프가 없다. 자바스크립트에는 블록레벨 스코프가 없는데 이는 종종 혼란을 일으킨다. 보통 for 문같은 경우는 다음과 같이 사용하는데 ```javascript for( var i=0; i<10; i++){ doSomething(i); } alert(i); //10 ``` 블록 레벨 스코프를 지원하는 언어에서는 for 문의 초기화 부분에서 선언한 변수가 오직 for 문의 컨텍스트 안에서만 존재한다. 자바스크립트에서는 for 문에서 생성한 i 변수가 루프 실행이 끝난 후에도 존재한다. **변수 선언 ** `var`를 사용해 선언한 변수는 자동으로 가장 가까운 컨텍스트에 추가된다. 함수 내부에서는 함수의 로컬 컨텍스트가 가장 가까운 컨텍스트이며 `with 문` 내부에서는 함수 컨텍스트가 가장 가까운 컨텍스트이다. 즉 `var`을 선언하지 않으면 전역 컨텍스트에 생성이 된다는 뜻 **식별자 검색** 컨텍스트 안에서 식별자를 참조하려 하면 먼저 검색부터 해야 한다. 검색은 스코프 체인 앞에서 시작하며 주어진 이름으로 식별자를 찾는다. 1. 로컬 컨텍스트에서 식별자 이름을 찾으면 검색을 멈추고 변수를 설정한다. 2. 만약 찾지 못한다면 스코프 체인을 따라 검색을 계속한다. 3. 전역 컨텍스트의 변수 객체에 도달할 때까지 이 과정을 반복한다. 4. 전역 컨텍스트의 변수 객체에서도 식별자를 차지 못하면 정의 되지 않은것으로 판단한다. 다음의 코드를 통해 식별자 검색이 어떻게 이루어지는지 생각해보자 ```javascript var color = "blue"; function getColor(){ return color; } alert(getColor()); // blue ``` 먼저 getColor()의 변수 객체에서 color라는 식별자 이름을 검색하고, getColor()의 변수 객체에서 찾지 못하면 다음(전역 컨텍스트) 변수 객체에서 color 식별자를 검색한다. 검색과정을 보면 지역변수를 참조할 때는 다음 변수를 검색하지 않도록 자동으로 검색을 멈춤을 알 수 있는데 달리 말해 다음과 같이 식별자가 로컬 컨텍스트에 정의되어 있으면 부모 컨텍스트에 같은 이름의 식별자가 있다 해도 참조 할 수 엇ㅂ다 ```javascript var color = "blue"; function getColor(){ var color = "red" return color; } alert(getColor()); // red ``` 가령 위와같이 getColor() 안에 지역변수 color를 설정해놓으면 로컬컨텍스트에서 검색을 마치고 전역 변수로는 접근하지 않는다. 위 소스에서 만약 전역 컨텍스ㅏ트의 color변수를 이용하려면 `window.color` 라고 명시해야 한다. > 변수 검색에도 비용이 들어가게 되는데 지역변수는 스코프 체인을 따라 올라가며 검색할 피룡가 없으므로 전역 변수보다 빨리 검색된다. > 자바스크립트 엔진에서 식별자 검색을 최적화하고 있으므로 미래에는 이런 차이가 무시할만한 정도로 좁혀질 수도 있다. ### 4.3 가비지 콜렉션 자바스크립트는 실행환경에서 코드 실행중에 메모리를 관리하는데 이런의미에서 가비지 콜렉션 언어라고 불러도 된다. 자바스크립트는 필요한 메모리를 자동으로 할당하고 더 이상 사용하지 않는 메모리는 자동으로 회수하므로 개발자가 직접 메모리를 관리하지 않아도 된다. 그 개념은 아주 단순한데, > 더 이상 사용하지 않을 변수를 찾아내서 해당 변수가 차지하고 있던 메모리를 회수하는 것이다. 이 프로세스는 주기적으로 실행되는데 코드 실행 중에 특정 시점에서 메모리를 회수하도록 지정할 수도 있다. **함수의 지역 변수를 통해 생각해보자** 1. 함수를 실행하면 변수가 생성된다. 2. 해당 시점에서 스택에 변수의 값을 저장할 메모리가 할당된다.(힙에도 할당될 수 있다. 3. 변수는 함수안에서만 존재하므로 함수가 종료되면 변수는 더 이상 필요하지 않고 , 따라서 해당 변수가 차지하고 있던 메모리를 회수해 다른 용도로 쓸 수 있다. 위와 같은 상황이라면 분면 해당 변수가 더 이상 필요 없지만 이렇게 분명하지 않은 경우도 많다. > 즉 분명하지 않은 상황에서 `가비지 콜렉터`는 어떤 변수가 더 이상 사용되지 않는지, 사용될 가능성이 있는 변수는 무엇인지 추적해야 메모리 회수 대상을 정할 수 있다. 더 이상 사용하지 않는 변수를 식별하는 기준은 브라우저마다 다르지만 보통 두 가지 방법을 흔히 채용한다. #### 4.3.1 표시하고 지우기 자바스크립트에서 가장 널리 쓰이는 가비지 컬렉션 방법은 `표시하고 지우기(mark-and-sweep)`라 불린다. > 변수가 특정 컨텍스트 안에서 사용할 것으로 사용할 것으로 정의되면(예를 들어 함수 안에서 변수를 정의하면) 그 변수는 그 컨텍스트 안에 있는 것으로 표시된다. > 컨텍스트 안에 존재하는 변수의 메모리는 해제해서는 안되는데, 해당 컨텍스트가 실행 중인 한 사용될 가능성이 있기 때문이다. > 변수가 컨텍스트 밖으로 나가면 컨텍스트 밖에 있는 것으로 표시된다. 변수에 표시하는 방법은 다양한데, 변수가 컨텍스트 안에 있을 때 특정 비트를 `on` 상태로 표시할 수도 있고, "컨텍스트 내부"와 "컨텍스트 외부"를 나타내는 변수 목록을 따로 두어서 변수의 움직임을 추적할 수도 있지만, 이를 어떻게 구현 했느냐는 중요하지 않은 탁상공론일 뿐이다. 가비지 컬렉터가 작동하면 메모리에 저장된 변수 전체에 표시를 남긴다. 그 다음 컨텍스트에 있는 변수와, 컨텍스트에 있는 변수가 참조하는 변수에서 표시를 지운다. 이 과정을 거친 다음에도 표시가 남아 있는 변수는 컨텍스트에 있는 변수와 무관하므로 삭제해도 안전하다. <file_sep>/java/java_web_develop_workBook/3장. 서블릿 프로그래밍/README.md ## 3. 서블릿 프로그래밍 ### 1) 서블릿(servlet)이란? 자바에서는 웹 브라우저와 웹서버를 활용하여 좀 더 쉽게 서버 어플리케이션을 개발할 수 있도록 `서블릿(Servlet)`이라는 기술을 제공하고 있다. 이 서블릿 기술을 이용하여 웹 어플리케이션을 개발하는 것을 보통 `서블릿 프로그래밍`이라 부른다. ### 2) CGI 프로그램과 서블릿 사용자가 직접 아이콘을 더블 클릭하거나 명령 창(터미널)을 통해 실행시키는 프로그램을 일반적으로 '애플리케이션' 또는 '데스크톱 애플리케이션'이라고 한다. 반면에 사용자가 웹을 통해 간접적으로 실행시키는 프로그램이 ' 웹 어플리케이션'이다. `웹 어플리케이션`이 실행은 `웹브라우저`가 `웹서버`에게 실행을 요청하고, `웹 서버`는 `클라이언트`가 요청한 프로그램을 찾아서 실행한다. 해당 프로그램은 작업을 수행한 후 그 결과를 웹서버에게 돌려준다. 그러면 웹서버는 그결과를 `HTTP` 형식에 맞추어 웹 브라우저에게 보낸다. > 이때 웹서버와 프로그램 사이의 데이터를 주고받는 규칙을 `CGI(Common Gateway Interface)`라고 한다 > 이렇게 웹서버에 의해 실행되며 `CGI` 규칙에 따라서 웹 서버와 데이터를 주고 받도록 작성된 프로그램을 `CGI 프로그램`이라고 한다. ##### CGI 프로그램 - `CGI`프로그램은 `C`나 `C++`, `Java` 와 같은 컴파일 언어로 작성할 수 있으며 `Perl`, `PHP`, `Python`, `VBScript` 등 스크립트 언어로도 작성할 수 있다. - 컴파일 방식은 기계어로 번역된 코드를 바로 실행하기 때문에 실행속도가 빠르지만, 변경사항이 발생할 때마다 다시 컴파일 하고 재배포 해야 하는 문제가 있다. - 스크립트 방식은 실행할 때마다 소스코드의 문법을 검증하고 해석해야 하기 때문에 실행속도가 느리다. - 하지만 변경사항이 발생하면 단지 소스코드를 수정하고 저장만 하면 되기때문에 편리하다. ##### 서블릿 - 자바 `CGI 프로그램`은 `C/C++` 처럼 컴파일 방식이다. - 자바로 만든 `CGI 프로그램`을 `서블릿`이라고 부른다. - 자바 서블릿이 다른 `CGI 프로그램`과 다른점은, 웹 서버와 직접 데이터를 주고받지 않으며, 전문 프로그램에 의해 관리된다는 점이다. 1) 서블릿 컨테이너 - 서블릿의 생성과 실행, 소멸 등 생명주기를 관리하는 프로그램을 `서블릿 컨테이너(Servlet Container)`라고 한다 - 서블릿 컨테이너가 서블릿을 대신하여 `CGI`규칙에 따라 웹 서버와 데이터를 주고 받는다. - 서블릿 개발자는 더이상 `CGI 규칙`에 대해 알 필요가 없다. 대신 `서블릿 컨테이너`와 `서블릿 사이의 규칙`을 알아야 한다. - 자바 웹 어플리케이션 개발자는 `JaveEE`기술 사양에 포함된 `Servlet`규칙에 따라 `CGI 프로그램` 을 만들고 배포한다. ### 3) 서블릿, JSP vs. JavaEE vs. WAS 이번 절에서는 자바 웹 프로그래밍 기술인 `서블릿`, `JSP`와 `JavaEE(Java Platform, Enterprise Edition)`의 관계를 이해하고, `WAS(Web Application Server)`가 무엇인지 알아보자 ##### Java EE > [자바오라클사이트](http://java.oracle.com) 사이트에 방문하여 Software Downloads 영역에서 `Java EE and GlassFish`링크를 클릭하여 `Technologies`탭을 클릭하면 `JavaEE`에 속한 하위 기술 목록이 출력된다. > 여기서 웹어플리케이션 관련 기술을 확인할 수 있다. - Java EE는 기능 확장이 쉽다. - 이기종 간의 이식이 쉽다. - 신뢰성과 보안성이 높다. - 트랜잭션 관리와 분산 기능을 쉽게 구현할 수 있는 기술을 제공한다. - `JavaEE`기술 사양은 한 가지 기술을 정의한 것이 아니라 기업용 어플리케이션과 클라우드 어플리케이션 개발에 필요한 여러가지 복합적인 기술들을 정의하고 모아 놓은 것이다. ##### WAS의 이해 - 클라이언트 서버 시스템 구조에서 서버쪽 애플리케이션의 생성과 실행, 소멸을 관리하는 프로그램을 `애플리케이션 서버(Application Server)`라 한다. - 서블릿과 서블릿 컨테이너와 같이 웹 기술을 기반으로 동작되는 애플리케이션 서버를 `WAS`라고 부른다. - 특히 `Java`에서 말하는 `WAS`란, `JavaEE`기술 사양을 준수하여 만든 서버를 가리킨다. 다른 말로 `JavaEE 구현체(Implementation)`라고도 말한다. > 상용제품으로는 티맥스소프트의 `제우스(JEUS)`, 오라클의 `웹로직`, IBM의 `웹스피어`, 레드햇의 `제이보스엔터프라이즈`등이 있다. > 무료 또는 오픈소스로는 레드햇의 `제이보스 AS`, 오라클의 `GlassFish`, 아파치 재단의 `Geronimo` 등이 있다 --- > 이클립스를 이용한 웹프로젝트 생성 에제는 P.111 ~ 114 참조 ```java package lesson03.servlets; import java.io.IOException; import javax.servlet.Servlet; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; / public class Helloworld extends Servlet { ServletConfig config; @Override public void init(ServletConfig config) throws ServletException{ System.out.println("init() 호출됨"); this.config=config; } @Override public void destroy(){ System.out.println("destroy() 호출됨"); } @Override public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException{ System.out.println("service() 호출됨"); } @Override public ServletConfig getServletConfig(){ System.out.println("getServletConfig() 호출됨"); return this.config; } @Override public String getServletInfo(){ System.out.println("getServletInfo() 호출됨"); return "version=1.0;author=eomjinyoung;copyright=eomjinyoung 2013"; } } ``` ##### javax.servlet.Servlet 인터페이스 서블릿 클래스는 반드시 javax.servlet.Servlet 인터페이스를 구현해야 한다. 서블릿 컨테이너가 서블릿에 대해 호출할 메소드를 정의한 것이 Servlet 인터페이스다. 1) 서블릿의 생명주기와 관련된 메서드 : `init()`, `service()`, `destroy()` `Servlet`인터페이스에 정의된 다섯 개의 메서드 중에서 서블릿의 생성과, 실행, 소멸, 즉 생명주기 Lifecycle 과 관련된 메서드가 `init()`, service(), `destroy()` 이다. init() - 서블릿 컨테이너가 서블릿을 생성한 후 초기화 작업을 수행하기 위해 호출하는 메서드 - 서블릿이 클라이언트의 요청을 처리하기 전에 준비할 작업이 있다면 이 메서드에 작성해야한다. - 예를 들어 이 메서드가 호출될 때 데이터베이스에 연결하거나 외부 스토리지 서버와의 연결, 프로퍼티 로딩 등 클라이언트 요청을 처리하는데 필요한 자원을 미리 준비할 수 있다. service - 클라이언트가 요청할 때 마다 호출되는 메서드 - 실질적으로 서비스 작업을 수행하는 메서드로, 이 메소드에 서블릿이 해야 할 일을 작성하면 된다. - 예제 소스는 단시 메소드가 호출되었음을 확인하기 위해 서버 실행 창으로 간단한 문구를 출력하도록 한것이다. destroy - 서블릿 컨테이너가 종료되거나 웹 어플리케이션이 멈출 때, 또는 해당 서블릿을 비활성화 시킬때 호출된다. - 따라서 이 메소드에는 서비스 수행을 확보했던 자원을 해제한다거나 데이터를 저장하는 등의 마무리 작업을 작성하면 된다. ##### 서블릿 배치 정보 작성 > WebContent/WEB-INF/web.xml 파일 ```xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Lesson03</display-name> <!-- 서블릿 선언 --> <servlet> <servlet-name>Hello</servlet-name> <servlet-class>lesson03.servlets.HelloWorld</servlet-class> </servlet> <servlet> <servlet-name>Calculator</servlet-name> <servlet-class>lesson03.servlets.CalculatorServlet</servlet-class> </servlet> <!-- 서블릿을 URL과 연결 --> <servlet-mapping> <servlet-name>Hello</servlet-name> <url-pattern>/Hello</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>Calculator</servlet-name> <url-pattern>/calc</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> </web-app> ``` - web.xml 파일을 `배치 기술서` 또은 약어로 `DD파일` 이라고 부른다. - 웹 애플리케이션의 배치 정보를 담고 있는 파일이다. - 따라서 서블릿을 만들었으면 DD파일에 배치 정보를 등록해야 한다. - 그래야만 클라이언트에서 해당 서블릿의 실행을 요청할 수 있다. - DD파일에 등록되지 않은 서블릿은 서블릿 컨테이너가 찾을 수 없다. 서블릿 선언 - 서블릿 배치 정보를 작성할 때 먼저 `<servlet>`태그를 사용하여 서블릿 별명과 서블릿 클래스명을 설정한다 - `<servlet-name>`은 서블릿 별명을 설정하며, 클래스 이름일 필요는 없다. 공백을 포함해도 된다 - `<servlet-class>`는 패키지 이름을 포함한 서블릿 클래스명을 설정한다. ```xml <servlet> <servlet-name>Hello</servlet-name> <servlet-class>lesson03.servlets.HelloWorld</servlet-class> </servlet> ``` > 패키지명 + 클래스명 = Fully qualified name = QName 서블릿에 URL 부여 - 클라이언트에서 서블릿의 실행을 요청할 때는 URL을 사용한다. - 따라서 서블릿에 URL을 부여해야 클라이언트에서 요청할 수 있다. - `<servlet-name>`은 `<setvlet>` 태그에서 정의한 서블릿 별명이 온다. - `<url-pattern>`은 서블릿을 요청할 때 클라이언트가 사용할 URL을 설정한다. --- ##### 서블릿 구동 절차 1) 클라이언트의 요청이 들어오면 서블릿 컨테이너는 서블릿을 찾는다. 2) 만약 서블릿이 없다면, 서블릿 클래스를 로딩하고 인스턴스를 준비한 후 생성자를 호출한다. 그리고 서블릿 초기화 메서드인 inint()을 호출한다. 3) 클라이언트 요청을 처리하는 service() 메소드를 호출한다. 메소드 이름을 보면 이미 그 용도를 짐작할수 있다. 즉, 클라이언트의 요청에 대해 서비스를 제공한다는 뜻이다. 4) service() 메소드에서 만든 결과를 HTTP 프로토콜에 맞추어 클라이언트에 응답하는 것으로 요청처리를 완료한다. 5) 만약 시스템 운영자가 서블릿 컨테이너를 종료하거나, 웹 어플리케이션을 종료한다면, 6) 서블릿 컨테이너는 종료되기 전에 서블릿이 마무리 작업을 수행할 수 있도록 생성된 모든 서블릿에 대해 destroy() 메소드를 호출한다. > 콘솔창을 살펴보면, ```java init() 호출됨 service() 호출됨 ``` 위와 같이 호출되고 브라우져의 새로고침을 눌러보면 service()메소드만 추가되는 것을 볼 수 있다. 그 이유는 이미 Helloword 객체가 존재하기 때문이다. > 서블릿 컨테이너는 클라이언트로부터 요청을 받으면 해당 서블릿을 찾아보고, 만약 없다면 해당 서블릿의 인스턴스를 생성한다. > 서블릿 객체가 생성되면 웹 애플리케이션을 종료할 때까지 계속 유지한다. 서블릿 인스턴스는 하나만 생성되어 웹 애플리케이션이 종료될 때까지 사용된다. 따라서 인스턴스 변수에 특정 사용자를 위한 데이터를 보관해서는 안된다. 도한, 클라이언트가 보낸 데이터를 일시적으로 보관하기 위해 서블릿의 인스턴스 변수를 사용해서도 안된다. > destroy()가 호출되는 경우는 톰캣서버를 종료하는 것이다. --- ##### 웰컴 파일들 - 웹서버에게 요청할때 서블릿 이름을 생략하고 디렉터리 위치까지만 지정한다면, 웹 서버는 해당 디렉터리에서 웰컴 파일을 찾아서 보내준다. - 웰컴파일의 이름은 `web.xml`의 `<welcome-file-list>`태그를 사용하여 설정할 수 있다. - 여러개의 웰컴파일을 등록하게 되면 디렉토리에서 웰컴파일을 찾을 때 위에서부터 순차적으로 조회하여 먼저 찾은 것을 클라이언트로 보낸다. ```xml <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> ``` --- ### 4) GenericServlet의 사용 ##### GenericServlet이 없던 시절 > 지금까지는 서블릿클래스를 만들 때 Servlet 인터페이스를 구현했다. > 인터페이스를 구현하려면 인터페이스에 선언된 모든 메소드를 구현해야 하므로, 서블릿을 만들 때마다 Servlet인터페이스에 선언된 다섯 개의 메소드를 모두 구현했다. > 사실 이 메소드 중에서 반드시 구현해야 하는 메소드는 `service()`다. 클라이언트가 요청할 때마다 호출되기 때문이다. > `init()`의 경우 서블릿이 생성될 때 딱 한번 호출되는데, 서블릿을 위해 특별히 준비해야 하는 작업이 없다면 굳이 구현할 필요가 없다. (`destroy()`메소드도 마찬가지) > 그럼에도 '인터페이스를 구현하는 클래스는 반드시 인터페이스에 선언된 모든 메소드를 구현해야 한다.'라는 것이 자바의 법이기 때문에 다음과 같이 빈 메소드라도 구현해야 한다. ```java public void init(ServletConfig config) throws ServletException{ this.config = config; } public void destroy(){} ``` > 이런 불편한 점을 해소하기 위해 등장한 것이 바로 `GenericServlet` 추상 클래스이다. ##### GenericServlet의 용도 - `GenericServlet`은 추상클래스라는 말로 짐작할 수 있듯이 하위 클래스에게 공통의 필드와 메소드를 상속해 주고자 존재한다. - 서블릿 클래스가 필요로 하는 init(), destroy(), getServletConfig(), getServletInfo()를 미리 구현하여 상속해 준다. - service()는 어차피 각 서블릿 클래스마다 별도로 구현해야 하기 때문에 `GenericServlet`에서는 구현하지 않는다. 서블릿을 만들 때 `GenericServlet`을 상속받는다면 `Servlet` 인터페이스의 메소드 중에서 service()만 구현하면 된다. > 이전절의 `HelloWorld` 클래스가 `GenericServlet`을 상속받는다면 그 코드는 다음과 같을 것이다 ```java public class HelloWorld extends GenericServlet{ @Override public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException{ System.out.println("service() 호출됨"); } } ``` ##### ServletRequest > 계산기 예제소스를 통해 알아보자 ```java // 생략 @Override public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { int a = Integer.parseInt( request.getParameter("a") ); int b = Integer.parseInt( request.getParameter("b") ); response.setContentType("text/plain"); response.setCharacterEncoding("UTF-8"); PrintWriter writer = response.getWriter(); writer.println("a=" + a + "," + "b=" + b + "의 계산결과 입니다."); writer.println("a + b = " + (a + b)); writer.println("a - b = " + (a - b)); writer.println("a * b = " + (a * b)); writer.println("a / b = " + ((float)a / (float)b)); writer.println("a % b = " + (a % b)); } ``` service()의 매개변수 중에서 `ServletRequest` 객체는 클라이언트의 요청 정보를 다룰 때 사용한다. 이 객체의 주요 기능 몇 가지를 알아보자 위 소스에서 사용한 `getParameter()`는 GET 이나 POST 요청으로 들어온 매개변수 값을 꺼낼때 사용한다. `http://...생략.../calc?a=20&b=30` ```java request.getParameter("a"); ``` 1) getRemoteAddr() - 서비스를 요청한 클라이언트의 IP주소를 반환합니다. 2) getScheme() - 클라이언트가 요청한 URI 형식 Shceme을 반환합니다.. - 즉 URL에서 `:`문자 전에 오는 값을 반환합니다. URL에서 스킴의 의미는 자원을 식별하는 최상위 분류 기호다 - 스킴의 예로 `http`, `https`, `ftp`, `file`, `news`등이 있다. 3) getProtocol() - 요청 프로토콜의 이름과 버전을 반환한다. - 예 : HTTP/1.1 4) getParameterNames() - 요청정보에서 매개변수 이름만 추출하여 반환한다. 5) getParameterValues() - 요청정보에서 매개변수 값만 추출하여 반환한다. 6) getParameterMap() - 요청정보에서 매개변수들을 Map 객체에 담아서 반환한다. 7) setCharacteEncoding() - POST 요청의 매개변수에 대해 문자 집합을 설장한다. - 기본값은 `ISO-8859-1`로 설정되어 있다. - 매개변수의 문자 집합을 정확히 지정해야만 제대로 변환된 유니코드 값을 반환한다. - 매개변수의 문자 집합을 지정하지 않으면 무조건 ISO-8859-1이라 가정하고 유니코드로 변환한다. - 주의할 점은 처음 `getParameter()`를 호출하기 전에 이 메서드를 먼저 호출해야만 적용이 된다. --- ##### ServletResponse - `ServletResponse`객체는 응답과 관련된 기능을 제공한다. - 클라이언트에게 출력하는 데이터의 인코딩 타입을 설정하고, 문자집합을 지정하며, 출력 데이터를 임시보관하는 버퍼의 크기를 조정하거나, 데이터를 출력하기 위해 출력 스트림을 준비할 때 이 객체를 사용한다. 1) setContentType() - 출력할 데이터의 인코딩 형식과 문자 집합을 지정한다. - 클라이언트에게 출력할 데이터의 정보를 알려주어야 클라이언트는 그 형식에 맞추어 올바르게 화면에 출력(Rendering)할 수 있다. - 예를 들어 `HTML`형식이면 태그 규칙에 맞추어 화면에 출력할 것이고, `XML`형식이면 각 태그를 트리 노드로 표현할 것이다. 2) setCharacterEncoding() - 출력할 데이터의 문자 집합을 지정한다. - 기본값은 `ISO-8859-1`이다. - 가령 아래 코드는 출력할 데이터의 문자 집합을 'UTF-8'로 설정하고 있다는 뜻이다. 즉 데이터를 출력할때 유니코드 값을 UTF-8 형식으로 변환하라는 뜻이다. `response.setCharacterEncoding("UTF-8");` - 출력 데이터의 문자 집합은 다음과 같이 `setContentType()`을 사용하여 설정할 수도 있다. `response.setContentType("text/plain;chartest=UTF-8");` 3) getWriter() - 클라이언트로 출력할 수 있도록 출력 스트림 객체를 반환한다. - 이미지나 동영상과 같은 바이너리 데이터를 출력하고 싶을때는 `getOutputStream()`을 사용하자 --- ### 5) 정리 ##### CGI > 웹 서버가 실행시키는 프로그램을 `웹 어플리케이션`이라고 한다. 웹 서버와 웹 어플리케이션 사라이에는 데이터를 주고받기 위한 규칙이 있는데 이것을 `CGI(Common Gateway Interface)`라고 한다. 그래서 보통 웹 어플리케이션을 `CGI프로그램`이라고도 부른다. ##### 서블릿 > 특히 자바로 만든 웹 어플리케이션을 서블릿이라고 부르는데, Server와 Applet의 합성어다 > 즉, '클라이언트에게 서비스를 제공하는 작은 단위의 서버프로그램'이라는 뜻이다. ##### 서블릿컨테이너 > 서블릿의 생성에서 실행, 소멸까지 서블릿의 생명주기를 관리하는 프로그램이다. > 클라이언트로부터 요청이 들어오면, 서블릿 컨테이너는 호출 규칙에 따라 서블릿의 메소드를 호출한다. > 서블릿 호출 규칙은 javax.servlet.Servlet 인터페이스에 정의되어 있다. > 따라서 서블릿을 만들 때는 반드시 `Servlet 인터페이스`를 구현해야만 한다. ##### JavaEE > `Servlet`라는 규칙 외에 `JSP`를 만들고 실행하는 규칙, `EJB(Enterprise JavaBeans)`라는 분산 컴포넌트에 관한 규칙, 웹 서비스에 관한 규칙 등 기업용 어플리케이션 제작에 필요한 기술들의 사양을 정의한 것을 `JavaEE`라고 한다. > `JavaEE`는 이기종 간의 이식이 쉬우며, 신뢰성과 보안성이 높고 트랜잭션 관리와 분산기능을 쉽게 구현할 수 있는 기술을 제공한다. ##### WAS > JavaEE 사양에 따라 개발된 서버를 `Java EE 구현체(implementation)` 또는 `WAS`라고 부른다. ##### 서블릿 라이브러리 > 서블릿을 좀 더 편리하게 개발할 수 있도록 javax.servlet.GenericServlet 이라는 추상클래스를 제공한다. > GenericServlet 추상클래스는 Servlet 인터페이스에 선언된 메소드 중에서 service()를 제외한 나머지 메소드를 모두 구현해놓았다. > <file_sep>/Front-End/snippet/embeded responsive/README.md 유튜브 동영상 공유 소스 코드의 예. ```xml <iframe width="560" height="315" src="https://www.youtube.com/embed/xPvyrmPszlY" frameborder="0" allowfullscreen></iframe> ``` > 일반적으로 위소스처럼 넓이는 560, 높이는 315등등 사이즈가 고정되어 있을경우 해결 방법. `<div>` 클래스와 CSS 스타일로 해결 가능. 유튜브 동영상을 반응형으로 알맞게 보여주기 위한 클래스를 css 파일에 정의하여 적용합니다. 코드는 아래 참조~ ```css .embed-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; } .embed-container iframe, .embed-container object, .embed-container embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } ``` ```xml <div class='embed-container'> <iframe width="560" height="315" src="https://www.youtube.com/embed/-kypVh6MM4U" frameborder="0" allowfullscreen></iframe> </div> ``` `.padding-bottom: 56.25%`의 의미 #### 16:9 와이드 비율 `9 / 16 = 0.5625 = 56.25%` 가로 폭은 가변형이므로 padding-bottom 수치를 퍼센트로 지정하여 16:9의 와이드 화면 비율로 보여주는 방식. 위 아래의 검은 색 레터박스 없이 동영상이 재생된다. #### 4:3 표준 비율 `3 / 4 = 0.75 = 75%` 와이드 화면이 아닌 표준 비율의 동영상이라면 padding-bottom 값을 75%로 바꿔 주시면 됩니다. 클래스를 각각 따로 정의하여 동영상 비율에 맞게 넣으면 된다 ```css .embed-container-169 { padding-bottom: 56.25%; } .embed-container-43 { padding-bottom: 75%; } ``` > 만약 `16:9 동영상`임에도 위 아래로 조금씩 검은색 여백이 발생한다면 padding-top: 30px; 의 값을 0으로 바꾸거나 변경 <file_sep>/guide/개발 라이브러리 가이드/CI/03 . 주석 _ 파일, 클래스 명명 방법.md <style>.blue {color:#2844de;font-size:18px;}.red {color:#dd4814;font-size:18px;}.ex {color:gray;}p.me{padding:10px 8px 10px;line-height:20px;border:1px solid black;}.center{text-align:center;}</style> ## 03 . 주석 / 파일, 클래스 명명 방법 ## 주석 ```js /** * @Class 클래스명 * @Date 날짜 기입 * @Author 작성자 * @Brief 클래스 용도 */ ``` ## 파일 / 클래스 명명 방법 클래스와 파일이름은 같아야 한다. - 2.x 버전 : 파일이름은 <b class="blue">소문자</b>, 클래스이름은 <b class="red">대문자</b>로 시작 - 3.x 버전 : 파일이름과 클래스이름이 대소문자까지 같아야 한다. <br /> <file_sep>/guide/개발 라이브러리 가이드/CI/01 . CI시작하기.md <style>.blue {color:#2844de;font-size:18px;}.red {color:#dd4814;font-size:18px;}.ex {color:gray;}p.me{padding:10px 8px 10px;line-height:20px;border:1px solid black;}.center{text-align:center;}</style> ## 01 . CodeIgnighter 시작하기 ────────────── 순서 ──────────────<br />1. 다운로드<br />2. URI에서 index.php 제거하기 #### @ 다운로드 - 아래 사이트에서 다운로드를 받습니다. https://www.codeigniter.com/download - CodeIgniter 3.x - 다운로드 링크 : https://github.com/bcit-ci/CodeIgniter/archive/3.0.6.zip - CodeIgniter 2.x - 다운로드 링크 : https://github.com/bcit-ci/CodeIgniter/archive/2.2.6.zip - 3.x 와 2.x 의 차이 ||3.x | 2.x | |--|--|--| |controller 명명규칙|1. 클래스 이름과 파일 이름이 같아야 한다.<br />2. 파일이름과 클래스이름 둘다 <b class="blue">대문자</b>로 시작해야 한다.|1. 클래스 이름과 파일이름이 같아야 한다.<br />2. 클래스이름은 <b class="blue">대문자</b>로 시작해야 하고, 파일이름은 <b class="red">소문자</b>로 시작해야 한다.| | 예시|<sub style="color:gray;"># 파일이름</sub><br /><b>Test.php</b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br /><br /><sub class="ex"># 클래스 이름 </sub><br />class <b>Test</b> extends CI\_Controller{<br />&nbsp;&nbsp;&nbsp;&nbsp;function index(){<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;...<br />&nbsp;&nbsp;&nbsp;&nbsp;}<br />}|<sub style="color:gray;"># 파일이름</sub> <br /><b>test.php</b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br /><br /><sub style="color:gray;"># 클래스 이름</sub> <br />class <b>Test</b> extends CI\_Controller{<br />&nbsp;&nbsp;&nbsp;&nbsp;function index(){<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;...<br />&nbsp;&nbsp;&nbsp;&nbsp;}<br />}| <br /> #### @ index.php 파일 제거하기 - <big class="ex">example.com/<b>index.php</b>/news/article/my_article</big> --> <big class="red">example.com/news/article/my_article</big> - 1 _ Apache 설정 - apache 설정파일인 `httpd.conf` 파일에서 `mod_rewrite` 로 검색을 하면 `#LoadModule rewrite_module modules/mod_rewrite.so`라는 라인이 나옵니다. 주석처리(#)가 되어있다면, 주석(#)을 제거하시고, 위의 라인이 없다면 mod\_rewrite 모듈을 설치하셔야 합니다. - `.htaccess`파일을 사용하기 위해 서버디렉토리의 `AllowOverride 옵션`을 All로 변경하셔야 합니다. <p class="me center"> AllowOverride None -> <span class="red">AllowOverride All</span></p> - 설정을 저장하고 아파치 서버를 재시작 합니다. - 2 _ CI 설정 - `index.php`파일이 있는 디렉토리에 `.htaccess` 파일을 만듭니다. - `.htaccess`파일을 실행하여 아래의 내용을 입력합니다. ``` <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteCond $1 !^(data|index\.php|favicon\.ico|images|ci|views|uploads|common|js|css|robots\.txt) RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L] </IfModule> ``` 위의 내용중 4번째 줄의 의미는 `index.php 파일이 있는 하위 디렉토리중 images, ci, views, uploads, common, js, css 디렉토리와 index.php파일 자체, robots.txt 파일, favicon.ico파일에는 index.php 를 없애는 정규식을 적용하지 않겠다`는 말입니다. 5~6번째 줄의 의미는 `이부분은 파일이나 디렉토리가 존재하면 index.php를 거치지 않고 직접 아파치가 처리 하라는 뜻`입니다. - 출처 : http://www.codeigniter-kr.org/bbs/view/lecture?idx=7073<file_sep>/javascript/front_end_javascript/README.md # 프론트엔드 개발자를 위한 자바스크립트 프로그래밍 ## 1장 자바스크립트란 무엇인가 - - 자바스크립트가 어디에서 유래했고, 어떻게 진화했는지, 현재는 어떤 모습인지 설명한다. - 자바스크립트와 `ECMAScript`, `문서객체모델`, `브라우져 객체 모델(BOM)` 같은 개념을 소개한다. - `유럽 컴퓨터 제작자 협회(ECMA)`와 `W3C` 에서 제정한 관련 표준도 함께 서령한다. ## 2장 HTML 속의 자바스크립트 - - 자바스크립트가 HTML과 어떻게 상호작용하여 동적 웹 페이지를 만드는지 설명한다. - 페이지에 자바스크립트를 불러오는 다양한 방법을 설명하며 자바스크립트의 콘텐츠 타입과 `<script>` 요소와의 관계에 대해서도 설명한다. ## 3장 언어의 기초 - - 흐름을 제어하는 선언문과 문법을 포함해 자바스크립트의 기본 개념을 소개 - C 기반 언어와 자바스크립트 사이의 비슷한 점을 설명하고 차이점을 지목한다. - 내장 연산자와 관련된 타입 변환에 대해서도 소개 ## 4장 변수와 스코프, 메모리 - - 자바스크립트의 특징인 느슨한 타입과 하께 자바스크립트가 변수를 어떻게 다루는지 살펴본다. - 원시 데이터와 참조의 차이를 설명하며 실행 컨텍스트를 변수와의 관계를 기준으로 설명 - 변수가 스코프를 벗어났을 때 해당 변수가 사용하던 메모리를 해제하는 가비지 컬렉션이 자바스크립트에서 어떻게 동작하는지 설명 <file_sep>/java/god_of_java/Vol.1/03. OOP/Profile3.java public class Profile3 { String name ; int age; public void setName(String str) { name = str; } public void setAge(int val) { age = val; } public void printName() { System.out.println("name °ŠĀš : " + name); } public void printAge() { System.out.println("age °ŠĀš : " + age); } public static void main(String[] args) { String name = "shin"; int age = 29; System.out.println("My name is " + name); System.out.println("My age is "+ age); Profile3 p = new Profile3(); p.setName("Min"); p.setAge(20); p.printName(); p.printAge(); } }<file_sep>/guide/개발 라이브러리 가이드/CI/06. File_manager.md <style>.blue {color:#2844de;font-size:18px;}.red {color:#dd4814;font-size:18px;}.ex {color:gray;}p.me{padding:10px 8px 10px;line-height:20px;border:1px solid black;}.center{text-align:center;}</style> ## 06 File\_manager ──────────────────────순서────────────────────── 1. File\_manager 2. controller에서 적용 ──────────────────────────────────────────────── File_manager 클래스는 파일 **업로드 설정**, 파일 **업로드**, 파일 **삭제**, 파일 **다운로드**의 기능을 포함하고 있습니다. ```js <?php /** * @Class File_manager * @Date 2014. 01. 26. * @Author 비스톤스 * @Brief 파일 매니저 */ class File_manager extends CI_Model { /* * 생성자 */ function __construct() { parent::__construct(); } /** * @brief upload_config : 업로드 설정 * @param $path : 경로 * @param $type : 허용될 마임타입 * @param $size : 사이즈 */ function upload_config($path, $type, $size) { $config['upload_path'] = $_SERVER['DOCUMENT_ROOT'].'/uploads/'.$path; // 업로드 파일이 위치할 폴더경로 // $_SERVER['DOCUMENT_ROOT'] = 컴퓨터상에 프로젝트 위치 ex)c:/xampp/htdocs $config['allowed_types']= $type;// 업로드를 허용할 파일의 마임타입(mime types)을 설정 $config['overwrite'] = FALSE;// 같은 이름의 파일이 이미 존재한다면 덮어쓸지 여부 $config['max_size'] = $size;// 업로드 파일의 최대크기(KB)를 지정합니다 [2MB (2048KB)], 0으로 설정하면 크기 제한이 없음 $config['max_width'] = '0'; // 업로드 파일의 최대 높이(픽셀단위)를 설정합니다. 0이면 제한이 없습니다. $config['max_height'] = '0'; // 파일이름의 최대길이를 지정합니다.0이면 제한이 없습니다. $config['max_filename'] = '0'; // 파일이름의 최대길이를 지정합니다.0이면 제한이 없습니다. $config['encrypt_name'] = TRUE; // 파일이름은 랜덤하게 암호화된 문자열로 변합니다 $config['remove_spaces']= TRUE; // 파일명에 공백이 있을경우 밑줄(_)로 변경 return $config; } /** * @brief uploads : 업로드 설정 * @param Array $arrayFile : 업로드 파일 */ function uploads($arrayFile , $tableName='') { $img_file = ''; $orig_name=array(); // 파일의 원래 이름 저장할 배열 생성 for($i=0; $i<sizeof($arrayFile); $i++){ if ($this->upload->do_upload($arrayFile[$i])) // true -> 파일 올려짐 [ db저장 안됨 ] // ----------------------------------------> 파일 업로드에 성공하면 { $upload_data = $this->upload->data($arrayFile[$i]); // 등록된 파일의 정보를 가져옴 /* [ EX ] array(14) { ["file_name"]=> string(36) "b3c01cd4bf8eaa1adf2ecc1b06aed10f.jpg" ["file_type"]=> string(10) "image/jpeg" ["file_path"]=> string(33) "C:/xampp/htdocs/ceo/uploads/main/" ["full_path"]=> string(69) "C:/xampp/htdocs/ceo/uploads/main/b3c01cd4bf8eaa1adf2ecc1b06aed10f.jpg" ["raw_name"]=> string(32) "b3c01cd4bf8eaa1adf2ecc1b06aed10f" ["orig_name"]=> string(14) "Lighthouse.jpg" ["client_name"]=> string(14) "Lighthouse.jpg" ["file_ext"]=> string(4) ".jpg" ["file_size"]=> float(548.12) ["is_image"]=> bool(true) ["image_width"]=> int(1024) ["image_height"]=> int(768) ["image_type"]=> string(4) "jpeg" ["image_size_str"]=> string(25) "width="1024" height="768"" } */ $$arrayFile[$i] = element('file_name', $upload_data); // 파일의 암호화된 이름만 배열에 저장 $orig_name[$i] = element('orig_name', $upload_data); // 파일의 원본 이름을 배열에 저장 // 파일이 새로 들어오면 원래 있던 파일을 지우는 문단 if($arrayFile[$i]){ $query = $this->db->select($arrayFile[$i])->get($tableName); $count = $query->result(); foreach( $count as $row ){ $before_img_mobile = $row->$arrayFile[$i]; } $this->File_manager->deletefile($tableName, 'main', $arrayFile[$i], $before_img_mobile, $arrayFile[$i]); } } else { $$arrayFile[$i] = ''; $orig_name[$i] = ''; } } for($i=0; $i<sizeof($arrayFile); $i++){ if($$arrayFile[$i] != '') { $this->db->set($arrayFile[$i], $$arrayFile[$i], TRUE); // sys_pc_img에 암호화이름 저장 $this->db->set(substr($arrayFile[$i],4), $orig_name[$i], TRUE); // pc_img에 원본이름 저장 } } } /** * @Method Name : deletefile * @Description : 파일 삭제 */ function deletefile($table_name, $path, $seq_name='', $seq, $file) { // 파일 이름 을 데이터베이스에서 찾아, filename변수에 저장합니다. $this->db->select($file); $this->db->where($seq_name, $seq); $query = $this->db->get($table_name); $row = $query->row_array(); $filename = $row[$file]; // delete_filename변수에 제거할 파일의 로컬경로를 저장합니다. $delete_filename = UPLOAD_PATH.$path.'/'.$filename; // delete_filename변수에 저장된 값이 실제로 맞는 지 확인해서, 맞다면 if문안의 구문을 실행합니다. if ( is_file($delete_filename) ) { unlink($delete_filename); // 링크를 삭제합니다. [= 로컬에 저장된 파일이 제거됨] $data[$file] = ''; $this->db->where($seq_name, $seq); $this->db->update($table_name, $data); // 디비에서 파일의 이름을 지웁니다. } } /** * @Method Name : download * @Description : 파일 다운로드 */ function download($path, $filename) { $download_filename = UPLOAD_PATH.$path.'/'.$filename; if ( is_file($download_filename) ) { // 파일 다운 // $this->load->helper('download'); $data = file_get_contents(UPLOAD_PATH.$path.'/'.$filename); //로컬 패스 $name = $filename; force_download($name, $data); } else { goMsgPageBack('파일을 등록해주세요.'); } } } ``` <br /> #### controller에서 적용 파일 업로드를 사용하려면 우선 , controller에서 모델클래스를 로드하고, 설정값을 전달해야 합니다. ##### 사용할\_클래스.php ```js class 사용할_클래스 extends CI_Controller{ /** * @brief uploadProc : upload 프로세스 */ public function uploadProc() { ... ... $this->load->model('File_manager'); // auto_load에 자동 실행 설정을 해놓았다면 선언하지 않아도 됩니다. $this->load->library('upload', $this->File_manager->upload_config('main', 'gif|jpg|jpeg|png', '10240')); // 파일을 저장소에 저장하기 위해서 upload 라이브러리를 실행 할건데, // File_manager에서 설정한 upload_config 정보를 적용해서 실행 할 것입니다. // 파일 업로드의 단위는 기본 KB이므로, 1MB는 1024KB, 10MB는 10240KB입니다. // 업로드할 파일 배열 표기 $arrayFile = array( '업로드할 파일 태그의 name1', '업로드할 파일 태그의 name2', '업로드할 파일 태그의 name3', '업로드할 파일 태그의 name4', ... , ... , ... , '업로드할 파일 태그의 name10' ); $this->File_manager->uploads($arrayFile , '파일을 저장할 테이블명'); header('Location:'.SITE_URL.'admin/main/fileupload'); } /** * @brief fileDownload : 공통 파일 다운로드 * * 이 기능을 사용하기 위해선 , view페이지에서 자바스크립트를 이용하여 * 파일 path와, 파일 name, 원본파일 name을 전달 받아야 합니다. */ public function fileDownload() { // view로부터 path와 fileName[암호화 후 fileName], 원본fileName[암호화 전 fileName]을 가져옵니다. $path = $this->input->get('path', TRUE); $fileName = $this->input->get('fileName', TRUE); $originName = $this->input->get('originName', TRUE); // 원본fileName이 있으면 원본fileName을 $downName에 저장하고 , // 원본fileName이 없으면 $downName에 암호화된 $fileName을 저장합니다. if ($originName != '') { $downName = $originName; } else { $downName = $fileName; } // 실제 파일의 경로와 이름 설정 $download_filename = UPLOAD_PATH.$path.'/'.$fileName; // 해당위치에 파일이 있다면, if ( is_file($download_filename) ) { $this->load->helper('download'); // download 헬퍼클래스를 로드합니다. $data = file_get_contents($download_filename); // 파일의 경로와 이름을 file_get_contents()함수의 파라미터로 전달하면, // file_get_contents()함수가 해당위치의 파일 정보를 읽습니다. $name = $downName; force_download(iconv('UTF-8', 'EUC-KR', $name), $data); // force_download()함수는 데이터를 다운가능하도록 하게 하기위해 서버 헤더를 생성합니다. // force_download()함수의 첫 번째 파라미터는 다운로드 될 파일의 이름을 정하는데 사용합니다. // 두 번째 파라미터는 파일을 구성할 데이터 입니다. } else { goMsgPageBack('파일이 없습니다.'); } } /** * @brief fileDelete : 공통 파일 삭제 * * 이 기능을 사용하기 위해선 , view페이지에서 자바스크립트를 이용하여 * seq와, 파일 name, 파일 path를 전달 받아야 합니다. */ public function fileDelete() { $seq = $this->input->post('seq', TRUE); $fild = $this->input->post('fild', TRUE); $path = $this->input->post('path', TRUE); $path_upper = strtoupper($path); $this->load->model('File_manager'); // File_manager모델 클래스 실행 $this->File_manager->deletefile('테이블명', $path, $seq_name, $seq, $fild); /* << 삭제할 파일의 정보를 넘긴다. >> * 테이블명 : 파일 정보가 저장된 데이터베이스 테이블 * $path : 파일이 저장된 로컬영역 경로 * $seq_name : 데이터베이스에서 파일을 찾을 조건컬럼 * $seq : 데이터베이스에서 파일을 찾을 조건값 * $fild : file 이름 */ } } ```<file_sep>/C#.NET/1. C#.NET.MD # C#.NET 1. C#.NET이란? 2. 참고 사이트 3. 개발 툴 4. 기본문법 --- ##### 1.C#.NET이란? --------------- ##### PHP의 장점 * 웹에 최적화된 언어 * 웹 개발에 필요한 수많은 로직들이 함수의 형태로 미리 제공됨 * 크로스플랫폼 * 거의 모든 데이터베이스를 지원 * 가장 많은 공개소프트웨어가 PHP로 만들어짐 --------------- ##### 2. 참고사이트 [태오 ASP](http://taeyo.net/Columns/), [Hoons .NET](http://www.hoons.net/) --------------- ##### 3. 개발 툴 Visual Studio --------------- ##### 3. 개발 툴 * 문서의 처음시작에 `<?php`를 , 마지막에 `?>`를 표기한다. ```PHP <?php ... ... ?> ``` --------------- ##### 문자열 * 문자열 출력 방법 : `echo "문자열";` * 문자열 작성시 `' '` 나 `" "`로 문자열을 감싸준다 * 입력이 끝나면 제일 마지막에 ` ; `을 붙여준다. ```PHP <?php echo "누군가가 웃기 시작했다 'hahahaha ' , 하나둘 웃음 소리가 퍼지기 시작했다."; ?> ───────────── 출력 ──────────────── 누군가가 웃기 시작했다 'hahahaha ' , 하나둘 웃음 소리가 퍼지기 시작했다. ``` * 문자열의 연결은 ``` . ```을 이용한다. ```PHP <?php $date = "2016.05.25"; echo "오늘 날짜는 : ".date." 입니다."; ?> ───────────── 출력 ──────────────── 오늘 날짜는 : 2016.05.25 입니다. ``` --------------- ##### 숫자 * 숫자 출력 방법 : `echo 숫자;` * 숫자 입력시 `' '` 나 `" "`로 감싸지 않아도 된다 ```PHP <?php echo 123456; ?> ───────────── 출력 ──────────────── 123456 ``` * 숫자의 연산도 바로 가능하다. ```PHP <?php echo 1+2; ?> ───────────── 출력 ──────────────── 3 ``` * 숫자는 `.`을 이용하여 연결할 수 없다. 문자열만 가능하다. --------------- ##### 주석 * 주석은 코드에 부가적인 설명을 쓰거나 사용하지 않는 코드를 비활성화시키기 위해서 사용한다. * `#` 을 이용하며, `#`뒤에 따라오는 내용은 해석되지 않는다. * `#` 대신에 `//`를 사용할 수도 있다. * 긴 구간을 주석으로 처리하고 싶다면 `/* */` 을 사용한다. --------------- ##### 변수 * 변수는 `문자나 숫자 같은 값을 담는 컨테이너` 이다. * 여기에 담겨진 값은 다른 값으로 바꿀 수 있다. * 변수는 마치 (사람이 쓰는 언어인) 자연어에서 대명사와 비슷한 역할을 한다. * `$`를 이용해서 변수 선언을 한다. ```PHP <?php $test = 1; ?> ``` 위의 예제에서 `$`는 변수 선언을 알리는 기호이고, `test`는 변수이름이며, `1`은 변수에 저장할 값이다. * 숫자만 들어있는 변수의 경우, 변수를 이용하여 연산을 할 수도 있다. ```PHP <?php $a = 1; $b = 2; $c = $a + $b; echo "c1 = ".$c; echo "c2 = ".($c+3); ?> ───────────── 출력 ──────────────── c1 = 3 c2 = 6 ``` --------------- ##### 가변변수 * 가변변수는 변수의 이름을 변수로 변경 할 수 있는 기능이다. ```PHP <?php $title = 'subject'; $$title = 'PHP tutorial'; echo $subject; ?> ───────────── 출력 ──────────────── PHP tutorial ``` --------------- ##### 상수 * 상수는 변하지 않는 값이다. * 상수를 정의할 때는 define을 사용한다. * define의 첫번째 인자로 상수의 이름이 사용되고, 두번째 인자로 상수의 값이 사용된다. * 상수에 저장된 값을 사용하기 위해서는 인용부호가 없이 상수의 이름을 적어주면 된다. ```PHP <?php define('TEST','777'); echo TEST; ?> ───────────── 출력 ──────────────── 777 ``` --------------- ##### 자료형 확인 * 변수에 담긴 데이터 형을 검사하는 ** 방법 1 ** * var_dump(값)를 이용하여 출력해본다. `var_dump()는 단독으로 데이터의 형식을 출력하는 명령임` ```PHP <?php var_dump("sasdsd"); // string(6) var_dump('sasdsd'); // string(6) var_dump(123123); // int(123123) var_dump(123.123); // float(123.123) ?> ───────────── 출력 ──────────────── string(6) string(6) int(123123) float(123.123) ``` * 변수에 담긴 데이터 형을 검사하고 변경하기 ** 방법 2 ** * gettype과 settype을 이용한다. * gettype(변수) = 변수의 데이터형 확인 * var_dump와 비슷하지만, var_dump는 데이터형에 대한 검사와 함께 출력까지 강제로 하기 때문에 활용도가 떨어진다. * settype(변수,'자료형') = 변수의 자료형 변경 ```PHP <?php $a = 123; echo gettype($a); settype($a,'double'); echo '<br />'; echo gettype($a); ?> ───────────── 출력 ──────────────── integer double ``` * 이와 비슷한 역할을 하는 API로는 아래와 같은 것이 있다. ```PHP << 아래의 함수들은 맞으면 true를, 틀리면 false를 출력함 >> boolean is_array(mixed $var) = var이 array인지 확인한다. boolean is_bool(mixed $var) = var이 bool인지 확인한다. boolean is_callable(mixed $var) = var이 함수처럼 호출가능한지 확인한다. boolean is_double(mixed $var) = var이 double인지 확인한다. boolean is_float(mixed $var) = var이 float인지 확인한다. boolean is_real(mixed $var) = is_float()함수의 별칭이다. boolean is_int(mixed $var) = var이 정수형인지 확인한다. boolean is_integer(mixed $var) = var이 정수형인지 확인한다. boolean is_long(mixed $var) = var이 정수형인지 확인한다. boolean is_null(mixed $var) = var이 null인지 확인한다. boolean is_numeric(mixed $var) = var에 들어있는 내용이 모두 숫자인지 확인한다. boolean is_object(mixed $var) = var이 객체인지 확인한다. boolean is_resource(mixed $var) = var이 자원인지 확인한다. boolean is_scalar(mixed $var) = var이 스칼라인지 확인한다. boolean is_string(mixed $var) = var이 문자열인지 확인한다. ``` <file_sep>/java/diskstaion_java_lec/04 OOP/Overloading3.java public class Overloading3 { public static void main(String[] args) { Superman s1 = new Superman(600,"this 생성자"); s1.showInfo(); } } class Superman { String name; //null int height; //0 int power; //0 //기본 생성자 public Superman() { name="아무개"; height=170; power=200; } //인자 생성자 public Superman(String name) { this.name=name; } public Superman(String name, int h) { this.name=name; height=h; } public Superman(int power, String name) { this(name,180,power); // 바로 아래에 있는 생성자(매개변수가 3개있는)를 참조하게된다. } public Superman(String name, int h, int p) { this.name=name; height=h; power=p; } public void showInfo() { System.out.println("===Superman Info==="); System.out.println("이름 : "+name); System.out.println("키 : "+height); System.out.println("힘 : "+power); } } class Aquaman { String name; int height; int speed; public Aquaman() { name="기본형"; height=100; speed=200; } public Aquaman(String name, int h, int s) { this.name=name; height=h; speed=s; } public Aquaman(String name) { this.name=name; } public void showInfo() { System.out.println("===Aquaman Info==="); System.out.println("이름 : "+name); System.out.println("키 : "+height); System.out.println("속도 : "+speed); } } <file_sep>/java/opentutorials/3. OOP3/README.md ## 1. 상속 ##### 상속이란? - 객체지향을 통해서 달성하고자 하는 목표 중에서 가장 중요한 것은 재활용성일 것이다. 상속은 객체지향의 재활용성을 극대화시킨 프로그래밍 기법이라고 할 수 있다. 동시에 객체지향을 복잡하게 하는 주요 원인이라고도 할 수 있다. - 상속(Inheritance)이란 물려준다는 의미다. 어떤 객체가 있을 때 그 객체의 필드(변수)와 메소드를 다른 객체가 물려 받을 수 있는 기능을 상속이라고 한다. 부모와 자식의 관계에 따른 비유를 들을 수도 있지만, 비유는 얻는 것보다 잃는 것이 많기 때문에 구체적인 코드를 통해서 상속을 알아보자. - 객체지향 수업의 [첫 번째 예제인 CalculatorDemo 예제](https://opentutorials.org/module/516/5400#Calculator.java)로 이동하자. 이 예제에서 등장하는 객체 Calculator는 더하기와 평균에 해당하는 sum과 avg 메소드를 가지고 있다. 그런데 이 객체가 가지고 있는 기능에 빼기를 추가하고 싶다. 가장 쉬운 방법은 이 객체에 빼기를 의미하는 substract를 추가해서 아래와 같이 사용하고 싶다. > 아래는 예제의 전체소스이다 > 두개의 `int`형 값을 받아 더하기와 평균값을 내주는 간단한 소스이다. ```java package org.opentutorials.javatutorials.object; class Calculator{ int left, right; public void setOprands(int left, int right){ this.left = left; this.right = right; } public void sum(){ System.out.println(this.left+this.right); } public void avg(){ System.out.println((this.left+this.right)/2); } } public class CalculatorDemo4 { public static void main(String[] args) { Calculator c1 = new Calculator(); c1.setOprands(10, 20); c1.sum(); c1.avg(); Calculator c2 = new Calculator(); c2.setOprands(20, 40); c2.sum(); c2.avg(); } } ``` > 만약 위 소스에 빼기 기능을 추가하고 싶다면?? ```java Calculator c1 = new Calculator(); c1.setOprands(10, 20); c1.sum(); c1.avg(); c1.substract(); ``` 위 소스처럼 객체에 빼기를 하는 메소드를 추가하면 되지만 다음과 같은 경우에 문제가 생긴다. 1. 객체를 자신이 만들지 않았다. 그래서 소스를 변경할 수 없다. 변경 할 수 있다고 해도 원 소스를 업데이트 하면 메소드 substarct이 사라진다. 이러한 문제가 일어나지 않게 하기 위해서는 지속적으로 코드를 관리해야 한다. 2. 객체가 다양한 곳에서 활용되고 있는데 메소드를 추가하면 다른 곳에서는 불필요한 기능이 포함될 수 있다. 이것은 자연스럽게 객체를 사용하는 입장에서 몰라도 되는 것까지 알아야 하는 문제가 된다. -> 즉, 객체지향의 부품으로서의 가치가 떨어진다고 볼수있다. > 그렇다면 기존의 객체를 그대로 유지하면서 어떤 기능을 추가하는 방법이 없을까? 이런 맥락에서 등장하는 것이 바로 **상속**이다. 즉, 기존의 객체를 수정하지 않으면서 새로운 객체가 기존의 객체를 기반으로 만들어지게 되는것이다. 이때 기존의 객체는 기능을 물려준다는 의미에서 부모 객체가 되고 새로운 객체는 기존 객체의 기능을 물려받는다는 의미에서 자식 객체가 된다. 그 관계를 반영해서 실제 코드로 클래스를 정의해보자. > 부모 클래스와 자식 클래스의 관계를 상위(super) 클래스와 하위(sub) 클래스라고 표현하기도 한다. 또한 기초 클래스(base class), 유도 클래스(derived class)라고도 부른다. 아래 코드를 `Calculator` 클래스에 추가로 입력한다. ```java class SubstractionableCalculator extends Calculator { public void substract() { System.out.println(this.left - this.right); } } ``` > `main()`메소드에는 아래와 같이 선언해주면 된다 ```java SubstractionableCalculator c1 = new SubstractionableCalculator(); c1.setOprands(10, 20); c1.sum(); c1.avg(); c1.substract(); ``` > 그럼 상속한 클래스를 다시 상속할 수 있을까? > 정답은 가능하다! 또한 상속받은 모든 내용을 상속받는다.. > 즉 손자는 부모와 조부모의 유전자를 모두 가진다고 생각하면 될 것 같다. 결론적으로 상속의 장점을 나열해보면 1. 유지보수의 편의성 2. 코드중복제거 3. 재활용성 증가! --- ## 2. 상속과 생성자 상속은 마냥 장점만 있는것이 아니다. 편리함을 위해 어떠한 기능을 수용하면 그 기능이 기존의 체계와 관계하면서 다양한 문제를 발생시킨다. 한마디로 **복잡도의 증가**라고 할 수 있다. > 생성자가 상속을 만나면서 발생한 복잡성을 알아보자 > 또한 그 맥락에서 `super`라는 키워드의 의미도 같이 다뤄보자 ```java package org.opentutorials.javatutorials.Inheritance.example4; public class ConstructorDemo { public static void main(String[] args) { ConstructorDemo c = new ConstructorDemo(); } } ``` > 기본생성자는 자동으로 생성되므로 위의 예제는 에러가 없다 > 반면 아래처럼 매개변수가있는 생성자를 정의하게되면 기본생성자가 생성되지 않으므로 에러가 발생한다. ```java package org.opentutorials.javatutorials.Inheritance.example4; public class ConstructorDemo { public ConstructorDemo(int param1) {} public static void main(String[] args) { ConstructorDemo c = new ConstructorDemo(); } } ``` > 이 문제를 해결하려면 기본생성자를 명시적으로 선언해줘야 한다 `public ConstructorDemo(){}` #### super ```java // 부모 클래스 class SubstractionableCalculator extends Calculator { public SubstractionableCalculator(int left, int right) { super(left, right); // super() 로 부모 생성자에 접근할 수 있다. // 부모클래스의 생성자라는 뜻이다! } public void substract() { System.out.println(this.left - this.right); } } ``` > 이때 초기화코드는 super 클래스보다 먼저 등장시키면 안된다. > 항상 하위 클래스의 초기화코드는 super클래스 이후에 작성해야 한다. --- ## 3. Overriding #### 창의적인 상속 <file_sep>/게시판만들기/c-cgi-mysql 게시판 만들기/cgi-bin/bak_160329/write_proc.c #include "common.h" // gcc -o write_proc.cgi write_proc.c cgic.c -I/usr/include/mysql -L/usr/local/lib/mysql -lmysqlclient /* 1. 2차원배열 char arr[4][MAX_LEN] 설명 - 배열의 크기를 미리 정해놓고 위 의 경우는 4개 문자열이 담길 2depth 부분의 크기를 지정한다. 문제점 - 사실상 2차원 배열을 쓰려고 하는 것 자체가 배열에 담긴 값을 반복문으로 처리해서 쿼리문을 실행하기 위함인데, 일단 1depth 크기부터 지정을 해야 하니 'key'에 해당하는 부분이 고정되어 버리고 (예를 들면 title, name, content 세개의 값으로 고정...여기서 date 라는 항목을 추가 하고 싶으면 배열을 또 수정해줘야 한다. 2. 포인터 배열 char *arr[] 설명 - 포인터를 배열로 담는다. 즉 2차원 배열이지만 1depth arr[] 부분이 동적으로 할당된다. 문제점 - 동적할당 부분은 배열이 아닌 포인터가 들어가기때문에 length 측정이 안된다. sizeof(arr) / sizeof(arr[0] 로 측정시 선언한 포인터의 데이터형의 크기만 측정된다.... 즉 char 포인터 배열에 4개의 문자열이 들어가 있다면 원하는 결과값은 4 지만 실제로는 char 형 포인터 4개이므로 8이 찍혀버린다. _msize 라는 함수가 있지만 표준함수가 아니고, 리눅스에서 사용할 또다른 함수도 완전하지 안하고 결과값이 다르게 찍힐때가 많아서 사실상 이 방법은 쓸 수 없다 */ int cgiMain(void) { printf("%s%c%c\n","Content-Type:text/html;charset=utf-8;",13,10); // 입력값 얻어냄 cgiFormString("seq", seq, MAX_LEN); // GET 전송 ( 수정할때 사용할 seq ) cgiFormString("title", title, MAX_LEN); cgiFormString("name", name, MAX_LEN); cgiFormString("content", content, MAX_LEN); mysqlDbConn(); //printf("%s / %s / %s / %s", seq, title, name, content); if(strcheck(seq)){ //char *arr[] = {update_title, update_name, update_content, update_seq}; updateData(title, name, content, seq); strcpy(alertMsg, "글 수정이 완료되었습니다."); }else{ insertData(title, name, content); strcpy(alertMsg, "글 등록이 완료되었습니다."); } printf("<!doctype html>\n"); printf("<html lang=\"ko\">\n"); printf("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n"); printf("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n"); printf("<head> \n"); printf(" <title>CGI - board</title>\n"); //printf(" <link href=\"https://maxcdn.bootstrapcdn.com/bootswatch/3.3.6/paper/bootstrap.min.css\" rel=\"stylesheet\" > \n"); printf(" <link href=\"https://maxcdn.bootstrapcdn.com/bootswatch/3.3.6/slate/bootstrap.min.css\" rel=\"stylesheet\" > \n"); printf(" <script src=\"https://code.jquery.com/jquery-1.12.1.min.js\"></script> \n"); printf(" <script > \n"); printf(" alert('%s') \n", alertMsg); printf(" window.location.href='list.cgi'; \n"); printf(" </script> \n"); printf("<head>\n"); printf("<body>\n"); printf("</body>\n</html>"); mysql_close(connection); }<file_sep>/java/servlet_container_ebook/ch03/README.md ## 3. 서블릿의 이해 <file_sep>/java/toby_spring/Vol.2/3장/README.md ## 3장 스프링 웹 기술과 스프링 MVC - 스프링 웹 계층 설계와 기술의 선정에 관한 기본원칙 - 스프링 웹 기술의 다양한 전략 - ㄴ<file_sep>/java/god_of_java/Vol.1/14. 다 배운 것 같지만, 예외라는 중요한 것이 있어요/ExceptionSample2.java public class ExceptionSample2 { public static void main(String[] args) { ExceptionSample2 sample = new ExceptionSample2(); sample.multiCatch(); } public void arrayOutOfBounds() { int[] intArray = null; try{ //intArray=new int[5]; System.out.println(intArray[5]); }catch(Exception e){ System.out.println(intArray.length); } System.out.println("this code shoul run."); } public void multiCatch() { int[] intArray = new int[5]; try { System.out.println(intArray[5]); } /*catch (NullPointerException e) { System.out.println("NullPointerException occured"); }*/ catch (Exception e) { System.out.println(intArray.length); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("ArrayIndexOutOfBoundsException occured"); } } } <file_sep>/java/god_of_java/Vol.1/04. 정보를 어디에 넣고 싶은데/README.md ```java public class VariableTypes { int instanceVariable; static int classVariable; public void method(int parameter) { int localVariable; } } ``` ### 1.자바의변수 ##### 1) 지역변수 ( local ) - 중괄호 내에서 선언된 변수 - 지역 변수를 선언한 중괄호 내에서만 유효하다. #### 2) 매개변수 ( parameters ) - 메소드나 생성자에 넘겨주는 변수 - 메소드가 호출될 때 생명이 시작되고, 메소드가 끝나면 소멸된다(정확히 호출될때 시작하지는 않지만 일단은 이정도로기억해두자) #### 3) 인스턴스 변수 ( instance ) - 메소드 밖에 , 클래스 안에 선언된 변수, 앞에는 static이라는 예약어가 없어야 한다. - 객체가 생성될 때 생명이 시작되고, 그 객체를 참조하고 있는 다른 객체가 없으면 소멸된다. #### 4) 클래스 변수 ( class ) - 인스턴스 변수처럼 메소드 밖에, 클래스 안에 선언된 변수 중에서 타입 선언앞에 static 이라는 예약어가 있는 변수 - 클래스가 생성될 때 생명이 시작되고 , 자바 프로그램이 끝날 때 소멸된다. > ##### 생각해보기 ##### > 아래 두개의 지역변수는 서로 같은 변수일까? ```java public class VariableTypes { int instanceVariable; static int classVariable; public void method(int parameter) { int localVariable; } public void anothermethod(int parameter) { int localVariable; } } ``` > ##### 생각해보기 ##### > 아래 1번과 2번의 의 지역변수는 서로 같은 변수일까? > 아래는 컴파일 에러가 난다 그이유는 글 작성시점에선 알고있지만 나중에 봤을때 생각이 안난다면 p.87 참조 ```java public class VariableTypes { int instanceVariable; static int classVariable; public void method(int parameter) { int localVariable; } public void anothermethod(int parameter) { if(true){ int localVariable; //1 if(true){ int localVariable;//2 } } //3 if(true){ int localVariable; } } } ``` ### 2. 자바의 자료형 #### 1) 기본자료형 (Primitive Data Type) - 추가로 만들 수 없다. - 이미 정해져 있다 - int a = 10; - new 없이 바로 초기화가 가능한것을 기본자료형이라 한다. * 기본자료형의 종류 - ㄱ)정수형 : byte, short, int, long, char - ㄴ)소수형 : float, double - ㄷ)기타 : boolean ㄱ) 정수형 타입 | 최소 | 최대 ------------ | ------------- | ------------- byte | -128 | 127 short | -32,768 | 32,767 int | -2,147,483,648 | 2,147,483,647 long | -9,223,372,036,854,775,808 | 9,223,372,036,854,775,807 char | 0('\u0000') | 65,535('\uffff') 8비트와 byte타입 > 아래 표를 보고 C를 생각해보면 생각날듯...(포인터) 2 ^7 | 2^6 | 2^5 | 2^4 | 2^3 | 2^2 | 2^1 | 2^0 --- | --- | --- | --- | --- | --- | --- | --- 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 > 위 테이블에서 모든공간이 1로 채워지면 255이다. > 근데 왜 byte의 범위는 127로 표기할까? 계산식에서 정확히 반토막이다. > 자바의 기본 자료형에 포함된 숫자들은 모두 부호가 있는 **signed**타입들이다. > 그 방법들을 선배 엔지니어들이 고민에 고민을 하다가 "맨앞에 있는 값이 0이면 양수, 1이면 음수로 정하자" > 라고 결정했다. 다시말하면, 가장 왼쪽의 공간은 2의7승이 아니라 그냥 음수와 양수를 구분하기 위한 공간이다. > 그래서!! > 위 계산식을 다시 해보면 127이 되는것이다. > 여기서 또 의문! > 왜 음수는 -128까지일까? 이론상 모든 byte의 공간을 1로 채우면 -127이 되어야 정상이다... > 그이유는 **하나의 값이라도 더 제공할 수 있도록 엔지니어들이 고민했기 때문이다** > 저 자세한 사항은 p.95 참조 및 부록의 비트연산자 참조 ```java public class PrimitiveTypes { public void checkByte() { byte byteMin = -128l byte byteMax = 127; System.out.println("byteMin="byteMin); System.out.println("byteMax="byteMax); byteMin--; byteMax++; System.out.println("byteMin--="byteMin); System.out.println("byteMax++="byteMax); } public void checkOtherTypes() { short shortMax=32767; int intMax=2147483647; long longMax=9223372036854775807l; // 맨 마지막은 소문자L 이다. long 타입을 명시하기 위해 사용 } public static void main(String[] args) { PrimitiveTypes types=new PrimitiveTypes(); types.checkByte(); } } ``` > 위 내용을 출력해보면 최소값에서 1을 빼면 최대값이 출력되고, > 최대값에서 1을 더하면 최소값이 된다. ㄴ) 소수형 - float과 double은 모두 소수점 값을 처리하기 위해서 사용된다 - float는 32비트, double은 64비트 - 간단한 계산에서는 사용해도 무방하지만 중요한 돈계산등에는 이 타입들을 사용하지 않는다. - 32비트와 64비트를 넘어서면 값의 정확성을 보장하지 못하기 때문! - 그래서 보통 자바에서는 돈계산과 같이 정확한 계산이 요구될 경우 `java.math.BigDecimal - 이라는 클래스를 사용하며 이는 Vol.2 에 자세히 설명되어있다고 한다~ - 일반적으로 double을 많이 사용한다 ㄷ) 기타 * 기본 자료형의 기본 값은 뭘까? * 자바의 모든 자료형은 값을 지정하지 않으면 기본값을 사용한다 * 단!! 지역변수는 기본값이 적용되지 않는다. * 즉 메소드 안에서 지정한 변수에 값을 지정하지 않고 사용하려고 하면 컴파일에러! * 인스턴스변수, 클래스변수,매개변수는 값을 지정하지 않아도 컴파일이 되기는 하지만 이는 안좋은 습관이다 - char와 boolean은 어떻게 쓸까? ```java public void checkChar() { char charMin = '\u0000'; char charMax = '\uffff'; System.out.println("charMin=["+ charMin+"]"); System.out.println("charMax=["+ charMax+"]"); } ``` ``` Result : charMin=[ ] charMax=[?] ``` > 위 내용처럼 min의 경우 아무것도 없는것처럼 보이나 실제로는 공백이 출력되어있는것이다. - 자세한 사항은 p.102참조 - 자바의 정수중 유일하게 부호가 없는 **unsigned**값이다. - boolean 값은 생략~ #### 2) 참조자료형 (Reference Data Type) - 마음대로 만들 수 있다. ex) Calculator, Car 같은 클래스들 - Calculator calc = new Calculator(); - new를 사용해서 초기화하는 것을 참조자료형 - String의 경우는 참조자료형 ` 일반적으로 아래와 같이 사용하여 기본자료형이라고 생각할 수 있지만.!! ``` String str1 = "book1"; ``` ` 다음과 같이 정의해도 상관없다. ``` String str2 = new String("book2"); ``` <file_sep>/게시판만들기/struts1 게시판 만들기/WEB-INF/classes/my/bbs2/BbsManager.java package my.bbs2; import java.util.*; import javax.servlet.http.*; import my.bbs2.BbsDAO; import my.bbs2.BbsDTO; import my.bbs2.BbsManager; import my.bbs2.ReplyDTO; import my.bbs2.controller.form.BbsEditForm; import com.oreilly.servlet.*; import java.sql.*; public class BbsManager { static private BbsManager instance = new BbsManager(); private BbsManager(){ } public static BbsManager getInstance(){ return instance; } public int writeOk(MultipartRequest mr) throws SQLException{ BbsDAO dao = new BbsDAO(); int n = dao.writeOk(mr); return n; } public ArrayList<BbsDTO> listAll(int cpage, int pageSize) throws SQLException{ BbsDAO dao = new BbsDAO(); ArrayList<BbsDTO> arr=dao.listAll(cpage,pageSize); return arr; } public int getTotalGulCount() throws SQLException{ BbsDAO dao = new BbsDAO(); return dao.getTotalGulCount(); } public BbsDTO viewContent(String idx) throws SQLException{ BbsDAO dao = new BbsDAO(); return dao.viewContent(idx); } public boolean getReadnum(String idx) throws SQLException{ BbsDAO dao = new BbsDAO(); return dao.getReadnum(idx); } public int deleteOk(String idx, String pwd) throws SQLException{ return new BbsDAO().deleteOk(idx, pwd); } public BbsDTO edit(String idx) throws SQLException{ return new BbsDAO().edit(idx); } public int editOk(BbsEditForm form) throws SQLException{ return new BbsDAO().editOk(form); } public int rewriteOk(MultipartRequest mr) throws SQLException{ return new BbsDAO().rewriteOk(mr); } public int replySave(String idx, String writer, String content, String pwd) throws SQLException{ return new BbsDAO().replySave(idx,writer,content, pwd); } public ArrayList<ReplyDTO> replyList(String idx) throws SQLException{ return new BbsDAO().replyList(idx); } public int replyDelPwd(String no, String pwd) throws SQLException{ return new BbsDAO().replyDelPwd(no,pwd); } } <file_sep>/게시판만들기/c-cgi-mysql 게시판 만들기/cgi-bin/bak_160324/write.c #include <stdio.h> #include "cgic.h" #include <string.h> #include <stdlib.h> #include <mysql.h> #include "common.h" // gcc -o write.cgi write.c cgic.c -I/usr/include/mysql -L/usr/local/lib/mysql -lmysqlclient int cgiMain(void) { /* 헤더 속성 최상단에 위치 - 헤더위에 print 문등이 있으면 500 error 발생 */ printf("%s%c%c\n","Content-Type:text/html;charset=utf-8",13,10); char seq[MAX_LEN]; char name[MAX_LEN], title[MAX_LEN], content[MAX_LEN]; char update_seq[MAX_LEN], update_name[MAX_LEN], update_title[MAX_LEN], update_content[MAX_LEN]; char email[MAX_LEN], homepage[MAX_LEN], mode[MAX_LEN]; char alertMsg[MAX_LEN]; char query[MAX_LEN]; // 입력값 얻어냄 cgiFormString("seq", seq, MAX_LEN); // GET 전송 ( 수정할때 사용할 seq ) MYSQL *connection=NULL, conn; MYSQL_RES *res; // (SELECT, SHOW, DESCRIBE, EXPLAIN)등의 쿼리를 내렸을때 그 결과를 다루기 위해 사용되는 구조체이다. MYSQL_ROW row; // 데이터의 하나의 row 값을 가리킨다. 만약 row 값이 없다면 null 을 가르키게 된다. // mysql 접속정보 char *server = "dev-smc.com"; char *user = "root"; char *pwd = "<PASSWORD>"; char *database = "main"; int i; // mysql 한글문자열 깨짐 방지 mysql_init(&conn); mysql_options(&conn, MYSQL_SET_CHARSET_NAME, "utf8"); mysql_options(&conn, MYSQL_INIT_COMMAND, "SET NAMES utf8"); connection = mysql_real_connect(&conn, server, user, pwd, database, 3306, (char *)NULL, 0); if(connection == NULL){ fprintf(stderr, "%s\n", mysql_error(&conn)); exit(1); } // modify if(strcheck(seq)){ //printf("MODIFY \n"); //exit(1); sprintf(query, "SELECT * FROM bbsc WHERE seq='%s'", seq); if(mysql_query(connection, query) ){ fprintf(stderr, "%s\n", mysql_error(&conn)); exit(0); } res = mysql_store_result(connection); row = mysql_fetch_row(res); printf("<!doctype html>\n"); printf("<html lang=\"ko\">\n"); printf("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n"); printf("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n"); printf("<head> \n"); printf(" <title>CGI - board</title>\n"); printf(" <link href=\"https://maxcdn.bootstrapcdn.com/bootswatch/3.3.6/paper/bootstrap.min.css\" rel=\"stylesheet\" > \n"); printf(" <script src=\"https://code.jquery.com/jquery-1.12.1.min.js\"></script> \n"); printf(" <script > \n"); printf(" //alert('123') \n"); printf(" function goList(){ \n"); printf(" location.href='list.cgi'; \n"); printf(" }; \n"); printf(" function goWrite(){ \n"); printf(" var form = document.update_frm \n"); printf(" form.submit(); \n"); printf(" }; \n"); printf(" </script> \n"); printf("<head>\n"); printf("<body>\n"); printf("<div class='container'>\n"); printf(" <div class='row'>\n"); printf(" <h2>CGI - board</h2>\n"); printf(" <form method='post' name='update_frm' id='update_frm' action='write.cgi'> \n"); printf(" <input type='hidden' name='update_seq' value='%s'>\n", seq); printf(" <table class='table'>\n"); printf(" <tr>"); printf(" <th class='active col-xs-1'>제목</th>\n"); printf(" <td><input name='update_title' id='update_title' class='form-control' value='%s'></td>\n", row[1]); printf(" </tr>\n"); printf(" <tr>\n"); printf(" <th class='active col-xs-1'>이름</th>\n"); printf(" <td><input name='update_name' id='update_name' class='form-control' value='%s'></td>\n", row[2]); printf(" </tr>\n"); printf(" <tr>\n"); printf(" <th class='active col-xs-1'>본문</th>\n"); printf(" <td><textarea name='update_content' id='update_content' class='form-control' cols='60' rows='10' >%s</textarea></td>\n", row[3]); printf(" </tr>\n"); printf(" </table>\n"); printf(" </form>\n"); printf(" <button class='btn btn-default' onclick='goWrite();' >작성</button> \n"); printf(" <button class='btn btn-default' onclick='goList();' >리스트</button> \n"); printf(" </div>\n"); printf("</div>\n"); printf("</body>\n</html>"); } // insert else{ cgiFormString("title", title, MAX_LEN); cgiFormString("name", name, MAX_LEN); cgiFormString("content", content, MAX_LEN); cgiFormString("update_seq", update_seq, MAX_LEN); cgiFormString("update_title", update_title, MAX_LEN); cgiFormString("update_name", update_name, MAX_LEN); cgiFormString("update_content", update_content, MAX_LEN); printf("<!doctype html>\n"); printf("<html lang=\"ko\">\n"); printf("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n"); printf("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n"); printf("<head> \n"); printf(" <title>CGI - board</title>\n"); printf(" <link href=\"https://maxcdn.bootstrapcdn.com/bootswatch/3.3.6/paper/bootstrap.min.css\" rel=\"stylesheet\" > \n"); printf(" <script src=\"https://code.jquery.com/jquery-1.12.1.min.js\"></script> \n"); printf(" <script > \n"); printf(" function goList(){ \n"); printf(" location.href='list.cgi'; \n"); printf(" }; \n"); printf(" </script> \n"); printf("<head>\n"); printf("<body>\n"); printf("<div class='container'>\n"); printf(" <div class='row'>\n"); printf(" <h2>CGI - board</h2>\n"); printf(" <div class='panel panel-default'>"); printf(" <div class='panel-heading'>입력이 완료되었습니다.</div>"); printf(" <div class='panel-body'>"); printf(" 리스트 페이지로 이동하려면 확인버튼을 누르세요. \n"); printf(" </div>"); printf(" </div>"); printf(" <table width='600' class='table table-bordered'>\n"); if(strcheck(update_title)){ printf(" <tr><th class='active col-xs-1'>제목</th> <td>%s</td></tr>\n", update_title); printf(" <tr><th class='active col-xs-1'>작성자</th> <td>%s</td></tr>\n", update_name); printf(" <tr><th class='active col-xs-1'>내용</th> <td>%s</td></tr>\n", update_content); sprintf(query, "UPDATE bbsc SET title='%s', name='%s', content='%s' WHERE seq='%s'", update_title, update_name, update_content, update_seq); //printf("%s", query); }else{ printf(" <tr><th class='active col-xs-1'>제목</th> <td>%s</td></tr>\n", title); printf(" <tr><th class='active col-xs-1'>작성자</th> <td>%s</td></tr>\n", name); printf(" <tr><th class='active col-xs-1'>내용</th> <td>%s</td></tr>\n", content); sprintf(query, "INSERT INTO bbsc (title, name, content) values('%s', '%s', '%s')", title, name, content); } printf(" </table>\n"); printf(" <button class='btn btn-default' onclick='goList();' >확인</button> \n"); printf(" </div>\n"); printf("</div>\n"); printf("</body>\n</html>"); /* 로그확인용 printf("title 타입 확인 : %s \n", title); printf("update_title 타입 확인 : %s \n", update_title); printf("title : %s \n name : %s \n content : %s \n", title, name, content); */ if(!mysql_query(connection, query) ){ //printf("진입\n"); fprintf(stderr, "%s\n", mysql_error(&conn)); exit(0); } exit(1); } mysql_close(connection); } <file_sep>/guide/개발 라이브러리 가이드/CI/08 . bs_message_helper.md <style>.blue {color:#2844de;font-size:18px;}.red {color:#dd4814;font-size:18px;}.ex {color:gray;}p.me{padding:10px 8px 10px;line-height:20px;border:1px solid black;}.center{text-align:center;}</style> ## 08 . bs\_message\_helper bs_message_helper 클래스는 아래의 기능을 구현하는 자바스크립트를 가진 함수들이 모인 클래스입니다. ──────────────────────순서────────────────────── 1. **alert 메세지** 츨력 2. **페이지 이동** 3. <b class="red">alert 출력</b> + **페이지 이동** 출력 4. **이전 페이지** 이동 5. <b class="red">alert 출력</b>후 **이전페이지** 이동 6. **페이지 닫기** 7. <b class="red">alert 출력</b>후 **페이지 닫기** 8. **부모페이지 reload, 현재창 close** 9. <b class="red">alert 출력</b> 후 **부모페이지 reload, 현재창 close** ──────────────────────────────────────────────── ```js // alert 메세지 츨력 function msg($msg) { echo (" <meta charset='utf-8'> <script type='text/javascript'> window.alert('".$msg."'); </script> "); } // 페이지 이동 function goPage($url) { echo (" <script type='text/javascript'> location.replace('".$url."'); </script> "); exit; } // 페이지 이동 + alert 메세지 출력 function goMsgPage($msg, $url) { echo (" <meta charset='utf-8'> <script type='text/javascript'> window.alert('".$msg."'); location.replace('".$url."'); </script> "); exit; } // 이전 페이지 이동 function goPageBack() { echo (" <script type='text/javascript'> history.go(-1); </script> "); exit; } // 메시지 출력후 이전페이지 이동 function goMsgPageBack($msg) { echo (" <meta charset='utf-8'> <script type='text/javascript'> window.alert('".$msg."'); history.go(-1); </script> "); exit; } // 페이지 닫기 function PageClose() { echo (" <meta charset='utf-8'> <script type='text/javascript'> self.close(); </script> "); } // 메시지 출력후 페이지 닫기 function goMsgPageClose($msg) { echo (" <meta charset='utf-8'> <script type='text/javascript'> window.alert('".$msg."'); self.close(); </script> "); exit; } // 부모페이지 reload, 현재창 close function parentReloadcurrentClosePopup() { echo (" <meta charset='utf-8'> <script type='text/javascript'> opener.location.reload(); window.close(); </script> "); exit; } // alert 실행후 부모페이지 reload, 현재창 close function reloadPopupMsg($msg) { echo (" <meta charset='utf-8'> <script type='text/javascript'> window.alert('".$msg."'); opener.location.reload(); window.close(); </script> "); exit; } ```<file_sep>/php/06. 함수.md ## 함수 ** << 목록 >> ** 1 . 함수 2 . 함수의 종류 3 . 함수의 정의와 호출 4 . 입력과 출력 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;return (출력) 5 . 인자 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;인자 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;복수의 인자 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;인자의 기본값 --------------- ##### 함수 * 함수란 하나의 로직을 재실행 할 수 있도록 하는 것으로 코드의 `재사용성을 높여준다`. * 사실 함수 이전에 우리가 배웠던 것들로도 프로그램을 만들 수 있는데 , 그런 점에서 함수 이전의 내용들은 프로그래밍의 실체라고 할 수도 있다. * 그 이후부터 등장하는 `함수`나 `객체지향`과 같은 개념들은 그것 자체가 프로그래밍의 연산이나 논리에 직접적으로 관여하는 것이라기 보다는 <font color='brown'><b>방대한 양의 코드를 줄여주고, 유지보수를 쉽게 하고, 버그가 발생할 여지를 줄여주는 것들</b></font>이라고 할 수 있다. --------------- ##### 함수의 종류 * 함수의 형식 ```php <?php function 함수명( [인자...[,인자]]) { 코드 return 반환값; } ?> ``` --------------- ##### 함수의 정의와 호출 * 함수는 키워드 `function` 뒤에 `함수의 이름`이 오고, `괄호`가 따라온다. * **괄호 안**에는 **함수에 대한 입력 값을 담을** `변수의 이름`이 오고, **복수의 입력 값을 정의 할 때**는 `변수와 변수 사이에 콤마`로 구분한다. * **중괄호**에는 **함수가 호출 되었을 때** `실행될 코드`가 온다. ```php <?php function numbering() { $i = 0; while($i<10){ echo $i; $i += 1; } } numbering(); // 함수 호출 ?> ───────────── 출력 ──────────────── 0123456789 ``` --------------- ##### 입력과 출력 * 함수의 핵심은 입력과 출력이다. 입력된 값을 연산해서 출력하는 것이 함수의 기본적인 역할이다. * 다음은 함수에서 입력과 출력의 역할을 하는 구문들에 대한 설명이다. <br> ###### return (출력) 함수 내에서 사용한 return은 return 뒤에 따라오는 값을 함수의 결과로 반환한다. 동시에 함수를 종료시킨다. ```php <?php function get_member1() { return 'abc'; } function get_member2() { return 'hyun'; } echo get_member1(); echo ' , '; echo get_member2(); ?> ───────────── 출력 ──────────────── abc , hyun ``` get_member1()과 get_member2()를 출력(echo)한 결과가 각각 abc와 hyun인 이유는 함수에서 return이 등장하면 return뒤의 값이 반환되기 때문이다. return은 결과를 반환하는 것 외에 함수를 중지시키는 역할도 한다. 다음 예제를 보자 ```php <?php function get_member(){ return 'abc'; return 'hyun'; return 'hahaha'; } echo get_member(); ?> ───────────── 출력 ──────────────── abc ``` kjh와 hahaha는 출력되지 않았다. 왜냐하면 return 'abc'를 실행한 후에 함수가 종료되었기 때문에 이후의 문장들은 실행되지 않은 것이다. `함수에서 return이 등장한 이후에는 함수 내의 어떠한 코드도 실행되지 않는다.` --------------- ##### 인자 ###### 인자 * 인자(argument)는 함수로 유입되는 값을 의미하는데, 어떤 값을 인자로 전달하느냐에 따라서 함수가 반환하는 값이나 메소드의 동작 방법을 다르게 할 수있다. ```php <?php function get_argument($arg){ return $arg; } print get_argument(1).'<BR>'; print get_argument(2); ?> ───────────── 출력 ──────────────── 1 2 ``` $arg에 의해서 1이 함수에 전달된다. 이때 $arg는 get_argument함수 내부에서만 사용할 수 있다. <br> ###### 복수의 인자 인자를 여러개 입력할 수도 있다. ```php <?php function get_argument($arg1,$arg2){ return $arg1 + $arg2; } print get_argument(10,20).'<BR>'; print get_argument(20,30); ?> ───────────── 출력 ──────────────── 30 50 ``` <br> 만약 두개의 인자를 받는 함수인데 인자를 하나만 보냈다면 `Warning: Missing argument 2 for get_argument(), ...`라는 경고메시지가 나타난다 ```php <?php function get_argument($arg1,$arg2){ return $arg1 + $arg2; } print get_argument(10,20).'<BR>'; print get_argument(20); ?> ───────────── 출력 ──────────────── 30 Warning: Missing argument 2 for get_argument(), called in C:\Apache24\htdocs\def1.php on line 7 and defined in C:\Apache24\htdocs\def1.php on line 2 Notice: Undefined variable: arg2 in C:\Apache24\htdocs\def1.php on line 3 20 ``` <br> ###### 인자의 기본값 만약 함수를 호출 할 때 기본값을 사용하고 싶다면 어떻게 해야할까?? 다음 예제를 보자. ```php <?php function get_argument($arg1=100){ return $arg1; } echo get_argument(1).'<br>'; echo get_argument(); ?> ───────────── 출력 ──────────────── 1 100 ``` 함수 선언문에서 보이는 $arg=100은 인자 $arg의 기본 값으로 100을 사용하겠다는 의미이다. 이렇게 해주면 인자의 값이 설정되지 않았을 때 $arg의 값은 100이 된다.<file_sep>/java/god_of_java/Vol.2/05. 자바랭 다음으로 많이 쓰는 애들은 컬렉션-Part1(List)/README.md ## 5장. 자바랭 다음으로 많이 쓰는 애들은 컬렉션-Part1(List) 자바에서 컬렉션은 목록성 데이터를 처리하는 자료구조를 통칭 #### 자료구조란? - Data Structure - 하나의 데이터가 아닌 여러 데이터를 담을 때 사용한다. - 배열이 가장 기본적인 자료구조다. #### 자바에서 데이터를 담는 자료구조는 크게 다음과 같이 분류할 수 있다. - 순서가 있는 목록인 List형 - 순서가 중요하지 않은 목록인 Set형 - 먼저 들어온 것이 먼저 나가는 Queue형 - 키-값(key-value)으로 저장되는 Map형 > 자바에서는 List와 Set, Queue는 Collection이라는 인터페이스를 구현하고 있다. 이 Collection 인터페이스는 java.util 패키지에 선언되어 있으며, 여러 개의 객체를 하나의 개체에 담아 처리할 때 공통적으로 사용되는 여러 메소드들을 선언해 놓았다. 위 목록에서 유일하게 Map만이 Collection과 관련 없는 별도의 인터페이스로 선언되어 있다. > List와 Set, Queue의 기본이 되는 Collection 인터페이스는 다음과 같이 선언되어 있다. ```java public interface Collection<E> extends Iterable<E> ``` > `Iterable<E>` 라는 인터페이스를 확장~extends~ 했다는 점. > 이 `Iterable<E>`인터페이스에 선언되어 있는 메소드는 단지 `iterator()` 하나다. > 또한 이 메소드는 `Iterator`라는 인터페이스를 리턴한다. 결론적으로, Collection 인터페이스가 Iterable 인터페이스를 확장했다는 의미는, Iterator 인터페이스를 사용하여 데이터를 순차적으로 가져 올 수 있다는 의미다. --- ### List 인터페이스와 그 동생들 배열과 비슷한 List에 대해서 알아보자. - List 인터페이스는 방금 배운 Collection 인터페이스를 확장하였다. - 따라서, 추가된 메소드를 제외하고는 Collection에 선언된 메소드와 큰 차이는 없다. - Collection을 확장한 다른 인터페이스와 List 인터페이스의 가장 큰 차이점은 배열처럼 ++**순서**++가 있다는 것이다. List 인터페이스를 구현한 클래스들은 매우 많지만 그중 java.util 패키지에서는 ArrayList, Vector, Stack, LinkedList를 많이 사용한다. 이 중에서 ArrayList와 Vector 클래스의 사용법은 거의 동일하고 기능도 거의 비슷하다. 이 두 클래스는 "크기 확장이 가능한 배열"이라고 생각하면 된다. ArrayList의 객체는 여러 명이 달려들어 값을 변경하려고 하면 문제가 발생할 수 있고, Vector는 그렇지 않다 즉, ArrayList 는Thread safe하지 않고, Vector는 Thread safe하다고 이야기 한다. Stack 클래스는 Vector 클래스를 확장하여 만들었다. 이 클래스를 만든 가장 큰 이유는 LIFO를 지원하기 위함이다 LIFO는 Last In First Out의 약자로, 가장 마지막에 추가한 값을 가장 처음 빼내는 것이다. > 프로그래밍 언어에서 "스택"이라는 의미는 보통 메소드가 호출된 순서를 기억하는 장소를 말한다. LinkedList라는 클래스는 List에도 속하지만, Queue에도 속한다. > 참고로 Vector보다 ArraList를 많이 선호한다. --- ### ArrayList에 대해서 파헤쳐보자 > 지금 배우는 컬렉션, 나중에 배울 쓰레드, IO, 네트워크 등의 관련 클래스를 사용할 때에는 한번 정도 그 클래스의 상속 관계를 살펴보자 왜냐하면 그 클래스의 API에 있는 메소드나 상수만 사용할 수 있는 것이 아니고, 부모 클래스에 선언되어 있는 메소드도 사용할 수 있기 때문이다. 우선은 ArrayList 클래스의 상속 관계를 살펴보자. ```java java.lang.Object java.util.AbstractCollection<E> java.util.AbstractList<E> java.util.ArrayList<E> ``` Object를 제외한 나머지 부모 클래스들의 이름 앞에는 `Abstract` 가 붙어있다. 즉, 이 클래스들은 abstract 클래스다. > abstract 클래스는 일반클래스와 비슷하지만, 몇몇 메소드는 자식에서 구현하라고 abstract로 선언한 메소드들이 있는 클래스 따라서, `AbstractCollection`은 `Collection` 인터페이스 중 일부 공통적인 메소드를 구현해 놓은 것이며, `AbstractList`는 `List` 인터페이스 중 일부 공통적인 메소드를 구현해 놓은 것이라고 기억하고 있으면 된다. > 확장한 클래스 외에 구현한 모든 인터페이스들은 다음과 같다. ``` All Implemented Interfaces: Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess ``` > 이와 같은 인터페이스들을 ArrayList가 구현했다는 것은 각 인터페이스에서 선언한 기능을 ArrayList에서 사용할 수 있다는 말이다. ### ArrayList의 생성자는 3개다 - 앞서 ArrayList는 "크게 확장이 가능한 배열" 이라고 설명했다. - 따라서, 배열처럼 사용하지만 대괄호는 사용하지 않고, 메소드를 통해서 객체를 넣고, 빼고, 조회한다. > ArrayList 의 생성자들 - `ArrayList()` : 객체를 저장할 공간이 10개인 ArrayList를 만든다. - `ArrayList(Collection<? extends E> c)` : 매개 변수로 넘어온 컬렉션 객체가 저장되어 있는 ArrayList를 만든다. - `ArrayList(int initialCapacity)` : 매개 변수로 넘어온 initialCapacity 개수만큼의 저장 공간을 갖는 ArrayList를 만든다. 역시 설명만으로는 무리다. 예제코드를 보자 ```java import java.util.ArrayList; public class ListSample { public static void main(String[] args) { ListSample sample=new ListSample(); sample.checkArrayList1(); } public void checkArrayList1(){ ArrayList list1=new ArrayList(); } } ``` > 이렇게 list1 객체를 생성하면, 이 ArrayList에는 어떤 객체도 넣을 수 있다. > 그리고 데이터를 넣을 때에는 add()라는 메소드를 사용한다. 이를테면 다음처럼~ ```java public void checkArrayList1(){} list1.add(new Object()); list1.add("ArrayListSample"); list1.add(new Double(1)); } ``` 그런데 보통 ArrayList는 이렇게 사용하지 않는다. 대부분 이렇게 다른 종류의 객체를 하나의 배열에 넣지 않고, 한가지 종류의 객체만 저장한다. > 여러 종류를 하나의 객체에 담을 때에는 되도록이면 `DTO`라는 객체를 하나 만들어서 담는 것이 좋다. 그래서 , 컬렉션 관련 클래스의 객체들을 선언할 때에는 앞 장에서 배운 제네릭을 사용하여 선언하는 것을 권장한다. 예를 들어 String 만 담는 ArrayList를 생성할때에는 다음과 같이 사용하면 된다. ```java ArrayList<String> list1=new ArrayList<String>(); ``` > 참고로 JDK7부터는 생성자를 호출하는 부분(new 뒤에)에 따로 타입을 적지 않고 `<>`로만 사용해도 되지만 JDK6이하 버전을 위해 > 되도록 위와 같이 사용하자 > 각설하고, 이처럼 list1을 선언해 놓으면, list1에는 String타입의 객체만 넣을 수 있다. 이제 위에서 만들어본 `checkArrayList1`메소드를 제네릭으로 선언한 후 컴파일을 해보자 > 그럼 당연하게도 컴파일에러가 뜬다 > 이렇게 제네릭을 사용하면 컴파일 시점에 타입을 잘못 지정한 부분을 걸러낼 수가 있다. - ArrayList 객체를 선언할 때 매개변수를 넣지 않으면, 기본 초기 크기는 10이다. - 따라서 10개 이상의 데이터가 들어가면 크기를 늘이는 작업이 ArrayList내부에서 자동으로 수행된다. - 이러한 작업은 애플리케이션 성능에 영향을 주니 만약 저장되는 데이터의 크기가 어느정도 예측가능하다면 - 다음과 같이 예측한 초기 크기를 지정할 것을 권장한다. ```java ArrayList<String> list2=new ArrayList<String>(100); ``` ### ArrayList에 데이터를 담아보자 생성자에 대해서 알아봤으니 ArrayList에 데이터를 담는 메소드를 살펴보자. - add() : 하나의 데이터를 담을때 사용 - addAll() : Collection을 구현한 객체를 한꺼번에 담을 때에 사용 > 반복해서 설명하지만 ArrayList는 확장된 배열 타입이기 때문에 **배열처럼 처음 순서가 매우중요하다** ㄱ) add(E e) - add()메소드에 매개변수하나만을 넘겨서 데이터를 저장하면 배열의 가장 끝에 데이터를 담는다. - 이 메소드를 사용하여 데이터를 추가했을 때 리턴되는 boolean 값은 제대로 추가가 되었는지 여부를 말한다. ㄴ) add(int index, E e) - 지정된 위치에 데이터를 담는다. - 그러므로, 이 경우에는 지정된 위치에 있는 기존 데이터들은 위치가 하나씩 뒤로 밀려난다. > 이 내용은 예제 코드로 확인해보자 ```java public void checkArrayList2(){ ArrayList<String> list=new ArrayList<String>(); list.add("A"); list.add("B"); list.add("C"); list.add("D"); list.add("E"); list.add(1,"A1"); for (String tmp:list){ System.out.println(tmp); } } ``` > 출력결과 ```java A A1 B C D E ``` ㄷ) addAll() 바로 예제를 통해 살펴보자 ```java public void checkArrayList2(){ ArrayList<String> list=new ArrayList<String>(); list.add("A"); list.add("B"); list.add("C"); list.add("D"); list.add("E"); list.add(1,"A1"); ArrayList<String> list2=new ArrayList<String>(); list2.add("0 "); list2.addAll(list); for (String tmp:list2){ System.out.println("List2 "+tmp); } } ``` > 출력결과 ```java List2 0 List2 A List2 A1 List2 B List2 C List2 D List2 E ``` 방금 사용한 예제메소드에 새로운 객체를 만들고 `addAll()`메소드를 사용해 값을 추가했다. > 위와 같이 list의 값을 list2에 복사해야 할 일이 생긴다면, 반드시 위처럼 할필요 없이 다음과 같이 생성자를 사용하면 편하다. ```java ArrayList<String> list2=new ArrayList<String>(list); ``` > 어떻게 이게 가능해??? 라는 생각이 들지만 ArrayList에는 Collection 인터페이스를 구현한 어떠한 클래스도 포함시킬 수 있는 생성자가 있기 때문이다. > 여기서 한가지 짚고 넘어갈 것이 있다. > 도대체 왜 Collection을 매개변수로 갖는 생성자와 메소드가 존재할까? > 이는 자바를 개발하다 보면 매우 다양한 타입의 객체를 저장하게되는데 모든 개발자들이 ArrayList만을 사용하는것도 아니고 > 앞으로 배울 `Set`과 `Queue`를 사용하여 데이터를 담을 수도 있으므로 이와 같은 생성자와 메소드를 제공하는 것이다. 한가지 더 알아볼 것이 있다 에제를 보자 ```java public void checkArrayList2(){ ArrayList<String> list=new ArrayList<String>(); list.add("A"); list.add("B"); list.add("C"); list.add("D"); list.add("E"); list.add(1,"A1"); ArrayList<String> list2=list; //치환 수행 list.add("Ooops"); for (String tmp:list2){ System.out.println("List2 "+tmp); } } ``` > 출력결과 ```java List2 A List2 A1 List2 B List2 C List2 D List2 E List2 Ooops ``` > 분명 list2객체에 "Ooops"라는 데이터를 저장한 일이 없는게 이게 뭔일일까? ```java list2=list ``` > 위의 문장은 list2가 list의 값만 사용하겠다는 것이 아니다. > list라는 객체가 생성되어 참조되고 있는 주소까지도 사용하겠다는 말이다. - 자바의 모든 객체가 생성되면 그 객체가 위치하는 주소가 내부적으로 할당된다. - 따라서 list2=list라고 문장을 작성하게 되면, 두 객체의 변수 이름은 다르지만, 하나의 객체가 변경되면 다른 이름의 변수를 갖는 객체도 바뀐다. > 따라서, 하나의 Collection관련 객체를 복사할 일이 있을 때에는 이와 같이 생성자를 사용하거나, addAll()메소드를 쓰자 ### ArrayList에서 데이터를 꺼내자 ArrayList 객체에서 데이터를 꺼내오는 법을 알아보기전에 먼저 알아봐야 할 메소드가 있다. 바로 ArrayList 객체에 들어가 있는 데이터의 개수를 가져오는 `size()` 메소드다. 배열에 넣을 수 있는 공간의 개수를 가져올 때에는 `배열.length`를 사용한다.(String문자열 길이도 마찬가지) > 하지만 Collecttion을 구현한 인터페이스는 size()메소드를 통하여 데이터 개수를 확인한다. > 이때 리턴 타입은 `int`!!! `배열.length`는 배열의 저장 공간 개수를 의미하지만, `size()`메소드의 결과는 데이터 개수를 의미한다. ```java public void checkArrayList3(){ ArrayList<String> list=new ArrayList<String>(); list.add("A"); list.add("B"); list.add("C"); list.add("D"); list.add("E"); int listSize=list.size(); for(int loop=0; loop<listSize; loop++){ System.out.println("list.get("+loop+")="+list.get(loop)); } } ``` > 위와 같은 for 루프 기본방식으로 ArrayList 객체에 있는 값을 가져올 때에는 `get()`메소드를 사용한다. 한 건의 데이터를 꺼내는 메소드는 이 get()메소드 뿐이다. 그리고, 위치로 데이터를 꺼내는 `get()`메소드와는 반대로 데이터로 위치를 찾아내는 `indexOf()`라는 메소드와 `lastIndexOf()` 라는 메소드도 있다. > indexOf()와 lastIndexOf()메소드가 있는 이유가 뭘까? ArrayList는 중복된 데이터를 넣을 수 있다. 즉, 0번째에도 `A` 1번째에도 `A` 가 들어있을 경우를 말한다. > 그런데 간혹 ArrayList객체에 있는 데이터들을 배열로 뽑아낼 때도 있다. 그럴때에는 `toArray()` 메소드를 사용하면 된다. > 여기서 중요한점은 매개변수가 없는 `toArray()`메소드는 `Object`타입의 배열로만 리턴을 한다는 것이다. > 그러므로, 제네릭을 사용하여 선언한 ArrayList객체를 배열로 생성할때에는 이 메소드를 사용하는 것은 좋지 않다. > 그러니 이메소드는 `toArray(T[] a)` 형식으로 사용하자 ```java String[] strList=list.toArray(new String[0]); ``` 이와 같이 toArray() 메소드의 매개 변수로 변환하려는 타입의 배열을 지정해주면 된다. - 매개변수로 넘기는 배열은 그냥 이와 같이 의미없이 타입만을 지정하기 위해서 사용할 수도 있다. - 그런데 실제로는 매개변수로 넘긴 객체에 값을 담아준다. - 하지만, ArrayList객체의 데이터 크기가 매개 변수로 넘어간 배열 객체의 크기보다 클 경우에는 매개 변수로 배열의 모든 값이 `null`로 채워진다. ```java public void checkArrayList3(){ ArrayList<String> list=new ArrayList<String>(); list.add("A"); list.add("B"); list.add("C"); list.add("D"); list.add("E"); String[] tempArray=new String[5]; String[] strList=list.toArray(tempArray); for(String tmp:strList){ System.out.println(tmp); } } ``` > 출력결과 ```java A B C D E ``` > 이번엔 tempArray 배열의 크기를 `[7]`로늘려서 테스트 해보자 (앞 서 말했던 null로 채워지는 문제를 확인하기위해) ```java // 생략 String[] tempArray=new String[7]; String[] strList=list.toArray(tempArray); for(String tmp:strList){ System.out.println(tmp); } ``` > 출력결과 ```java A B C D E null null ``` > 이번에는 반대로 `[2]`로 줄여서 테스트해보자 ```java String[] tempArray=new String[2]; String[] strList=list.toArray(tempArray); for(String tmp:tempArray){ System.out.println(tmp); } ``` > 출력결과 ```java null null ``` > 이처럼 ArrayList에 저장되어 있는 데이터의 크기보다 매개변수로 넘어온 배열의 크기가 작으면 새로운 배열을 생성하여 넘겨주므로, > 가장 처음에 사용한 것과 같이 크기가 `0`인 배열을 넘겨주는 것이 가장 좋다. ### ArrayList에 있는 데이터를 삭제하자 - clear() : 모든 데이터를 삭제 - remove(int index) : 매개 변수에서 지정한 위치에 있는 데이터를 삭제하고, 삭제한 데이터를 리턴 - remove(Object o) : 매개 변수에 넘어온 객체와 동일한 첫번째 데이터를 삭제 - removeAll(Collection<?> c) : 매개 변수로 넘어온 컬렉션 객체에 있는 데이터와 동일한 모든 데이터를 삭제 객체를 넘겨주는 `remove()`와 컬렉션 객체를 넘겨주는`removeAll()`은 비슷해보이지만 약간 다르다. `remove()` 메소드는 매개 변수로 넘어온 객체와 동일한 첫번째 데이터만 삭제한다. `removeAll()`메소드는 매개 변수로 넘어온 컬렉션에 있는 데이터와 동일한 모든 데이터를 삭제한다. ```java public void checkArrayList4(){ ArrayList<String> list=new ArrayList<String>(); list.add("A"); list.add("B"); list.add("C"); list.add("D"); list.add("E"); list.add("A"); System.out.println("Removed "+list.remove(0)); for(int loop=0;loop<list.size();loop++){ System.out.println("list.get("+loop+")="+list.get(loop)); } } ``` > 출력결과 ```java Removed A list.get(0)=B list.get(1)=C list.get(2)=D list.get(3)=E list.get(4)=A ``` 이번에는 메소드 삭제부분을 변경해서 테스트 해보자 ```java //System.out.println("Removed "+list.remove(0)); System.out.println(list.remove("A")); ``` > 출력결과 ```java true list.get(0)=B list.get(1)=C list.get(2)=D list.get(3)=E list.get(4)=A ``` 결과를 보면 A값을 삭제하고 그 결과인 true값이 리턴됬지만 마지막에 있는 `A`는 삭제되지 않았다. > 다시한번 코드를 수정해보자 ```java ArrayList<String> temp=new ArrayList<String>(); temp.add("A"); list.removeAll(temp); ``` > 출력결과 ```java list.get(0)=B list.get(1)=C list.get(2)=D list.get(3)=E ``` > `A`라는 값을 갖는 모든 데이터가 사라진 것을 볼 수 있다. 마지막으로 `set()` 메소드는 값을 변경하는 메소드다 사용법은 비슷하므로 직접 테스트 해보자 --- ### Stack 클래스는 뭐가 다른데? List 인터페이스를 구현한 또 하나의 클래스인 Stack 클래스에 대해서 살펴보자. - LIFO 기능을 구현하려고 할 때 필요한 클래스 > LIFO는 간단하게 말해서 후입선출 - 이 클래스보다 빠른 `ArrayDeque`라는 클래스가 있다 ( 다만 이클래스는 쓰레드에 안전하지 못하다.) - Stack 클래스의 부모 클래스는 `Vector`다 - Stack 클래스에서 구현한 인터페이스는 ArrayList 클래스에서 구현한 인터페이스와 모두 동일하다 - 상속을 잘못 받은 클래스지만 하위호환성을 위해서 이 상속관계를 유지하고 있다고 생각하자. - 생성자가 `Stack()` 하나다. (매개변수가 없다는 말인듯) > Stack 클래스의 메소드는 API를 참고하자 --- ### 직접해 봅시다. ```java import java.util.ArrayList; public class ManageHeight { public static void main(String[] args) { ManageHeight sample=new ManageHeight(); sample.setData(); for (int loop=1;loop<6 ;loop++ ) { //sample.printHeight(loop); sample.printAverage(loop); } } ArrayList<ArrayList<Integer>> gradeHeights = new ArrayList<ArrayList<Integer>>(); public void setData(){ ArrayList<Integer> list1=new ArrayList<Integer>(); list1.add(170); list1.add(180); list1.add(173); list1.add(175); list1.add(177); ArrayList<Integer> list2=new ArrayList<Integer>(); list2.add(160); list2.add(165); list2.add(167); list2.add(186); ArrayList<Integer> list3=new ArrayList<Integer>(); list3.add(158); list3.add(177); list3.add(187); list3.add(176); ArrayList<Integer> list4=new ArrayList<Integer>(); list4.add(173); list4.add(182); list4.add(181); ArrayList<Integer> list5=new ArrayList<Integer>(); list5.add(170); list5.add(180); list5.add(165); list5.add(177); list5.add(172); gradeHeights.add(list1); gradeHeights.add(list2); gradeHeights.add(list3); gradeHeights.add(list4); gradeHeights.add(list5); } public void printHeight(int classNo){ ArrayList<Integer> classHeight = gradeHeights.get(classNo -1); System.out.println("classNo = "+classNo); for(int tempArr: classHeight){ System.out.println(tempArr); } System.out.println(); } public void printAverage(int classNo){ ArrayList<Integer> classAverage = gradeHeights.get(classNo -1); System.out.println("Class No. : "+classNo); double sum=0; for(int tempArr:classAverage){ sum += tempArr; } int count = classAverage.size(); System.out.println("Height average : "+sum/count); } } ``` --- ### 정리해 봅시다. 1. Collection 인터페이스를 구현한 대표적인 타입은 List, Set, Queue 이다. 2. 배열과 같은 형태는 List 인터페이스에서 선언되어 있다. 3. 별도로 정하지 않을 경우 자바에서 제공하는 List 를 구현한 클래스의 데이터 개수는 10개이다. 4. ArrayList(int initialCapacity) 를 사용하면 초기 데이터 개수를 생성과 동시에 지정할 수 있다. 5. 제네릭을 사용하면 컴파일 시점에 타입을 잘못 지정한 부분을 걸러낼 수가 있기 때문이다. 6. add()와 addAll()메소드를 사용하면 ArrayList에 데이터를 담을 수 잇다. 7. 만약 String타입을 담는 list라는 ArrayList를 만들었다면 ```java for(String data:list) { // } ``` 와 같이 사용하면 된다. 8. size() 메소드를 사용하면 Collection을 구현한 클래스들에 들어 있는 데이터 개수를 확인할 수 있다. 9. get() 메소드를 사용하면 매개변수로 넘긴 위치에 있는 값을 리턴한다. 10. remove() 메소드를 사용하면 매개변수로 넘긴 위치에 있는 값을 삭제한다. 만약 매개변수로 객체를 넘기면, 동일한 첫번째 객체를 삭제한다. 11. set() 메소드를 사용하면 첫번째 매개변수로 넘긴 위치에 있는 값은 두번째 매개변수로 넘긴 값으로 대체한다. 12. Stack 클래스는 List 인터페이스를 구현하였다. 13. Stack 클래스에 데이터를 담을 때에는 push() 메소드를 사용한다. 14. Stack 클래스의 peek() 메소드는 가장 위에 있는 값을 리턴만한다. 15. Stack 클래스의 pop() 메소드는 가장 위에 있는 데이터를 지우고 리턴한다. <file_sep>/php/08. include와 네임스페이스.md ## include와 네임스페이스 ** << 목록 >> ** 1 . include란? - include의 사용 2 . 네임스페이스 --------------- ##### include란 ? * php에서는 필요에 따라서 다른 php파일을 코드 안으로 불러와서 사용할 수 있다. ###### include의 사용 `include '파일명.확장자';` - include는 외부의 php파일을 로드할 때 사용하는 명령이다. - php는 외부의 php파일을 로드하는 방법으로 4가지 형식을 제공한다. - include - include_once - require - require_once - `include와 require의 차이점`은 , **존재하지 않는 파일의 로드를 시도했을 때** include가 warning을 일으킨다면 , require는 fatal error를 일으킨다는 점이다. **fatal error**는 warning보다 **심각한 에러**이기 때문에 require가 include 보다 엄격한 로드 방법이라고 할 수 있다. - `_once`라는 접미사가 붙은 것은 파일을 로드할 때 **단 한번만 로드하면 된다는 의미**이다. --------------- ##### 네임스페이스 * 네임스페이스가 무엇인가를 정의하기에 앞서서 파일을 생각해보자. * 파일은 데이터를 보관하고 있는 일종의 컨테이너이다. * 그리고 이 컨테이너는 파일명으로 식별이 된다. * 파일의 수가 많아지면서 파일을 관리하는 것이 점점 어려워진다. * 그래서 고안된 것이 바로 디렉토리 이다. * 디렉토리를 이용하면 같은 이름의 파일이 하나의 컴퓨터에 존재할 수 있다. * 파일명의 충돌을 회피 할 수 있게 된 것이다. * 네임스페이스란 간단하게 `디렉토리`와 같은 것이라고 생각하자. * 하나의 에플리케이션에는 다양한 모듈을 사용하게 된다. * 그런데 모듈이 서로 다른 개발자에 의해서 만들어지기 때문에 **같은 이름을 쓰는 경우**가 생길 수 있다. * 이런 경우 **먼저 로드된 모듈은 나중에 로드된 모듈에 의해서 덮어쓰기 되기 때문에 이에 대한 대책이 필요하다.** * **네임스페이스가 필요해지게 되는 것이다.** * 사용방법 * `namespace` 키워드 뒤에 지정하고자 하는 이름을 작성하면 된다. * 네임스페이스의 구분자는 `\`를 사용한다. [ 자바에서는 `.` 을 이용 ] &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`주의사항 : namespace는 주석을 제외한 그 어떤 코드보다도 먼저 정의되어야 한다.` * 네임스페이스를 활용하면 소스코드를 **구조화** 할 수 있다. 다음 예제를 보자 ```php << greeting_en.php >> <?php function welcome() { return 'Hello world'; } ?> << greeting_ko.php >> <?php function welcome() { return '안녕 세계'; } ?> << O.php >> <?php require_once 'greeting_ko.php'; require_once 'greeting_en.php'; echo welcome(); echo welcome(); ?> ───────────── 출력 ──────────────── Fatal error: Cannot redeclare welcome() (previously declared in C:\Apache24\htdocs\greeting_ko.php:4) in C:\Apache24\htdocs\greeting_en.php on line 5 ``` 위의 파일 실행결과 Fatal error를 출력하는 이유는 , 로드한 두개의 파일 모두 welcome이라는 함수를 선언했기 때문이다. ** PHP에서는 함수의 중복 선언을 허용하지 않는다. ** 이런 경우 네임스페이스를 사용할 수 있다. 아래와 같이 로드되는 파일의 내용을 수정해보자. ```php << greeting_en.php >> <?php // namespace 이름1\이름2; namespace language\en; function welcome() { return 'Hello world'; } ?> << greeting_ko.php >> <?php // namespace 이름1\이름2; namespace language\ko; function welcome() { return '안녕 세계'; } ?> << O.php >> <?php require_once 'greeting_ko.php'; require_once 'greeting_en.php'; // 이름1\이름2\메소드명; echo language\ko\welcome(); echo language\en\welcome(); ?> ───────────── 출력 ──────────────── 안녕 세계Hello world ``` 네임스페이스는 **함수** 뿐만 아니라 **클래스**와 **상수**에 대해서도 사용할 수 있다. `주의할 점`은 인스턴스를 생성하거나 함수를 호출할 때는 네임스페이스 맨 앞에 `\`를 붙인다. 이것은 디렉토리에서 절대경로 `cd \etc`와 같다고 보면 된다. 이 절대경로의 개념은 네임스페이스에 속한 클래스나 함수가 아닌 `전역 클래스`나 `전역 함수`에 접근하는데 활용된다. <br> << 전역 함수를 호출하는 예제 >> ```php << MyClass.php >> <?php namespace myNamespace\mySubNamespace; function printf($str){ \printf(__NAMESPACE__.":%s",$str); // __NAMESPACE__은 php의 상수이며, 현재의 namespace 값이 저장된다. } printf("Hello. Namespace1.<br>"); ?> << OO.php >> <?php require_once 'MyClass.php'; \myNamespace\mySubNamespace\printf("Hello. Namespace2.<br>"); \printf("Hello. Namespace3.<br>"); // 함수 이름 앞에 전역을 의미하는 \을 선언했으므로, 사용자가 만든 printf함수가 아닌, 원래 php에서 제공하는 전역 함수인 printf()를 실행한다. ?> ``` 위의 예제에서 OO.php파일을 실행해 보면 아래와 같은 결과를 얻을 수 있다. ``` myNamespace\mySubNamespace:Hello. Namespace1. myNamespace\mySubNamespace:Hello. Namespace2. Hello. Namespace3. ```<file_sep>/python/algorithm/sum_n1.py def sum_n(n): s=0 for i in range(1,n+1): s= s+i return s print(sum_n(99)) #print(sum_n(100)) <file_sep>/javascript/inside_javascript/chapter07 함수형 프로그래밍/7.js /* *************************************** 7-1 예제 ******************************************* */ var f1 = function(input){ var result; /* 암호화 작업 수행 */ result = 1; return result; } var f2 = function(input){ var result; /* 암호화 작업 수행 */ result = 2; return result; } var f3 = function(input){ var result; /* 암호화 작업 수행 */ result = 3; return result; } var get_encrypted = function(func){ var str = 'zzoon'; return function(){ return func.call(null, str); } } var encrypted_value = get_encrypted(f1)(); console.log(encrypted_value); var encrypted_value = get_encrypted(f2)(); console.log(encrypted_value); var encrypted_value = get_encrypted(f3)(); console.log(encrypted_value); /* *************************************** 7-2-1 예제 ******************************************* */ function sum(arr){ var len = arr.length; var i = 0, sum =0; for (; i<len;i++){ sum += arr[i]; } return sum; } var arr = [1, 2, 3, 4, 5]; console.log(sum(arr)); /* *************************************** 7-2-2 예제 ******************************************* */ function multiply(arr){ var len = arr.length; var i = 0, result =1; for (; i<len;i++){ result *= arr[i]; } return result; } var arr = [1, 2, 3, 4]; console.log(multiply(arr)); /* *************************************** 7-2-4 예제 ******************************************* */ function reduce(func, arr, memo) { var len = arr.length, i = 0, accum = memo; for (; i < len; i++) { accum = func(accum, arr[i]); } return accum; } var arr = [ 1, 2, 3, 4 ]; var sum = function(x, y) { return x+y; }; var multiply = function(x, y) { return x*y; }; console.log(reduce(sum, arr, 0)); console.log(reduce(multiply, arr, 1)); /* *************************************** 7-3-1 예제 ******************************************* */ function fact(num) { var val = 1; for (var i = 2; i <= num; i++) val = val * i; return val; } console.log(fact(100)); /* *************************************** 7-3-2 예제 ******************************************* */ function fact(num) { if (num == 0) return 1; else return num* fact(num-1); } console.log(fact(100)); /* *************************************** 7-3-3 예제 ******************************************* */ var fact = function() { var cache = {'0' : 1}; var func = function(n) { var result = 0; if (typeof(cache[n]) === 'number') { result = cache[n]; } else { result = cache[n] = n * func(n-1); } return result; } return func; }(); console.log(fact(10)); console.log(fact(20)); /* *************************************** 7-4 예제 ******************************************* */ var fibo = function() { var cache = {'0' : 0, '1' : 1}; var func = function(n) { if (typeof(cache[n]) === 'number') { result = cache[n]; } else { result = cache[n] = func(n-1) + func(n-2); } return result; } return func; }(); console.log(fibo(10)); /* *************************************** 7-7 예제 ******************************************* */ function Calculate(a, b, c) { return a*b+c; } function Curry(func) { var args = Array.prototype.slice.call(arguments, 1); return function() { return func.apply(null, args.concat(Array.prototype.slice.call(arguments))); } } var new_func1 = Curry(Calculate, 1); console.log(new_func1(2,3)); // 5 var new_func2 = Curry(Calculate, 1, 3); console.log(new_func2(3)); // 6 /* *************************************** 7-9 예제 ******************************************* */ var print_all = function(arg) { for (var i in this) console.log(i + " : " + this[i]); for (var i in arguments) console.log(i + " : " + arguments[i]); } var myobj = { name : "zzoon" }; var myfunc = print_all.bind(myobj); myfunc(); // name : zzoon var myfunc1 = print_all.bind(myobj, "iamhjoo", "others"); myfunc1("insidejs"); /* *************************************** 7-10 예제 ******************************************* */ function wrap(object, method, wrapper){ var fn = object[method]; return object[method] = function(){ //return wrapper.apply(this, [ fn.bind(this) ].concat( return wrapper.apply(this, [ fn ].concat( Array.prototype.slice.call(arguments))); }; } Function.prototype.original = function(value) { this.value = value; console.log("value : " + this.value); } var mywrap = wrap(Function.prototype, "original", function(orig_func, value) { this.value= 20; orig_func(value); console.log("wrapper value : " + this.value); }); var obj = new mywrap("zzoon"); /* *************************************** 7-11 예제 ******************************************* */ function each( obj, fn, args ) { if ( obj.length == undefined ) for ( var i in obj ) fn.apply( obj[i], args || [i, obj[i]] ); else for ( var i = 0; i < obj.length; i++ ) fn.apply( obj[i], args || [i, obj[i]] ); return obj; }; each([1,2,3], function(idx, num) { console.log(idx + ": " + num); }); var zzoon = { name : "zzoon", age : 30, sex : "Male" }; each(zzoon, function(idx, value) { console.log(idx + ": " + value); }); /* *************************************** 7-13 예제 ******************************************* */ Array.prototype.reduce = function(callback) { // this 가 null 인지, 배열인지 체크 // callback이 함수인지 체크 var obj = this; var value, accumulated_value = 0; for ( var i = 0; i < obj.length; i++ ) { value = obj[i]; //console.log("exe"); accumulated_value = callback.call(null, accumulated_value, value); } return accumulated_value; }; var arr = [1,2,3]; var accumulated_val = arr.reduce(function(a, b) { return a + b*b; }); console.log(accumulated_val); <file_sep>/게시판만들기/struts1 게시판 만들기/WEB-INF/classes/my/bbs2/controller/action/BbsWriteOkAction.java package my.bbs2.controller.action; import org.apache.struts.action.*; import javax.servlet.ServletContext; import javax.servlet.http.*; import com.oreilly.servlet.*; import com.oreilly.servlet.multipart.*; import my.bbs2.*; public class BbsWriteOkAction extends Action{ @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { /** * 1. ActionForm은 파일 업로드 관련 데이터 셋팅 언됨 * 업로드할 경우 request의 기능이 상실됨 -->MultipartRequest가 가져가므로 * */ HttpSession session = request.getSession(); ServletContext ctx = session.getServletContext(); String upDir = ctx.getRealPath("/bbs2/Upload"); String upDir2 = "C:/javaide/workspace/bbs-all/WebContent/bbs2/Upload"; MultipartRequest mr = new MultipartRequest(request,upDir2,10*1024*1024,"UTF-8", new DefaultFileRenamePolicy()); BbsManager mgr = BbsManager.getInstance(); int result = mgr.writeOk(mr); System.out.println("upDir : "+upDir); System.out.println("upDir2 : "+upDir2); String msg="", url=""; if(result > 0){ msg = "글쓰기 성공"; url = "bbs-list.do?method=list"; }else{ msg = "글쓰기 실패"; url = "javascript:history.go(-1)"; } request.setAttribute("bbs-msg", msg); request.setAttribute("bbs-url", url); return mapping.findForward("gb-bbs-msg"); //return null; } } <file_sep>/java/toby_spring/Vol.1/1장/README.md ## 오브젝트와 의존관계 > 스프링의 핵심철학 객체지향 프로그래밍이 제공하는 폭넓은 혜택을 누릴 수 있도록 기본으로 돌아가자는 것 스프링이 가장 관심을 많이 두는 대상은 오브젝트다. 그래서 스프링을 이해하려면 먼저 오브젝트에 깊은 관심을 가져야 한다. 애플리케이션에서 오브젝트가 생성되고 다른 오브젝트와 관계를 맺고, 사용되고, 소멸하기까지의 전 과정을 진지하게 생각해볼 필요가 있다. 더 나아가서 오브젝트는 어떻게 설계돼댜 하는지, 어떤 단위로 만들어지며 어떤 과정을 통해 자신의 존재를 드러내고 등장해야 하는지에 대해서도 살펴봐야 한다. 결국 오브젝트에 대한 관심은 오브젝트의 기술적인 특징과 사용 방법을 넘어서 오브젝트의 설계로 발전하게 된다. 객체지향 설계(Object oriented design)의 기초와 원칙을 비롯해서, 다양한 목적을 위해 재활용 가능한 설계 방법인 디자인 패턴, 좀 더 깔끔한 구조가 되도록 지속적으로 개선해나가는 작업인 리팩토링, 오브젝트가 기대한 대로 동작하고 있는지를 효과적으로 검증하는 데 쓰이는 단위 테스트와 같은 오브젝트 설계와 구현에 관한 여러가지 응용기술과 지식이 요구된다. ### 초난감 DAO > 사용자 정보를 JDBC API를 통해 DB에 저장하고 조회할 수 있는 간단한 DAO를 통해 차근차근 알아보자 DAO(Data Access Object)는 DB를 사용해 데이터를 조회하거나 조작하는 기능을 전담하도록 만든 오브젝트를 말한다. > User 클래스 ```java package springbook.dev.com; public class User { String id; String name; String password; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } ``` > UserDao ```java package springbook.user.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import springbook.user.domain.User; public class UserDao { public void add(User user) throws ClassNotFoundException, SQLException { Class.forName("com.mysql.jdbc.Driver"); Connection c = DriverManager.getConnection( "jdbc:mysql://localhost/springbook?characterEncoding=UTF-8", "spring", "book"); PreparedStatement ps = c.prepareStatement( "insert into users(id, name, password) values(?,?,?)"); ps.setString(1, user.getId()); ps.setString(2, user.getName()); ps.setString(3, user.getPassword()); ps.executeUpdate(); ps.close(); c.close(); } public User get(String id) throws ClassNotFoundException, SQLException { Class.forName("com.mysql.jdbc.Driver"); Connection c = DriverManager.getConnection( "jdbc:mysql://localhost/springbook?characterEncoding=UTF-8", "spring", "book"); PreparedStatement ps = c .prepareStatement("select * from users where id = ?"); ps.setString(1, id); ResultSet rs = ps.executeQuery(); rs.next(); User user = new User(); user.setId(rs.getString("id")); user.setName(rs.getString("name")); user.setPassword(rs.getString("password")); rs.close(); ps.close(); c.close(); return user; } } ``` 가장 기본적인 위 코드들이 만들어졌다. 그런데 만약 이 클래스가 제대로 동작하는지 어떻게 확인할 수 있을까? 서버에 배치하고, 웹브라우져를 통해 테스트해보는 방법이 있지만, 이런 간단한 UserDao 코드를 확인하기 위한 작업치고는 부담이 너무 크다. > 이럴때 가장 간단한 방법은 main()메소드를 통해 확인해보는 방법이 있다. ```java public static void main(String[] args) throws ClassNotFoundException, SQLException{ UserDao dao = new UserDao(); User user = new User(); user.setId("whiteship"); user.setName("신명철"); user.setPassword("<PASSWORD>"); dao.add(user); User user2 = dao.get(user.getId()); System.out.println(user2.getName()); System.out.println(user.getPassword()); System.out.println(user2.getId()+ " 조회성공"); } ``` > 출력결과 ```java 신명철 1234 whiteship 조회성공 ``` > 위의 DAO는 테스트결과 문제없이 잘 실행된다.. > 하지만 위 코드는 사실 문제점이 많은 코드다..어떤점이 문제가 될지 생각해보자 ### DAO의 분리 > 과연 어떻게 변경이 일어날 때 필요한 작업을 최소화하고, 그 변경이 다른곳에 문제를 일으키지 않게 할수 있을까? 그것은 **분리**와 **확장**을 고려한 설계를 필요로 한다. 보통 모든 변경과 발전은 한 번에 한가지 관심사항에 집중해서 일어난다. 여기서 먼저 분리에 대해 생각해보자 문제는, ++**변화는 대체로 집중된 한가지**++관심에 대해 일어나지만 그에따른 작업은 한곳에 집중되지 않는 경우가 많다는 점이다. - 단지 DB접속용 암호를 변경하려고 DAO클래스 수백개를 모두 수정해야 한다면? - 혹은 트랙잭션 기술을 다른 것으로 바꿨따고 비즈니스 로직이 담긴 코드의 구조를 모두 변경해야 한다면? - 또는 다른 개발자가 개발한 코드에 변경이 이러날 때마다 내가 만든 클래스도 함께 수정을 해줘야 한다면? 생각만해도 끔직한 일이다. 만약 변화가 한 번에 한가지 관심에(예를들어 특정하여 DB접속정보를 변경해야하는 경우) 집중돼서 일어난다면, 우리가 준비해야 할 일은 ++**한가지 관심이 한 군데에 집중되게 하는 것**++이다. **즉 관심이 같은 것끼리는 모으고, 관심이 다른 것을 따로 떨어져 있게 하는것이다.** 프로그래밍의 기초 개념 중에 관심사의 분리(Separation of Concerns)라는 게 있다. 이를 객체지향에 적용해보면, 관심이 같은 것끼리는 하나의 객체 안으로 또는 친한 객체로 모이게 하고, 관심이 다른 것은 가능한 한 따로 떨어져서 서로 영향을 주지 않도록 분리하는 것이라고 생각할 수 있다. #### 커넥션 만들기의 추출 위의 서술했던 관심사를 클래스를 통해 살펴보자 UserDao의 add()메소드 하나에서만 적어도 세 가지의 관심사항을 발견할 수 있다. 1. DB연결을 위한 커넥션을 어떻게 가져올까? 2. 사용자 정보를 Statement에 담긴 SQL을 DB를 통해 실행시키는 방법 3. 작업이 끝나면 사용한 리소스인 Statement와 Connection오브젝트를 닫아줘서 공유 리소스를 시스템에 돌려주기! 여기서 가장 문제가 되는 것은 첫번째 관심사인 DB연결을 위한 Connection 오브젝트를 가져오는 부분이다. DB커넥션을 가져오는 코드가 다른 관심사와 섞여서 add(), get()두개의 메소드의 동일하게 중복되어 있다. 여기서는 두개의 메소드지만 만약 수백,수천 개의 DAO 메소드를 만들었다면 정말 답도 없는 상황이 나온다. **바로 이렇게 하나의 관심사가 방만하게 중복되어 있고, 여기저기 흩어져 있어서 다른 관심의 대상과 얽혀 있으면, 변경이 일어날 때 엄청난 고통을 일으키는 원인이 된다.** ##### 중복 코드의 메소드 추출 가장 먼저 할 일은 커넥션을 가져오는 이 중복된 코드를 분리하는 것이다. > DB 커넥션 정보를 가져오는 별도의 메소드 getConnection() 메소드를 만든다 ```java public void add(User user) throws ClassNotFoundException, SQLException { Connection c = getConnection(); ... } public User get(String id) throws ClassNotFoundException, SQLException { Connection c = getConnection(); ... } private Connection getConnection() throws ClassNotFoundException, SQLException { Class.forName("com.mysql.jdbc.Driver"); Connection c = DriverManager.getConnection( "jdbc:mysql://localhost/springbook?characterEncoding=UTF-8", "spring", "book"); return c; } ``` 이렇게 중복되는 코드를 분리하여 별도의 메소드로 만드니 DB커넥션 정보가 바뀌더라도 이 메소드만 수정하면 된다. 관심의 종류에 따라 코드를 구분해놓았기 때문에 한 가지 관심에 대한 변경이 일어날 경우 그 관심이 집중되는 부분의 코드만 수정하면 된다. ##### 변경사항에 대한 검증:리팩토링과 테스트 이렇게 코드를 수정했지만 UserDao의 기능에는 아무런 변화가 없다. 이 작업은 기능에는 영향을 주지 않으면서 코드의 구조만 변경해서, 훨씬 깔금해졌고 미래의 변화에 좀 더 손쉽게 대응할 수 있는 코드가 됬다. > 바로 이런 작업을 `리팩토링(refactoring)`이라고 한다. > 또한, 위에서 사용한 `getConnection()`이라고 하는 공통의 기능을 담당하는 메소드로 중복된 코드를 뽑아내는 것을 리팩토링에서는 `메소드 추출(extract method)` 기법이라고 부른다. 그런데 여기서 만약 UserDao의 소스코드를 공개하지 않고 DB커넥션 생성방식을 각각 다른 방법으로 사용하려면 어떻게 해야될까? N사와 D사의 비유를 생각해보자 ##### 상속을 통한 확장 고객에게 전체 소스코드를 노출하지 않으면서도 고객별로 독립된 DB커넥션 생성방식을 제공하려면 기존의 UserDao 코드를 한 단계 더 분리해야 한다. 바로 getConnect()을 추상 메소드로 만드는 것이다. 추상 메소드라서 메소드 코드는 없지만 메소드 자체는 존재한다. 따라서 add(), get()메소드에서 getConnection()을 호출하는 코드는 그대로 유지할 수 있다. > 기존에는 같은 클래스에 다른 메소드로 분리됐던 DB커넥션 연결이라는 관심을 이번에는 상속을 통해 서브클래스로 분리해버리는 것이다. 아래는 위와 같은 방식으로 리팩토링한 코드다 ```java public abstract class UserDao { public void add(User user) throws ClassNotFoundException, SQLException { Connection c = getConnection(); ... } public User get(String id) throws ClassNotFoundException, SQLException { Connection c = getConnection(); ... } abstract protected Connection getConnection() throws ClassNotFoundException, SQLException ; public class NUserDao extends UserDao { protected Connection getConnection() throws ClassNotFoundException, SQLException { Class.forName("com.mysql.jdbc.Driver"); Connection c = DriverManager.getConnection( "jdbc:mysql://localhost/springbook?characterEncoding=UTF-8", "spring", "book"); return c; } public class DUserDao extends UserDao { protected Connection getConnection() throws ClassNotFoundException, SQLException { Class.forName("com.mysql.jdbc.Driver"); Connection c = DriverManager.getConnection( "jdbc:mysql://localhost/springbook?characterEncoding=UTF-8", "spring", "book"); return c; } } ``` 수정한 코들르 살펴보면, 클래스 계층구조를 통해 두 개의 관심이 독립적으로 분리되면서 변경작업은 한층 용이해졌다. 이제는 UserDao의 코드는 한 줄도 수정할 필요 없이 DB연결 기능을 새롭게 정의한 클래스를 만들 수 있다. 이제 UserDao는 단순히 변경이 용이하다라는 수준을 넘어서 손쉽게 확장된다라고 말할 수도 있게 됐다. 이렇게 **슈퍼클래스에 기본적인 로직의 흐름(커넥션 가져오기, SQL생성, 실행, 반환)을 만들고, 그 기능의 일부를 추상메소드나 오버라이딩이 가능한 protected 메소드 등으로 만든 뒤 서브클래스에서 이런 메소드를 필요에 맞게 구현해서 사용하도록 하는 방법**을 디자인 패턴에서 `템플릿 메소드 패턴(template method pattern)`이라고 한다. 이 `템플릿 메소드 패턴`은 스프링에서 애용되는 디자인 패턴이다. - UserDao의 getConnection()메소드 = Connection 타입 오브젝트를 생성한다는 기능을 정의해놓은 추상메소드 - UserDao의 서브클래스의 getConnection()메소드 = 어떤 Connection 클래스의 오브젝트를 어떻게 생성할 것인지를 결정하는 방법 위처럼 서브클래스에서 구체적인 오브젝트 생성방법을 결정하게 하는 것을 `팩토리 메소드 패턴(factory method pattern)`이라고 부르기도 한다. 이와 같이 변경함으로 인해 관심사항이 다른 코드를 분리해내고, 서로 독립적으로 변경 또는 확장할 수 있도록 만드는 것은 간단하면서도 매우 효과적인 방법이다. 하지만 이 방법은 상속을 사용했다는 단점이 있다. 상속 자체는 간단해 보이고 사용하기도 편리하게 느껴지지만 사실 많은 한계점이 있다. 만약 이미 UserDao가 다른 목적을 위해 상속을 사용하고 있다면 어쩔까? **자바는 클래스의 다중상속을 허용하지 않는다** 단지, 커넥션 객체를 가져오는 방법을 분리하기 위해 상속구조로 만들어버리면, 후에 다른 목적으로 UserDao에 상속을 적용하기 힘들다. 또 다른 문제는 **상속을 통한 상하위 클래스의 관계는 생각보다 밀접하다**는 점이다. 상속관계는 두 가지 다른 관심사에 대해 긴밀한 결합을 허용한다. 서브클래스는 슈퍼클래스의 기능을 직접 사용할 수 있다. 그래서 슈퍼클래스 내부의 변경이 있을 때 모든 서브클래스를 함께 수정하거나 다시 개발해야 할 수도 있다. 반대로 그런 변화에 따른 불편을 주지 않기 위해 슈퍼클래스가 더 이상 변화하지 않도록 제약을 가해야 할지도 모른다. 또한 확장된 기능인 DB 커넥션을 생성하는 코드를 다른 DAO클래스에 적용할 수 없다는 것도 큰 단점이다. ### DAO의 확장 상속을 통한 구현의 여러가지 문제점을 살펴봤으니 이번에는 또다른 관점에서 접근해보자 ##### 클래스의 분리 두 개의 관심사를 본격적을 독립시키면서 동시에 손쉽게 확장할 수 있는 방법 지금까지는 성격이 다른, 그래서 다르게 변할 수 있는 관심사를 분리하는 작업을 점진적으로 진행해왔다. 처음에는 독립된 메소드를만들어 분리했고, 다음에는 상하위클래스로 분리했다. 이번에는 아예 상속관계도 아닌 완전히 독립적인 클래스로 만들어 보자 즉, 서브클래스가 아닌 아예 별도의 클래스를 만들고, 이렇게 만든 클래스를 UserDao가 이용하게 하는 것이다. `SimpleConnectionMaker`라는 새로운 클래스를 만들고 DB생성 기능을 그 안에 넣는다. 그리고 UserDao는 new 키워드를 사용해 `SimpleConnectionMaker` 클래스의 오브젝트를 만들어두고, 이를 add(), get()메소드에서 사용하면 된다. > 독립된 SimpleConnectionMaker를 사용하게 만든 UserDao ```java public abstract class UserDao { private SimpleConnectionMaker simpleConnectionMaker; public UserDao() { this.simpleConnectionMaker = new SimpleConnectionMaker(); } public void add(User user) throws ClassNotFoundException, SQLException { Connection c = this.simpleConnectionMaker.getConnection(); ... } public User get(String id) throws ClassNotFoundException, SQLException { Connection c = this.simpleConnectionMaker.getConnection(); ... } } ``` > 독립시킨 DB연결 기능 메소드를 담은 SimpleConnectionMaker ```java package springbook.user.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class SimpleConnectionMaker { public Connection getConnection() throws ClassNotFoundException, SQLException { Class.forName("com.mysql.jdbc.Driver"); Connection c = DriverManager.getConnection( "jdbc:mysql://localhost/springbook?characterEncoding=UTF-8", "spring", "book"); return c; } } ``` 이처럼 성격이 다른 코드를 화끈하게 분리하기는 잘한 것 같은데, 이번엔 다른 문제가 발생했다. N사와 D사에 UserDao클래스만 공급하고 상속을 통해 DB커넥션 기능을 확장해서 사용하게 했던 게 다시 불가능해졌다. 즉 UserDao 소스코드의 다음 줄을 직접 수정해야 한다. ```java simpleConnectionMaker = new SimpleConnectionMaker(); ``` UserDao의 소스코드를 함께 제공하지 않고는 DB연결방법을 바꿀 수 없다는 처음 문제로 다시 되돌아와 버렸다. 이렇게 클래스를 분리한 경우에도 상속을 이용했을 때와 마찬가지로 자유로운 확장이 가능하게 하려면 두 가지 문제를 해결해야 한다. 1. 분리한 simpleConnectionMaker 클래스의 메소드 예) Connection c = simpleConnectionMaker.openConnection(); 2. DB커넥션을 제공하는 클래스가 어떤 것인지를 UserDao가 구체적으로 알고 있어야 한다는 점 이러한 문제들의 근본적인 원인은 UserDao가 바뀔 수 잇는정보, 즉 DB커넥션을 가져오는 클래스에 대해 너무 많이 알고 있기 때문이다. 어떤 클래스가 쓰일지, 그 클래스에서 커넥션을 가져오는 메소드는 이름이 뭔지까지 일일히 알고 있어야 한다. 따라서 **UserDao는 DB커넥션을 가져오는 구체적인 방법에 종속**되어 버린다. 결과적으로 보면 상속을 이용한 방법만도 못한 상황이 되버렸다. #### 인터페이스의 도입 그렇다면 클래스를 분리하면서도 이런 문제를 해결할 수는 없을까? 가장 좋은 해결책은 두 개의 클래스가 서로 긴밀하게 연결되어 있지 않도록 중간에 추상적인 느슨한 연결고리를 만들어 주는 것이다. > 추상화란 어떤 것들의 공통적인 성격을 뽑아내어 이를 따로 분리해내는 작업을 말한다. 자바가 추상화를 위해 제공하는 가장 유용한 도구는 바로 인터페이스다. 결국 오브젝트를 만들려면 구체적인 클래스 하나를 선택해야겠지만, 인터페이스로 추상화해놓은 최소한의 통로를 통해 접근하는 쪽에서는 오브젝트를 만들때 사용할 클래스가 무엇인지 몰라도 된다. 즉 이제 UserDao는 자신이 사용할 클래스가 어떤 것인지 몰라도 된다. UserDao가 인터페이스를 사용하게 한다면 인터페이스의 메소드를 통해 알 수 있는 기능에만 관심을 가지면 되지, 그 기능을 어떻게 구현했는지에는 관심을 둘 필요가 없다. DB커넥션을 가져오는 메소드 이름을 makeConnection()이라고 정하고, 이 인터페이스를 사용하는 UserDao 입장에서는 ConnectionMaker 인터페이스 타입의 오브젝트라면 어떤 클래스로 만들어졌든지 상관없이 makeConnection()메소드를 호출하기만 하면 Connection 타입의 오브젝트를 만들어서 돌려줄 것이라고 기대할 수 있다. > ConnectionMaker 인터페이스 ```java public interface ConnectionMaker { public abstract Connection makeConnection() throws ClassNotFoundException, SQLException; } ``` 즉 고객에게 납품을 할 때는 UserDao클래스와 함께 ConnectionMaker 인터페이스도 전달한다. 그리고 D사의 개발자라면 아래와 같이 ConnectionMaker 인터페이스를 구현한 클래스를 만들고, 메소드를 작성해주면 된다 > ConnectionMaker 구현 클래스 ```java public class DConnectionMaker implements ConnectionMaker { public Connection makeConnection() throws ClassNotFoundException, SQLException { ... } } ``` 그러면 이 코드를 적용한 UserDao의 코드를 살펴보자 > ConnectionMaker 인터페이스를 사용하도록 개선한 UserDao ```java public class UserDao { // 인터페이스를 통해 오브젝트에 접근하므로 구체적인 클래스 정보를 알 필요가 없다. private ConnectionMaker connectionMaker; // 생성자에 클래스 이름이 나온다...(관계에 유의...) public UserDao() { connectionMaker = new DConnectionMaker(); } // 인터페이스에 정의된 메소드를 사용하므로 클래스가 바뀐다고 해도 메소드 이름이 변경될 걱정은 없다. public void add(User user) throws ClassNotFoundException, SQLException { Connection c = connectionMaker.makeConnection(); ... } public User get(String id) throws ClassNotFoundException, SQLException { Connection c = this.connectionMaker.makeConnection(); ... } } ``` UserDao의 add(), get()메소드와 필드에는 ConnectionMaker라는 인터페이스와 인터페이스의 메소드인 makeConnection만 사용하도록 했다. 그러니 이제는 아무리 N사와D사가 DB접속용 클래스를 다시 만든다고 해도 UserDao의 코드를 뜯어 고칠 일은 없을 것 같다. 그러나 자세히 살펴보면 DConnection 클래스의 생성자를 호출해서 오브젝트를 생성하는 코드가 아래와 같이 여전히 UserDao에 남아있다. ```java connectionMaker = new DConnectionMaker(); ``` UserDao의 다른 모든 곳에서는 인터페이스를 이용하게 만들어서 DB커넥션을 제공하는 클래스에 대한 구체적인 정보는 모두 제거가 가능했지만, 초기에 한 번 어떤 클래스의 오브젝트를 사용할지를 결정하는 생성자의 코드는 제거되지 않고 남아 있다. > 초기에 한 번 사용하는 이 코드조차 제거를 하려면 어떻게 해야 할까? 결국, 또 다시 원점이다. 여전히 UserDao소스코드를 함께 제공해서, 필요할 때마다 UserDao의 생성자 메소드를 직접 수정하지 않고서는 고객에게 자유로운 DB커넥션 확장 기능을 가진 UserDao를 제공할 수 가 없다. #### 관계설정 책임의 분리 말이 어렵지만 문장의 뜻보다는 흐름을 통해 이해하자 UserDao와 ConnectionMaker 라는 두 개의 관심을 인터페이스를 써가면서까지 거의 완벽하게 분리했는데도, 여전히 UserDao에는 어떤 ConnectionMaker 구현 클래스를 사용할지를 결정하는 코드가 남아있다. 이 때문에 여전히 UserDao변경 없이는 DB커넥션 기능의 확장이 자유롭지 못한데, 그 이유는 UserDao안에 분리되지 않은, 또 다른 관심사항이 존재하고 있기 때문이다. UserDao의 관심사항 - JDBC API와 User오브젝트를 이용해 DB에 정보를 어떻게 넣고 뺄 것인가? - ConnectionMaker 인터페이스로 대표되는 DB커넥션을 어떻게 가져올 것인가? UserDao 에 있는 new DConnectionMaker()라는 코드는 위의 두가지 관심사항과는 또다른 어떤 ConnectionMaker 구현 클래스의 오브젝트를 사용할지를 결정하는 관심사를 가지고 있다. 간단히 말하자면 UserDao와 UserDao가 사용할 ConnectionMaker의 특정 구현 클래스 사이의 관계를 설정해주는 것에 관한 관심이다. > 바로 이 관심사를 담은 코드를 UserDao에서 분리하지 않으면 UserDao는 결코 독립적으로 확장 가능한 클래스가 될 수 없다. 여기서 클라이언트의 개념이 필요한데 여기서 말하는 `클라이언트`는 두개의 오브젝트가 있고 A오브젝트가 B오브젝트의 기능을 사용한다면, 사용되는 쪽인 A오브젝트가 사용하는 쪽인 B오브젝트에게 서비스를 제공하는 셈이다. 이때 사용되는 오브젝트 `A를 서비스`, `B를 클라이언트`라고 부를 수 있다. UserDao의 클라이언트라고 하면 UserDao를 사용하는 오브젝트를 가리킨다. 갑자기 뜬금없이 클라이언트에 대한 정의까지 해가며 설명을 하는 이유는 바로 이곳이 UserDao와 ConnectionMaker 구현 클래스의 관계를 결정해주는 기능을 분리해서 두기에 적절한 곳이기 때문이다. > 즉 우리는 UserDao의 모든 코드를 ConnectionMaker 인터페이스 외에는 어떤 클래스와도 관계를 가져서는 안되면서도, > UserDao 오브젝트가 동작하려면 특정 클래스의 오브젝트와 관계를 맺도록 만들어야 한다. 주의할점은 **클래스 사이의 관계가 아닌, 단지 오브젝트 사이에 다이나믹한 관계**를 만들어야 한다는 것이다. 이 차이를 잘 구분해야 하는데............. 클래스 사이의 관게는 앞서 살펴봤던 ```java connectionMaker = new DConnectionMaker(); ``` 위 코드처럼 코드에 다른 클래스 이름이 나타내기 때문에 만들어지는 것이다. 하지만 ++**오브젝트 사이의 관계**++는 그렇지 않다. 코드에서는 특정 클래스를 전혀 알지 못하더라도 해당 클래스가 구현한 인터페이스를 사용했다면, 그 클래스의 오브젝트를 인터페이스 타입으로 받아서 사용할 수 있다. 이거야 말로 객체지향 프로그램의 **다형성** 이라는 특징 덕분에 가능한 일이다. 다시 본론으로 돌아와서 UserDao 오브젝트가 DConnectionManager 오브젝트를 사용하게 하려면 두 클래스의 오브젝트 사이에 - 런타임 사용관계 or - 링크 or - 의존관계 라 불리는 관계를 맺어주면 된다. > 그렇다면 **오브젝트간의 관계**를 설명하기전에 먼저 언급했던 UserDao의 클라이언트는 무슨 역할을 하는 걸까? 바로 위와 같은 런타임 오브젝트 관계를 갖는 구조로 만들어주는게 클라이언트의 책임이다. 기존의 UserDao에서는 생성자에게 이 책임이 있었다면, 이 역할을 클라이언트가 넘겨 받는 셈이다. > UserDao의 생성자가 맡고 있떤 역할을 클라이언트에게 넘김에 따라 생성자를 새로 수정하자 ```java public UserDao(ConnectionMaker connectionMaker){ this.connectionMaker = connectionMaker; } ``` 보다시피 클라이언트가 미리 만들어 둔 ConnectionMaker의 오브젝트를 전달 받을 수 있도록 매개변수를 추가했고, 그에 따라 구체적인 구현체의 이름인 `DConnectionMaker()`가 드디어 사라졌다. > 어떻게 이것이 가능한 걸까? > UserDao의 클라이언트 UserDaoTest 클래스(새로만들었다)를 통해 살펴보자 ```java public class UserDaoTest{ public static void main(String[] args) throws ClassNotFoundException, SQLException{ // UserDao가 사용할 ConnectionMaker 구현 클래스를 결정하고 오브젝트를 만든다. ConnectionMaker connectionMaker = new DConnectionMaker(); // 1. UserDao 생성 // 2. 사용할 ConnectionMaker 타입의 오브젝트 제공. // 결국 두 오브젝트 사이의 의존관계 설정 효과 UserDao dao = new UserDao(connectionMaker); ... } } ``` UserDaoTest는 UserDao와 ConnectionMaker 구현 클래스와의 **런타임 오브젝트 의존관계**를 설정하는 책임을 담당해야 한다. 그래서 특정 ConnectionMaker 구현 클래스의 오브젝트를 만들고, UserDao 생성자 파라미터에 넣어 두 개의 오브젝트를 연결해 준다. > 이렇게 `인터페이스`를 도입하고 `클라이언트`의 도움을 얻는 방법은 상속을 사용해 비슷한 시도를 했을 경우에 비해서 훨씬 유연하다. #### 원칙과 패턴 ##### 개방 폐쇄 원칙 개방 폐쇄 원칙(OCP, Open-Closed Principle)을 이요하면 지금까지 해온 리팩토리 작업의 특징과 최종적으로 개선된 설계와 코드의 장점이 무엇인지 효과적으로 설명할 수 있다. - 깔끔한 설계를 위해 적용 가능한 객체지향 설계 원칙중의 하나 - '클래스나 모듈은 확장에는 열려 있어야 하고 변경에는 닫혀 있어야 한다.' > 참고로 객체지향 설계 원칙(SOLID) 에 대해 참고해보자 [참고사이트 바로가기](http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod) > - SRP(The Single Responsibility Principle) : 단일 책임 원칙 > - OCP(The Open Closed Principle) : 개방 폐쇄 원칙 > - LSP(The Liskov Substitution Principle) : 리스코프 치환 원칙 > - ISP(The Interface Segregation Principle) : 인터페이스 분리 원칙 > - DIP(The Dependency Inversion Principle) : 의존관계 역전 원칙 #### 높은 응집도와 낮은 결합도 개방 폐쇄 원칙은 **높은 응집도와 낮은 결합도**라는 소프트웨어 개발의 고전적인 원리로도 설명이 가능하다 높은 응집도 - 하나의 모듈, 클래스가 하나의 책임 또는 관심사에만 집중되어 있다는 뜻 - 불필요하거나 직접 관련이 없는 외부의 관심과 책임이 얽혀 있지 않으며, 하나의 공통 관심사는 한 클래스에 모여있다. 낮은 결합도 - 책이과 관심사가 다른 오브젝트 또는 모듈과는 느슨하게 연결된 형태를 유지하는 것이 바람직 - 관계를 유지하는데 꼭 필요한 최소한의 방법만 간접적인 형태고 제공하고, 나머지는 서로 독립적이고 알 필요도 없게 만드는것이다. - 결합도가 낮아지면 변화에 대응하는 속도가 높아지고, 구성이 깔끔해진다. 또한 확장하기에도 매우 편리하다. #### 전략패턴 최종적으로 개선한 UserDaoTest - UserDao - ConnectionMaker 구조를 디자인 패턴의 시각으로 보면 `전략 패턴(Strategy Pattern)`에 해당한다고 볼 수 있다. - 디자인 패턴의 꽃이라고 불릴만큼 다양하고 자주 사용되는 패턴 - 개방 폐쇄 원칙의 실현에도 가장 잘 들어 맞는 패턴 > 자신의 기능 맥락(context)에서, 필요에 따라 변경이 필요한 알고리즘을 인터페이스를 통해 통째로 외부로 분리시키고, 이를 구현한 구체적인 알고리즘 클래스를 필요에 따라 바꿔서 사용할 수 있게 하는 디자인 패턴이다. 여기서 UserDao는 전략패턴의 `컨텍스트에` 해당되고,DB 연결방식인 ConnectionMaker 인터페이스를 구현한 클래스는 `전략`으로 볼 수 있다. ### 제어의 역전 (IoC) IoC라는 약자로 많이 사용되는 제어의 역전(Inversion of Control)이라는 용어가 있다. 스프링을 통해 알려졌지만 이미 그전부터 있어왔던 개념으로 UserDao코드를 좀더 개선해가며 알아보자 #### 오브젝트 팩토리 지금까지 개선해온 코드는 사실 얼렁뚱땅 넘긴 게 하나 있다 바로 클라이언트인 UserDaoTest다. 지금껏 가장 중점적으로 해왔던 작업이 성격이 다른 책이이나 관심사를 분리하는 작업이였는데, UserDaoTest는 현재 UserDao의 기능이 잘 동작하는지 테스트하려고 만들었음에도 오브젝트 연결의 역할까지 맡고있는 상황이다. 그러니 이것도 분리하자. 즉 분리될 기능은 UserDao와 ConnectionMaker 구현 클래스의 오브젝트를 만드는 것과, 그렇게 만들어지 두 개의 오브젝트가 연결돼서 사용될 수 있도록 관계를 맺어주는 것이다. ##### 팩토리 분리시킬 기능을 담당할 클래스를 하나 만들어보자. 이 클래스의 역할은 객체의 생성 방법을 결정하고 그렇게 만들어진 오브젝트를 돌려주는 것인데, 이런 일을 하는 오브젝트를 흔히 `팩토리(Factory)`라고 부른다. 팩토리 역할을 맡을 클래스를 지정하고, UserDaoTest에 담겨 있던 UserDao, ConnectionMaker 관련 생성 작업을 DaoFactory로 올기고, UserDaoTest에서는 DaoFactory에 요청해서 미리 만들어진 UserDao 오브젝트를 가져와 사용하게 만든다. > 팩토리 역할을 맡을 클래스 DaoFactory클래스 ```java package springbook.user.dao; public class DaoFactory { public UserDao userDao() { // 팩토리의 메소드는 UserDao 타입의 오브젝트를 어떻게 만들고, 어떻게 준비시킬지를 결정한다. ConnectionMaker connectionMaker = new DConnectionMaker(); UserDao userDao = new UserDao(connectionMaker); return userDao; } } ``` > 또한 DB커넥션 정보를 DaoFactory 클래스로 넘기면서 변화된 UserDaoTest 클래스도 살펴보자 ```java public class UserDaoTest { public static void main(String[] args) throws ClassNotFoundException, SQLException { UserDao dao = new UserDaoFactory().userDao(); ... } } ``` ##### 설계도로서의 팩토리 이렇게 분리된 오브젝트들의 역할과 관계를 분석해보자. - UserDao, ConnectionMaker : 애플리케이션의 핵심적인 **데이터 로직과 기술 로직**을 담당 - DaoFactory : 애플리케이션의 오브젝트들을 구성하고 그 **관계를 정의하는 책임** 전자가 실질적인 로직을 담당하는 컴포넌트라면, 후자는 애플리케이션을 구성하는 컴포넌트의 구조와 관계를 정의한 설계도 같은 역할을 한다고 볼 수 있다. > 여기서 말하는 '설계도'의 개념은 간단히 어떤 오브젝트가 어떤 오브젝트를 사용하는지를 정의해놓은 코드정도라고만 생각하자 이제 N사와 D사에 UserDao를 공급할 때 UserDao, ConnectionMaker와 함께 DaoFactory도 제공하면 된다. 새로운 ConnectionMaker 구현 클래스로 변경이 필요하면 DaoFactory를 수정해서 변경된 클래스를 생성해주도록 변경하면 되며, 핵심 기술(어디까지나 가정이다)이 담긴 UserDao는 변경이 필요없으므로 안전하게 소스코드를 보존할 수 있다. 동시에 DB연결 방식은 자유로운 확장이 가능하다. 이렇게 Factory를 통해 분리했을때 얻을 수 있는 장점은 매우 다양하지만 그중에서도, 애플리케이션의 컴포넌트 역할을 하는 오브젝트와 애플리케이션의 구조를 결정하는 오브젝트를 분리했다는 데 가장 의미가 있다. #### 오브젝트 팩토리의 활용 만약 DaoFactory에 UserDao가 아닌 다른 DAO의 생성기능을 넣으면 어떻게 될까? AccountDao, MessageDao 등을 만들었다고 해보자. ```java public class DaoFactory{ public UserDao userDao(){ return new UserDao(new DConnectionMaker()); } public AccountDao accountDao(){ return new AccountDao(new DConnectionMaker()); } public MessageDao messageDao(){ return new MessageDao(new DConnectionMaker()); } } ``` 딱 봐도 우리가 가장 처음에 메소드로 분리했던 DB커넥션정보가 중복되어 나타나고 있다. 이렇게 코드가 중복되는건 좋지 않은 현상이다. DAO가 지금보다 더 많아지면 Connection 의 구현 클래스를 바꿀 땜마다 모든 메소드를 일일히 수정해야 하기 때문이다. 중복 문제를 해결하려면 역시 분리해내는 게 가장 좋은 방법이다. ConnectionMaker의 구현 클래스를 결정하는 오브젝트를 만드는 코드를 별도의 메소드로 뽑아내고, DAO를 생성하는 각 메도스에서는 새로 만든 메소드를이용하도록 수정해보자 가장 처음에 했던 getConnection 메소드를 따로 만들어 DB연결 기능을 분리해낸 것과 동일한 리팩토링 방법이다. ```java public class DaoFactory{ public UserDao userDao(){ return new UserDao(ConnectionMaker()); } public AccountDao accountDao(){ return new AccountDao(ConnectionMaker()); } public MessageDao messageDao(){ return new MessageDao(ConnectionMaker()); } // 분리해서 중복을 제거한 ConnectionMaker 타입 오브젝트 생성 메소드 public ConnectionMaker connectionMaker(){ return new DConnectionMaker(); } } ``` #### 제어권의 이전을 통한 제어관계 역전 이제 제어의 역전이라는 개념에 대해 알아보자. > 제어의 역전이라는 건, 간단히 프로그램의 **제어 흐름 구조가 뒤바뀌는 것**이라고 설명할 수 있다. 일반적인 프로그램의 흐름을 살펴보면 각 오브젝트는 프로그램 흐름을 결정하거나 사용할 오브젝트를 구성하는 작업에 능동적으로 참여한다. 초기 UserDao를 보면 테스트용 main()메소드는 UserDao 클래스의 오브젝트를 직접 생성하고, 만들어진 오브젝트의 메소드를 사용한다. UserDao 또한 자신이 사용할 ConnectionMaker의 구현클래스(예를 들면 DConnectionMaker)를 자신이 결정하고, 그 오브젝트를 필요한 시점에서 생성해두고, 각 메소드에서 이를 사용한다. 즉!!! 모든 오브젝트가 능동적으로 자신이 사용할 클래스를 결정하고, 언제 어떻게 그 오브젝트를 만들지를 스스로 관장한다. **모든 종류의 작업을 사용하는 쪽에서 제어하는 구조다.** > `제어의 역전(Ioc)`이란 이런 제어 흐름의 개념을 거꾸로 뒤집는 것이다. 제어의 역전에서는 - 오브젝트가 자신이 사용할 오브젝트를 스스로 선택하지 않는다. - 당연히 생성하지도 않는다. - 자신도 어떻게 만들어지고 어디서 사용되는지를 알 수 없다. 바로 모든 제어권한을 자신이 아닌 다른 대상에게 위이하기 때문이다. main()과 같은 엔트리 포인트를 제외하면 **모든 오브젝트는 이렇게 위임받은 제어 권한을 갖는 특별한 오브젝트에 의해 결정되고 만들어진다.** - 서블릿도 이러한 개념이 적용되어 있다고 볼 수있다. - 템플릿 메소드 패턴도 이러한 개념을 활용해 문제를 해결하는 디자인 패턴이라고 불 수 있다. - **프레임워크는 제어의 역전 개념이 적용된 대표적인 기술이다** 1. 라이브러리 라이브러리를 사용하는 애플리케이션 코드는 애플리케이션 흐름을 직접 제어한다. 단지 동작하는 중에 필요한 기능이 있을 때 능동적으로 라이브러리를 사용할 뿐이다. 2. 프레임워크 프레임워크는 거꾸로 애플리케이션 코드가 프레임워크에 의해 사용된다. 보통 프레임워크 위에 개발한 클래스를 등록해두고, 프레임워크가 흐름을 주도하는 중에 개발자가 만든 애플리케이션 코드를 사용하도록 만드는 방식이다. **프레임워크에는 분명한 제어의 역전 개념이 적용되어 있어야 한다** 애플리케이션 코드는 프레임 워크가 짜놓은 틀에서 수동적으로 동작해야 한다. > 우리가 만든 UserDao와 DaoFactory에도 제어의 역전이 적용되어 있다. 원래 ConnectionMaker의 구현 클래스를 결정하고 오브젝트를 만드는 제어권은 UserDao에게 있었다. 그런데 지금은 DaoFactory에게 있다. 자신이 어떤 ConnectionMaker 구현 클래스를 만들고 사용할지를 결정할 권한을 DaoFactoryy에 넘겼으니 UserDao는 이제 능동적이 아니라 수동적인 존재가 됐다. UserDao 자신도 팩토리에 의해 수동적으로 만들어지고 자신이 사용할 오브젝트도 DaoFactory가 공급해주는 것을 수동적으로 사용해야 할 입장이 됐다. UserDaoTest는 DaoFactory가 만들고 초기화해서 자신에게 사용하도록 공급해주는 ConnectionMaker를 사용할 수 밖에 없다. 더욱이 UserDao와 ConnectionMaker의 구현체를 생성하는 책임도 DaoFactory가 맡고 있다. > 바로 이것이 제어의 역전(IoC)이 일어난 상황이다. > 자연스럽게 관심을 분리하고 책임을 나누고 유연하게 확장 가능한 구조로 만들기 위해 DaoFactory를 도입했던 과정이 바로 IoC를 적용하는 작업이었다고 볼 수 있다. 제어의 역전에서는 프레임워크 또는 컨테이너와 같이 애플리케이션 컴포넌트의 생성과 관계설정, 사용, 생명주기 관리등을 관장하는 존재가 필요하다. DaoFactory는 오브젝트 수준의 가장 단순한 IoC컨테이너 내지는 IoC프레임워크라고 불릴 수 있다. --- ### 스프링의 IoC 스프링의 핵심을 담당하는 건, 바로 빈 팩토리 또는 애플리케이션 컨텍스트라고 불리는 것이다. #### 오브젝트 팩토리를 이용한 스프링 IoC ###### 애플리케이션 컨텍스트와 설정정보 - 스프링에서는 스프링이 제어권을 가지고 직접 만들고 관계를 부여하는 오브젝트를 `빈(bean)`이라고 부른다. - 스프링 빈은 스프링컨테이너가 **생성과 관계설정, 사용 등을 제어해주는 제어의 역전이 적용된 오브젝트** 가리키는 말이다. - 빈의 생성과 관계설정 같은 제어를 담당하는 IoC오브젝트를 `빈 팩토리(bean factory)`라고 부른다. 보통 `빈 팩토리`보다는 이를 좀 더 확장한 `애플리케이션 컨텍스트(application context)`를 주로 사용한다. IoC방식을 따라 만들어진 일종의 빈 팩토리라고 생각하자 > 애플리케이션 컨텍스트 란? - 별도의 정보를 참고해서 빈(오브젝트)의 생성, 관계설정 등의 제어 작업을 총괄한다. - 기존 DaoFactory 코드에는 설정정보, 예를 들어 어떤 클래스의 오브젝트를 생성하고 어디에서 사용하도록 연결해줄 것인가 등에 관한 정보가 평버한 자바코드로 만들어져 있다. - 직접 이런 정보를 담고 있진 않다. - 별도로 설정정보를 담고 있는 무엇인가를 가져와 이를 활용하는 범용적인 IoC엔진 같은 것이라고 볼 수 있다. ###### DaoFactory를 사용하는 애플리케이션 컨텍스트 앞서 만든 DaoFactory를 스프링의 빈 팩토리가 사용할 수 있는 본격적인 설정정보로 만들어 보자. - 스프링이 빈팩토리를 위한 오브젝트 설정을 담당하는 클래스라고 인식할 수 있도록 `@Configuration` 이라는 어노테이션을 추가한다. - 오브젝트를 만들어 주는 메소드에는 `@Bean`이라는 어노테이션을 붙여준다. > 이와같이 변경한 아래고 소스는 자바코드지만 사실은 XML과 같은 스프링 전용 설정정보라고 보는 것이 좋다. > DoaFactory 클래스 ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; ... @Configuration -> 애플리케이션 컨텍스트 또는 빈팩토리가 사용할 설정정보라는 표시 public class DaoFactory{ @Bean public UserDao userDao(){ return new UserDao(ConnectionMaker()); } @Bean public ConnectionMaker connectionMaker(){ return new DConnectionMaker(); } } ``` > 이제 위의 DaoFactory를 설정정보로 사용하는 애플리케이션 컨텍스트를 만들어보자. - 애플리케이션 컨텍스트는 `ApplicationContext` 타입의 오브젝트다. - `ApplicationContext`를 구현한 클래스는 여러 가지가 있는데 DaoFactory 처러 `@Configuration`이 붙은 자바 코드를 설정정보로 사용하려면 `AnnotationConfigpplicaationContext`를 이용하면 된다. - 애플리케이션 컨텍스트를 만들 때 생성자 파라미터로 DaoFactory 클래스를 넣어준다. - 준비된 `ApplicationContext`의 getBean()이라는 메소드를 이용해 UserDao의 오브젝트를 가져올 수 있다. > 위 내용대로 UserDaoTest 를 애플리케이션 컨텍스트로 만들어 보자 ```java public class UserDaoTest{ public static void main(String[] args) throws ClassNotFoundException, SQLException{ ApplicaationContext context = new AnnotationConfigApplicationContext(DaoFactory.class); UserDao dao = context.getBean("userDao", UserDao.class); ... } } ``` `getBean()`메소드는 `ApplicationContext`가 관리하는 오브젝트를 요청하는 메소드다. `getBean()`의 파라밈터인 "userDao"는 ApplicationContext에 등록된 빈의 이름이다. DaoFactory()에서 @Bean이라는 어노테이션을 userDao라는 이름의 메소드에 붙였는데, 이 메소드 이름이 바로 빈의 이름이 된다. 즉, userDao라는 이름의 빈을 가져온다는 것은 DaoFactory의 userDao()메소드를 호출해서 그 결과를 가져온다고 생각하면 된다. > 그런데 UserDao를 가져오는 메소드는 하나뿐인데 왜 굳이 이름을 사용할까? 그것은 UserDao를 생성하는 방식이나 구성을 다르게 가져가는 메소드를 추가할 수 있기 때문이다. getBean()은 기본적으로 Object타입으로 리턴하게 되어 있어서 매번 리턴되는 오브젝트에 다시 캐스팅을 해줘야 하는데 제네릭을 사용해 getBean()의 두 번째 파라미터에 리턴타입을 주면, 지저분한 캐스팅 코드를 사용하지 않아도 된다. #### 애플리케이션 컨텍스트의 동작방식 기존에 오브젝트 팩토리를 이용했던 방식과 스프링의 애플리케이션 컨텍스트를 사용한 방식을 비교해보자 오브젝트 팩토리에 대응되는 것이 스프링의 애플리케이션 컨텍스트다. DaoFactory가 UserDao를 비롯한 DAO 오브젝트를 생성하고 DB 생성 오브젝트와 관계를 맺어주는 제한적인 역할을 하는 데 반해, 애플리케이션 컨텍스트는 애플리케이션에서 IoC를 적용해서 관리할 모든 오브젝트에 대한 생성과 관계설정을 담당한다. 대신 ApplicationContext에는 DaoFactory와 달리 직접 오브젝트를 생성하고 관계를 맺어주는 코드가 없고, 그런 생성정보와 연관관계정보를 별도의 설정정보를 통해 얻는다. `@Configuration`이 붙은 Daofactory는 이 애플리케이션 컨텍스트가 활용하는 IoC설정정보다. 내부적으로는 애플리케이션 컨텍스트가 DaoFactory의 userDao()메소드를 호출해서 오브젝트를 가져온 것을 클라이언트가 getBean()으로 요청할 때 전달해준다. 이렇게 DaoFactory를 오브젝트 팩토리로 직접 사용했을 때와 비교해서 애플리케이션 컨텍스트를 사용했을 때 얻을 수 있는 장점은 다음과 같다. - 클라이언트는 구체적인 팩토리 클래스를 알 필요가 없다 - 애플리케이션 컨텍스트는 종합 IoC 서비스를 제공해준다 - 오브젝트 생성과 관계설정만이 전부가 아니다. - 오브젝트가 만들어지는 방식 - 시점과 전략을 다르게 가져갈 수도 있다. - 이에 부가적으로 자동생성, 오브젝트에 대한 후처리, 정보의 조합, 설정 방식의 다변화등 오브젝트를 효과적으로 활용할 수 있는 다양한 기능을 제공한다. - 애플리케이션 컨텍스트는 빈을 검색하는 다양한 방법을 제공한다. --- ### 싱글톤 레지스트리와 오브젝트 스코프 애플리케이션 컨텍스트와 기존에 만들었던 오브젝트 팩토리와는 중요한 차이점이 있다. 먼저 DaoFactory의 userDao()메소드를 두 번 호출해서 리턴되는 UserDao오브젝트를 비교해보자 > 오브젝트의 동일성과 동등성에 관한 내용 ( p.103 참조) ```java DaoFactory factory = new DaoFactory(); UserDao dao1 = factory.userDao(); UserDao dao2 = factory.userDao(); System.out.println(dao1); System.out.println(dao2); ``` > 출력결과 ```java springbook.dao.UserDao@119f375 //주소값은 당연히 매번 달라진다. springbook.dao.UserDao@117a8bd ``` 출력 결과에서 알 수 있듯이, 두 개는 각기 다른 값을 가진 동일하지 않은 오브젝트다. userDao를 매번 호출하면 계속해서 새로운 오브젝트가 만들어질 것이다. 이번에는 애플리케이션 컨텍스트에 DaoFactory를 설정정보로 등록하고 getBean()메소드를 이용해 userDao라는 이름으로 등록된 오브젝트를 가져와 보자 ```java ApplicationContext context = new AnnotationConfigApplicationContext(DaoFactory.class); UserDao dao3 = context.getBean("userDao", UserDao.class); UserDao dao4 = context.getBean("userDao", UserDao.class); System.out.println(dao3); System.out.println(dao4); ``` > 출력결과 ```java springbook.dao.UserDao@ee9f375 springbook.dao.UserDao@ee9f375 ``` 출력결과를 보면 두 오브젝트의 값이 같음을 알수 있다. 즉 getBean()을 두 번 호출해서 가져온 오브젝트가 동일하다는 말이다. 이렇게 스프링은 여러 번에 걸쳐 빈을 요청하더라도 매번 동일한 오브젝트를 돌려준다. 단순하게 getBean()을 실행할 때마다 userDao()메소드를 호출하고, 매번 new에 의해 새로운 UserDao가 만들어지지 않는다는 뜻이다. > 그럼 여기서 의문...대체 왜?????? #### 싱글톤 레지스트리로서의 애플리케이션 컨텍스트 애플리케이션 컨텍스트는 우리가 만들었던 오브젝트 팩토리와 비슷한 방식으로 동작하는 IoC컨테이너다. 그러면서 동시에 이 애플리케이션 컨텍스트는 싱글톤을 저장하고 관리하는 싱글톤 레지스트리 이기도 하다. 스프링은 기본적으로 별다른 설정을 하지 않으면 내부에서 생성하는 빈 오브젝트를 모두 싱글톤으로 만든다. 주의할점은 여기서 싱글톤이라는 것은 디자인 패턴에서 나오는 싱글톤 패턴과 비슷한 개녀이지만 그 구현방법은 확연히 다르다. ##### 서버 애플리케이션과 싱글톤 왜 스프링은 싱글톤으로 빈을 만드는 것일까? - 스프링이 주로 적용되는 대상이 자바엔터프라이즈 기술을 사용하는 서버환경이기 때문이다. - 태생적으로 스프링은 엔터프라이즈 시스테을 위해 고안된 기술이기 때문에 서버 환경에서 사용될 때 그 가치가 있고, 실제로 스프링은 대부분 서버환경에서 사용된다. 스프링이 처음 설계됐던 대규모의 엔터프라이즈 서버환경은 **서버 하나당 최대로 초당 수십에서 수백 번씩 브라우저나 여타 시스템으로부터의 요청을 받아 처리할 수 있는 높은 성능이 요구되는 환경**이었고, 다양한 기능을 담당하는 오브젝트들이 차여하는 계층형 구조로 이뤄진 경우가 대부분이었다. 비즈니스 로직도 복잡하고... 그런데 매번 클라이언트에서 요청이 올 때마다 각 로직을 담당하는 오브젝트를 새로 만들어서 사용한다고 생각해보자.. 아무리 자바의 오브젝트 생성과 가비지 컬렉션의 성능이 좋아졌다고 한들 이렇게 **부하가 걸리면 서버가 감당하기 힘들다.** 이런 이유로 엔터프라이즈 분야에서는 서비스 오브젝트라는 개념을 일찍부터 사용해 왔다. **서블릿**은 자바 엔터프라이즈 기술의 가장 기본이 되는 서비스 오브젝트라고 할 수 있다. 스펙에서 강제하진 않지만, 서블릿은 대부분 멀티스레드 환경에서 싱글톤으로 동작한다. 서블릿 클래스당 하나의 오브젝트만 만들어 두고, 사용자의 요청을 담당하는 여러스레드에서 하나의 오브젝트를 공유해 동시에 사용한다. 이렇게 애플리케이션 안에 제한된 수 , 대개 한개의 오브젝트만 만들어서 사용하는 것이 싱글톤 패턴의 원리다. ##### 싱글톤 패턴의 한계 자바에서 싱글톤을 구현하는 방법은 보통 이렇다. - 클래스 밖에서는 오브젝트를 생성하지 못하도록 생성자를 private 으로 만든다. - 생성된 싱글톤 오브젝트를 저장할 수 있는 자신과 같은 타입의 스태틱 필드를 정의한다. - 스태틱 팩토리 메소드인 getInstance()를 만들고 이 메소드가 최초로 호출되는 시점에서 한번만 오브젝트가 만들어지게 한다. 생성된 오브젝트는 스태틱 필드에 저장된다. 또는 스태틱 필드의 초기값으로 오브젝트를 미리 만들어둘 수도 있다. - 한번 오브젝트(싱글톤)가 만들어지고 난 후에는 getInstance()메소드를 통해 이미 만들어져 스태틱 필드에 저장해둔 오브젝트를 넘겨준다. > UserDao를 전형적인 싱글톤 패턴을 이용해 만든다면 다음과 같이 될 것이다. ```java public class UserDao{ privte static UserDao INSTANCE; ... private UserDao(ConnectionMaker connectionMaker){ this.connectionMaker = connectionMaker; } public static synchronized UserDao getInstance(){ if(INSTANCE == null) INSTANCE = new UserDao(???); return INSTANCE; } ... } ``` 일단 깔끔하게 정리했던 UserDao에 싱글톤을 위한 코드가 추가되고 나니 코드가 상당히 지저분해졌다. 게다가 private으로 바뀐 생성자는 외부에서 호출 할 수가 없기 때문에 DaoFactory에서 UserDao를 생성하며 ConnectionMaker오브젝트를 넣어주는 게 이제는 불가능해졌다. > 여러모로 생각해봐도 지금까지 개선한 UserDao에 싱글톤 패턴을 도입하는 건 무리로 보인다. 일반적으로 싱글톤 패턴 구현 방식에는 다음과 같은 문제가 있다. - private 생성자를 갖고 있기 때문에 상속할 수 없다. - 싱글톤은 테스트하기가 힘들다 - 서버환경에서는 싱글톤이 하나만 만들어지는 것을 보장하지 못한다. - 싱글톤의 사용은 전역 상태를 만들 수 있기 때문에 바람직하지 못하다. ##### 싱글톤 레지스트리 스프링은 서버환경에서 싱글톤이 만들어져서 서비스 오브젝트 방식으로 사용되는 것은 적극 지지한다. 하지만 자바의 기본적인 싱글톤 패턴의 구현 방식은 여러가지 단점이 있기 때문에, 스프링은 직접 싱글톤 형태의 오브젝트를 만들고 관리하는 기능을 제공한다. 그것이 바로 `싱글톤 레지스트리(singleton registry)`다. 스프링 컨테이너는 싱글톤을 생성하고, 관리하고, 공급하는 싱글톤 관리 컨테이너이기도 하다. 싱글톤 레지스트리의 장점! - 스태틱 메소드와 `private` 생성자를 사용해야 하는 비정상적인 클래스가 아니라 평범한 자바 클래스를 싱글톤으로 활용하게 해준다. - 평범한 자바 클래스라고 IoC방식의 컨테이너를 사용해서 생성과 관계설정, 사용등에 대한 제어권을 컨테이너에게 넘기면 손쉽게 싱글톤 방식으로 만들어져 관리되게 할 수 있다. - 싱글톤 방식으로 사용될 어플리케이션 클래스라도 `public` 생성자를 가질 수 잇다. - 테스트 환경에서 자유롭게 오브젝트를 만들 수 있고, 테스트를 위한 목 오브젝트로 대체하는 것도 간단하다. - 생성자 파라미터를 이용해서 사용할 오브젝트를 넣어주게 할 수도 있다. - **가장 중요한 것은 싱글톤 패턴과 달리 스프링이 지지하는 객체지향적인 설계방식과 원칙, 디자인 패턴(싱글톤 패턴은 제외)등을 적용하는 데 아무런 제약이 없다는 점이다.** 즉 스프링은 **IoC컨테이너**일뿐만 아니라, 고전적인 싱글톤 패턴을 대신해서 싱글톤을 만들고 관리해주는 **싱글톤 레지스트리**라는 점을 기억하자. 스프링이 빈을 싱글톤으로 만드는 것은 결국 오브젝트의 생성방법을 제어하는 IoC컨테이너로서의 역할이다.. #### 싱글톤과 오브젝트의 상태 싱글톤은 멀테스레드 환경이라면 여러 쓰레드가 동시에 접근해서 사용할 수 있으므로 상태 관리에 주의를 기울여야 한다. - 기본적으로 싱글톤이 멀티스레드 환경에서 서비스 형태의 오브젝트로 사용되는 경우에는 상태정보를 내부에 갖고 있지 않은 무상태(stateless)방식으로 만들어져야 한다. > 그렇다면 상태가 없는 방식으로 클래스를 만드는 경우에 각 요청에 대한 정보나, DB나 서버의 리소스로부터 생성한 정보는 어떻게 다뤄야 할까? > 이때는 파라미터와 로컬변수, 리턴 값 등을 이용하면 된다. 메소드 파라미터나, 메소드 안에서 생성되는 로컬변수는 매번 새로운 값을 저장할 독립적인 공간이 만들어지기 때문에 싱글톤이라고 해도 여러 스레드가 변수의 값을 덮어쓸 일은 없다. > 인스턴스 변수를 사용하도록 수정한 UserDao ```java public class UserDao{ private ConnectionMaker connectionMaker; // 초기에 설정하면 사용 중에는 바뀌지 않는 읽기전용 인스턴스 변수 private Connection c; // 매번 새로운 값으로 바뀌는 정보를 담은 인스턴스 변수... private User user; // 심각한 문제가발생한다. public User get(String id) throws ClassNotFoundException, SQLException{ this.c = connectionMaker.makeConnection(); ... this.user = new User(); this.user.setId(rs.getString("id")); this.user.setName(rs.getString("name")); this.user.setPassword(rs.getString("password")); ... return this.user; } } ``` 기존에 만들었던 UserDao와 다른 점은 기존에 로컬변수로 선언하고 사용했던 Connection과 User를 클래스의 인스턴스 필드로 선언했다는 것이다. 따라서 싱글톤으로 만들어져서 멀티쓰레드 환경에서 사용하면 위에서 설명한 대로 심각한 문제가 발생한다. 따라서 스프링의 싱글톤 빈으로 사용되는 클래스를 만들 때는 기존의 UserDao처러 개별적으로 바뀌는 정보는 로컬 변수로 정의하거나, 파라미터로 주고받으면서 사용하게 해야 한다. 단 기존 UserDao의 ConnectionMaker 인터페이스 타입처럼 읽기전용의 정보는 인스턴스 변수로 정의해서 사용해도 된다. #### 스프링 빈의 스코프 스프링이 관리하는 오브젝트, 즉 빈이 생성되고, 존재하고, 적용되는 범위에 대해 알아보자 스프링에서는 이것을 빈의 **스코프(scope)**라고 한다. 스프링 빈의 기본 스코프는 싱글톤이다. 싱글톤 스코프는 컨테이너 내에 한 개의 오브젝트만 만들어져서, 강제로 제거하지 않는 한 스프링 컨테이너가 존재하는 동안 계속 유지된다. 대부분의 빈은 싱글톤 스코프를 갖지만, 그 외의 스코프를 가질 수 있다. 대표적으로 프로토타입 스코프가 있는데, 싱글톤과 달리 컨테이너에 빈을 요청할 때마다 매번 새로운 오브젝트를만들어 준다 물론 이 외에도 여러가지의 스코프가 있다 (싱글톤 외의 빈의 스코프에 대해서는 10장 참조) --- ### 의존관계 주입(DI) ##### 제어의 역전(IoC)과 의존관계 주입 IoC라는 용어는 매우 느슨하게 정의돼서 폭넓게 사용되는 언어라서, 스프링을 단순히 IoC 컨테이너라고만 해서는 스프링이 제공하는 기능의 특징을 명확하게 설명하지 못한다. 그래서 스프링이 제공하는 IoC 방식의 핵심을 짚어주는 `의존관게 주입(Dependency Injection)`이라는 이름이 등장했다. #### 런타임 의존관계 설정 ##### 의존관계 먼저 의존관계가 뭔지 부터 생각해보자 두 개의 클래스 또는 모듈이 의존관계에 있다고 말할 때는 항상 방향성을 부여해줘야 한다. 즉 누가 누구에게 의존하는 관계에 있다는 식이어야 한다. UML모델에서는 두 클래스의 `의존관계(dependency relationship)`를 점선으로 된 화살표로 표현한다. > 그렇다면 의존하고 있다는 건 무슨 의미일까? A가 B에 의존하고 있다고 생각해보자 만약 B가 변하면 그것이 A에 영향을미친다는 뜻이다. 더 자세히 예를 들어보면 A 에서 B에 정의된 메소드를 호출해서 사용하는 경우다. 의존관계에는 방향성이 있다고 했는데, 이때 B는 A에 의존하지 않으므로 A가 어떻게 변하든 B는 상관이 없다 ##### UserDao의 의존관계 지금까지 작업해왔던 UserDao의 예를 보자. UserDao가 ConnectionMaker에 의존하고 있는 형태다. 따라서 ConnectionMaker 인터페이스가 변한다면 그 영향을 UserDao가 직접적으로 받게된다. 하지만 ConnectionMaker 인터페이스를 구현한 클래스, 즉 DConnectionMaker 등이 다른것으로 바뀌거나 그 내부에서 사용하는 메소드에 변화가 생겨도 UserDao에 영향을 주지 않는다. 이렇게 인터페이스에 대해서만 의존관계를 만들어두면 인터페이스 구현 클래스와의 관계는 느슨해지면서 변화에 영향을 덜 받는 상태가 된다. 즉 결합도가 낮다고 설명할 수 있다. > 이렇게 인터페이스를 통해 의존관계를 제한해주면 그만큼 변경에서 자유로워지는 셈이다. 현재 UserDao는 DConnectionMaker 라는 클래스의 존재도 알지 못한다. 모델의 관점에서 보자면 UserDao는 DConnectionMaker 클래스에는 의존하지 않기 때문이다. UML에서 말하는 의존관계란 이러헥 설계 모델의 관점에서 이야기하는 것이다. 그런데! 모델이나 코드에서 클래스와 인터페이스를 통해 드러나는 의존관계 말고, 런타임 시에 오브젝트 사이에서 만들어지는 의존관계도 있다. `런타임 의존관계` 또는 `오브젝트 의존관계`인데, **설계 시점의 의존관계가 실체화된 것**이라고 볼 수있다. `런타임 의존관계`는 모델링 시점의 의존관계와는 성격이 분명히 다르다. 이때 프로그램이 시작되고 UserDao 오브젝트가 만들어지고 나서 런타임 시에 의존관계를 맺는 대상, 즉 실제 사용대상인 오브젝트를 `의존 오브젝트(dependent object)`라고 말한다. 의존관계 주입은 이렇게 구체적인 의존 프로젝트와 그것을 사용할 주체, 보통 클라이언트라고 부르는 오브젝트를 런타임 시에 연결해주는 작업을 말한다. 정리하면 의존관계 주입이란 다음과 같은 세가지 조건을 충족하는 작업을 말한다. - 클래스 모델이나 코드에는 런타이 시점의 의존관계가 드러나지 않는다. 그러기 위해서는 인터페이스에만 의존하고 있어야 한다. - 런타임 시점의 의존관계는 컨테이너나 팩토리 같은 제 3의 존재가 결정한다. - 의존관계는 사용할 오브젝트에 대한 레퍼런스를 외부에서 제공(주입)해줌으로써 만들어진다. > 여기서 `의존관계 주입`의 핵심은 설계 시점에는 알지 못했던 **두 오브젝트의 관계를 맺도록 도와주는 제3의 존재가 있다는 것**이다 - 전략패턴에 등장하는 클라이언트 - 앞에서 만들었던 DaoFactory - 스프링의 애플리케이션 컨텍스트, - 빈 팩토리 - IoC컨테이너 등이 모두 외부에서 오브젝트 사이의 런타이 관계를 맺어주는 책임을 지닌 제3의 존재라고 볼 수 있다. ##### UserDao의 의존관계 주입 UserDao에 적용된 의존관계 주입 기술을 다시 살펴보자 처음에 UserDao는 자신이 사용할 구체적인 클래스를 알고 있어야만 했다. 관계설정의 책임을 분리하기 전에 UserDao 클래스의 생성자를 다시한번 살펴보자 ```java public UserDao(){ connectionMaker = new DConnectionMaker(); } ``` 이 코드에 따르면 UserDao는 이미 설계 시점에서 DConnectionMaker라는 구체적인 클래스의 존재를 알고 있다. 즉 DConnectionMaker 오브젝트를 사용하겠다는 것까지 UserDao가 결정하고 관리하고 있는 셈이다. 이 코드의 문제는 이미 런타임 시의 의존관계가 코드 속에 다 미리 결정되어 있다는 점이었다. 그래서 IoC방식을 써서 UserDao로부터 런타임 의존관계를 드러내는 코드를 제거하고, 제3의 존재에 런타이 의존관계 결정 권한을 위임했고, 그렇게 해서 최종적으로 만들어진 것이 DaoFactory다. DaoFactory는 위에서 열거한 의존관계 주입의 세가지 조건을 모두 충족한다고 볼 수 있다. 그래서 DaoFactory는 `DI 컨테이너`다. DI 컨테이너는 UserDao를 만드는 시점에서 생성자의 파라미터로 이미만들어진 DConnectionMaker의 오브젝트를 전달한다. 정확히는 DConnectionMaker 오브젝트의 레퍼런스가 전달되는 것이다. 주입이라는 건 외부에서 내부로 무엇인가를 넘겨줘야 하는것인데, 자바에서 오브젝트에 무엇인가를 넣어준다는 개념은 메소드를 실행하면서 파라미터로 오브젝트의 레퍼런스를 전달해주는 방법뿐이다. 가장 손쉽게 사용할 수 있는 파라미터 전달이 가능한 메소드는 바로 생성자다. DI컨테이너는 자신이 결정한 의존관계를 맺어줄 클래스의 오브젝트를 만들고 이 생성자의 파라미터로 오브젝트의 레퍼런스를 전달해준다. 바로 다음의 코드가 이 과정의 작업을 위해 필요한 전형적인 코드다 ```java public class UserDao { private ConnectionMaker connectionMaker; public UserDao(ConnectionMaker simpleConnectionMaker) { this.connectionMaker = simpleConnectionMaker; } } ``` 이렇게 해서 두 개의 오브젝트 간에 런타임 의존관계가 만들어졌다. UserDao 오브젝트는 이제 생성자를 통해 주입받은 DConnectionMaker 오브젝트를 언제든지 사용하면 된다. 이렇게 DI컨테이너에 의해 런타임 시에 의존 오브젝트를 사용할 수 있도록 그 레퍼런스를 전달받는 과정이 마치 메소드(생성자)를 통해 DI 컨테이너가 UserDao에게 주입해 주는 것과 같다고 해서 이를 `의존관계 주입`이라고 부른다. DI는 자신이 사용할 오브젝트에 대한 선택과 생성 제어권을 외부로 넘기고 자신은 수동적으로 주입받은 오브젝트를 사용한다는 점에서 IoC의 개념에 잘 들어맞는다. 스프링 컨테이너의 IoC는 주로 의존관계 주입 또는 DI라는 데 초점이 맞춰져 있다.. 그래서 스프링을 IoC컨테이너 외에도 DI 컨테이너 또는 DI 프레임워크라고 부르는 것이다. #### 의존관계 검색과 주입 스프링이 제공하는 IoC방법에는 `의존관계 주입`만 있는 것이 아니다. 코드에서는 구체적인 클래스에 의존하지 않고, 런타임 시에 의존관계를 결정한다는 점에서 의존관계 주입과 비슷하지만, 의존관계를 맺는 방법이 외부로부터의 주입이 아니라 스스로 검색을 이용하기 때문에 `의존관계 검색(dependency lookup)`이라고 불리는 것도 있다. > 의존관계 검색은 자신이 필요로 하는 의존 오브젝트를 능동적으로 찾는다. 물론 이때 자신이 어떤 클래스의 오브젝트를 이용할지 결정하지는 않는다.(그러면 IoC라고 할 수 없겠찌) 즉, `의존관계 검색`은 `의존관계 주입`과 같이 런타임 시 의존관계를 맺을 오브젝트를 결정하는 것과 오브젝트의 생성작업은 외부 컨테이너에게 IoC로 맡기지만, 이를 ++**가져올 때는 메소드나 생성자를 통한 주입 대신 스스로 컨테이너에게 요청하는 방법을 사용한다.**++ > DaoFactory를 이용하는 생성자를 구성해보자 ```java public UserDao(){ DaoFactory daoFactory = new DaoFactory(); this.connectionMaker = daoFactory.connectionMaker(); } ``` 이렇게 소스를 변경해도 UserDao는 여전히 자신이 어떤 ConnectionMaker 오브젝트를 사용할지 미리 알지 못한다. 여전히 코드의 의존대상은 ConnectionMaker 인터페이스 뿐이다. 런타임 의존관계를 맺으며 IoC의 개념을 잘 따르고 있는 코드다. 하지만 적용방법은 외부로부터의 주입이 아니라 스스로 IoC컨테이너인 DaoFactory에게 요청하는 것이다. 스프링의 IoC컨테이너인 애플리케이션 컨텍스트는 `getBean()`이라는 메소드를 제공하는데, 바로 이 메소드가 의존관계 검색에 사용되는 것이다. > 애플리케이션 컨텍스트를 사용해서 의존관계 검색 방식으로 ConnectionMaker를 가져오도록 UserDao를 수정해보자 ```java public UserDao(){ AnnotationConfigApplictionContext context = new AnnotationConfigApplictionContext(DaoFactory.class); this.connectionMaker = context.getBean("connectionMaker", ConnectionMaker.class); } ``` `의존관계 검색`은 기존 의존관계 주입의 거의 모든 장저을 갖고 있다. 단 방법만이 조금 다를 뿐이다. 대개는 의존관계 주입 방식을 사용하는 편이 낫지만, 의존관계 검색방식을 사용해야 할 때가 있다. 앞에서 만들었던 테스트 코드인 UserDaoTest를 보자. 테스트 코드에서는 이미 의존관계 검색방식인 getBean()을 사용했다. 스프링의 IoC와 DI 컨테이너를 적용했다고 하더라도 애플리케이션의 기동시점에서 적어도 한 번은 의존관계 검색 방식을 사용해 오브젝트를 가져와야 한다. 스태틱 메소드인 main()에서는 DI를 이용해 오브젝트를 주입받을 방법이 없기 때문이다. 서버에서도 마찬가지다. `의존관계 검색`과 `의존관계 주입`을 적용할 때 발견할 수 있는 중요한 차이점이 하나 있는데, 의존관계 검색방식에서는 검색하는 오브젝트는 자신이 스프링의 빈일 필요가 없다는 점이다. 즉 ConnectionMaker만 스프링의 빈이기만 하면된다. 반면에 의존관계 주입에서는 UserDao와 ConnectionMaker 사이에 DI가 적용되려면 UserDao도 반드시 컨테이너가 만드는 빈 오브젝트여야 한다. 컨테이너가 UserDao에 ConnectionMaker 오브젝트를 주입해주려면 UserDao에 대한 생성과 초기화 권한을 갖고 있어야 하고, 그러려면 UserDao는 IoC방식으로 컨테이너에서 생성되는 오브젝트, 즉 빈이어야 하기 때문이다. 이런 점에서 DI와 DL(의존관계 검색)은 적용방법에 차이가 있다. > DI를 원하는 오브젝트는 먼저 자기 자신이 컨테이너가 관리하는 빈이 돼야 한다는 사실을 잊지 말자. #### 의존관계 주입의 응용 런타임 시에 사용 의존관계를 맺을 오브젝트를 주입해준다는 DI 기술의 장점은 무엇일까? 앞에서 살펴봤던 오브젝트 팩토리가 바로 DI 방식을 구현한 것이니, 앞에서 설명한 모든 객체지향 설계와 프로그래밍의 원칙을 따랏을 때 얻을 수 있는 장점이 그대로 DI기술에도 적용될 것이다. 스프링이 제공하는 기능의 99%가 DI의 혜택을 이용하고 있다. ##### 기능 구현의 교환 실제 운영에 들어가기전 개발시점에서는 개발자 PC에 설치된 로컬 DB로 사용해야 한다고 해보자. 그리고 개발이 완료되면 운영서버로 배치를 해야 하는데 이때 DI방식을 적용하지 않았다고 가정해보자. 개발중에는 로컬DB를 사용하도록하는 클래스를 만들어서 사용했을 것이고, 이 클래스는 모든 DAO에 들어있을 것이다. DB연결정보를 운영서버의 데이터베이스로 하기 위해서는 이를 모두 수정해야 하는 문제가 생기는 것이다. 반면 DI방식을 적용해서 만들었다면 모든 DAO는 생성시접에 ConnectionMaker 타입의 오브젝트를 컨테이너로부터 제공받는다. 구체적인 사용 클래스 이름은 컨테이너가 사용할 설정정보에 들어 있다. @Configuration 이 붙은 DaoFactory를 사용한다고 하면 개발자 PC에서는 DaoFactory의 코드를 다음과 같이 만들어서 사용하면 된다. > 개발용 ConnectionMaker 생성코드 ```java @Bean public ConnectionMaker connectionMaker(){ return new LocalDBConnectionMaker(); } ``` 이를 서버에 배포할 때는 어떤 DAO클래스와 코드도 수정할 필요가 없다. 단지 서버에서 사용할 DaoFactory를 다음과 같이 수정해주기만 하면 된다. > 운영용 ConnectionMaker 생성코드 ```java public ConnectionMaker connectionMaker(){ return new ProdeuctionDBConectionMaker(); } ``` ##### 부가기능 추가 DAO가 DB를 얼마나 많이 연결해서 사용하는지 파악하고 싶다고 해보자. DB연결횟수를 카운팅하기 위해 무식한 방법으로, 모든 DAO의 makeConnection() 메소드를 호출하는 부분에 새로 추가한 카운터를 증가시키는 코드를 넣어야 할까? 이런 DB연결횟수를 세는 일은 DAO의 관심사항이 아니다. 어떻게든 분리돼야 할 책임이기도 하다 DI 컨테이너에서라면 아주 간단한 방법으로 가능하다. DAO와, DB커넥션을 만드는 오브젝트 사이에 연결횟수를 카운팅하는 오브젝트를 하나 더 추가하는 것이다. DI를 이용한다고 했으니 당연히 기존 코드는 수정하지 않아도 된다. > CountingConnectionMaker 라는 클래스 리스트트 다음과 같이 만들어보자 > 이때 중요한 것은 ConnectionMaker 인터페이스를 구현해서 만든다는 점이다. > DAO가 의존할 대상이 될 것이기 때문이다. ```java public class CountingConnectionMaker implements ConnectionMaker { int counter = 0; private ConnectionMaker realConnectionMaker; public CountingConnectionMaker(ConnectionMaker realConnectionMaker) { this.realConnectionMaker = realConnectionMaker; } public Connection makeConnection() throws ClassNotFoundException, SQLException { this.counter++; return realConnectionMaker.makeConnection(); } public int getCounter() { return this.counter; } } ``` CountingConnectionMaker 클래스는 ConnectionMaker 인터페이스를 구현했지만 내부에서 직접 DB커넥션을 만들지 않는다. 대신 DAO가 DB 커텍션을 가져올 때마다 호출하는 makerConnection()에서 DB 연결횟수 카운터를 장가시킨다. CountingConnectionMaker는 자신의 관심사인 DB 연결횟수 카운팅 작업을 마치면 실제 DB커넥션을 만들어주는 `relConnectionMaker`에 저장된 `ConnectionMaker` 타입 오브젝트의 makeConnection()을 호출해서 그 결과를 DAO에게 돌려준다. 그래야만 DAO가 DB 커넥션을 사용해서 정상적으로 동작할 수 있다. 생성자를 보면 CountingConnectionMaker도 DI를 받는 것을 알 수 있다. CountinConnectionMaker의 오브젝트가 DI 받을 오브젝트도 역시 ConnectionMaker 인터페이스를 구현한 오브젝트다 아마 실제 DB 커넥션을 돌려주는 DConnectionMaker 클래스의 오브젝트일 것이다. CountinConnectionMaker가 추가되면서 런타임 의존관계가 어떻게 바뀌는지 살펴보자. CountinConnectionMaker를 사용하기 전의 런타임 의존관계를 보면 UserDao 오브젝트는 ConnectionMaker 타입의 DConnectionMaker 오브젝트에 의존한다. UserDao는 ConnectionMaker 의 인터페이스에만 의존하고 있기 때문에, ConnectionMaker 인터페이스를 구현하고 있다면 어떤 것이든 DI가 가능하다. 그래서 UserDao 오브젝트가 DI 받는 대상의 설정을 조정해서 DConnection 오브젝트 대신 CountingConnectionMaker 오브젝트로 바꿔치기 하는 것이다. 이렇게 해두면 UserDao()가 DB커넥션을 가져오려고 할 때마다 CountingConnectionMaker의 makeConnection()메소드가 실행되고 카운터는 하나씩 증가할 것이다. > 그럼 여기서 의문 기존의 DConnection을 카운팅 메소드로 대체했으니 DB커넥션정보를 다시 제공해줘야 되지 않을까? 그래서 CountingConnectionMaker가 다시 실제 사용할 DB커넥션을 제공해주는 DConnectionMaker를 호출하도록 만들어야 한다. 역시 DI를 사용하면 된다. 이 의존관계를 표현해보면 다음과 같다 `UserDao` -> `CountingConnectionMaker` -> `DConnectionMaker` > 새로운 의존관계를 담은 설정용 CountingDaoFactory 클래스 ```java packge springbook.user.dao; ... @Configuration public class CountingDaoFactory{ @Bean public UserDao userDao(){ return new UserDao(connectionMaker()); } @Bean public ConnectionMaker connectionMaker(){ return new CountingConnectionMaker(realConnectionMaker()); } @Bean public ConnectionMaker realConnectionMaker(){ return new DConnectionMaker(); } } ``` 이제 커넥션 카운팅을 위한 실행코드를 만들어보자. 기본적으로 UserDaoTest와 같지만 설정용 클래스를 CountingDaoFactory로 변경해줘야 한다. DAO를 DL 방식으로 가져와 어떤 작업이든 여러 번 실행시킨다. (테스트를 위해 그냥 0~9까지 10번 for문으로 돌렸음) 설정정보에 지정된 이름과 타입만 알면 특정 빈을 가져올 수 있으니 CountingConnectionMaker 오브젝트를 가져오는 건 간단하다. 지금은 DAO가 하나뿐이지만 DAO가 수십, 수백 개여도 상관없다. DI의 장점은 관심사의 분리(SoC)를 통해 얻어지는 높은 응집도에서 나온다. 모든 DAO가 직접 의존해서 사용할 ConnectionMaker 타입 오브젝트는 connectionMaker()메소드에서 만든다. 따라서 CountingConnectionMaker의 의존관계를 추가하려면 이 메소드만 수정하면 그만ㅊ이다. 또한 CountingConnectionMaker 를 이용한 분석작업이 모두 끝나면, 다시 CountingDaoFactory 설정 클래스를 DaoFactory로 변경하거나 connectionMaker()메소드를 수정하는 것만으로 DAO의 런타이 의존관계는 이전 상태로 복구된다. #### 메소드를 이용한 의존관계 주입 지금까지는 UserDao의 의존관계 주입을 위해 생성자를 사용했다. 생성자에 파라미터를 만들어두고 이를 통해 DI 컨테이너가 의존할 오브젝트 레퍼런스를 넘겨주도록 만들었다. 그런데 의존관계 주입 시 반드시 생성자를 사용해야 하는 것은 아니다. 생성자가 아닌 일반 메소드를 사용할 수도 있을 뿐만 아니라, 생성자를 사용하는 방법보다 더 자주 사용된다. > 생성자가 아닌 일반 메소드를 이용해 의존 오브젝트와의 관계를 주입해주는 데는 크게 두 가지 방법이 있다. - 수정자 메소드를 이용한 주입 - 일반 메소드를 이용한 주입 여기서 생성자가 수정자 메소드보다 나은 점은 한 번에 여러개의 파라미터를 받을 수 있다는 점이다. 하지만 파라미터의 개수가 많아지고 비슷한 타입이 여러개라면 실수하기 쉽다. 임의의 초기화 메소드를 이용하는 DI는 적절한 개수의 파라미터를 가진 여러 개의 초기화 메소드를 만들 수도 있기 때문에 한 번에 모든 필요한 파라미터를 다 받아야 하는 생성자보다 낫다. > 스프링은 전통적으로 메소드를 이용한 DI 방법 중에서 수정자 메소드를 가장 많이 사용해왔다. > 뒤에서 보겠지만 DaoFactory 같은 자바 코드 대신 XML을 사용하는 경우에는 자바빈 규약을 따르는 수정자 메소드가 가장 사용하기 편리하다. 수정자 메소드 DI를 사용할 때는 메소드의 이름을 잘 결정하는 게 중요하다. 만약 이름을 짓는 게 귀찮다면 메소드를 통해 DI받을 오브젝트의 타입 이름을 따르는 것이 가장 무난하다. > 예를 들어 ConnectionMaker 인터페이스 타입의 오브젝트를 DI받는다면 메소드의 이름은 setConnectionMaker()라고 ~ UserDao도 수정자 메소드를 이용해 DI 하도록 만들어보자. - 기존 생성자는 제거한다. - 생성자를 대신할 setConnectionMaker()라는 메소드를 하나 추가하고 파라미터로 ConnectionMaker 타입의 오브젝트를 받도록 선언한다. - 파라미터로 받은 오브젝트는 인스턴스 변수에 저장해두도록 만든다. 대부분의 IDE는 수정자 메소드를 자동생성하는 기능이 있다. - 인스턴스 변수만 정의해두고 자동생성 기능을 사용하면 편리하다 > 수정자 메소드 DI를 적용한 UserDao ```java public class UserDao{ private ConnectionMaker connectionMaker; public void setConnectionMaker(ConnectionMaker connectionMaker){ this.connectionMaker = connectionMaker; } ... // 위 코드는 수정자 메소드 DI의 전형적인 코드다 잘 기억해두자 } ``` UserDao를 수정자 메소드 DI 방식이 가능하도록 변경했으니 DI를 적용하는 DaoFactory의 코드도 함께 수정해줘야 한다. > 수정자 메소드 DI를 사용하는 팩토리 메소드 DaoFactory ```java @Bean public UserDao userDao() { UserDao userDao = new UserDao(); userDao.setConnectionMaker(connectionMaker()); return userDao; } ``` 단지 의존관계를 주입하는 시점과 방법이 달라졌을 뿐 결과는 동일하다 스프링은 생성자, 수정자 메소드, 초기화 메소드를 이용한 방법 외에도 다양한 의존관계 주입 방법을 지원한다. (이는 Vol. 2를 참조) --- ### XML을 이용한 설정 스프링은 DaoFactory와 같은 자바 클래스를 이용하는 것 외에도, 다양한 방법을 통해 DI의존관계 설정정보를 만들 수 있는데, 가장 대표적인 것이 바로 XML이다. XML은 단순한 텍스트파일이기 때문에 다루기 쉬우며, 자바코드와 달리 컴파일과 같은 별도의 빌드 작업도 필요없다는 장점이 있다. 이제 DaoFactory 자바 코드에 담겨있던 DI를 위한 오브젝트 의존관계 정보를 XML을 이용해서 만들어 보자 #### XML 설정 스프링의 애플리케이션 컨텍스트는 XML에 담긴 DI 정보를 활용할 수 있다. DI 정보가 담긴 XML 파일은 `<beans>`를 루트 엘리먼트로 사용한다. 이름에서 알 수 있듯이 `<beans>`안에는 여러개의 `<bean>`을 정의할 수 있다. XML 설정은 `@Configuration`과 `@Bean`이 붙은 자바 클래스로 만든 설정과 내용이 동일하다. - `@Configuration` = `<beans>` - `@Bean` = `<bean>` 위와 같이 대응해서 생각하자 하나의 `@Bean`메소드를 통해 얻을 수 있는 빈의 DI 정보는 다음 세가지가 - 빈의 이름 : `@Bean`메소드 이름이 빈의 이름이다. 이 이름은 `getBean()`에서 사용된다. - 빈의 클래스 : 빈오브젝트를 어떤 클래스를 이용해서 만들지를 정의한다. - 빈의 의존 오브젝트 : 빈의 생성자나 수정자 메소드를 통해 의존 오브젝트를 넣어준다. 의존 오브젝트도 하나의 빈이므로 이름이 있을 것이고, 그 이름에 해당하는 메소드를 호출해서 의존 오브젝트를 가져온다. 의존 오브젝트는 하나 이상일 수도 있다. XML 에서 `<bean>`을 사용해도 이 세가지 정보를 정의할 수 있다. ConnectionMaker 처럼 더 이상 의존하고 있는 오브젝트가 없는 경우에는 세 번째 의존 오브젝트 정보는 생략할 수 있다. ##### connectionMaker() 전환 먼저 DaoFactory의 connectionMaker()메소드에 해당하는 빈을 XML로 정의해보자. connectionMaker()로 정의되는 빈은 의존하는 다른 오브젝트는 없으니 DI정보 세 가지중 두 가지만 있으면 된다. | | 자바 코드 설정정보 | XML 설정정보 |--------|--------|------- | 빈 설정파일 | @Configuration | `<beans>` | 빈의 이름 | @Bean methodName() | `<bean id="methodName">` | 빈의 클래스 | return new BeanClass(); | `<bean class="a.b.c...BeanClass">` DaoFactory의 @Bean 메소드에 담긴 정보를 1:1로 XML의 태그와 애트리뷰트로 전환해주기만 하면 된다. 단 `<bean>`태그의 class 애트리뷰트에 지정하는 것은 자바 메소드에서 오브젝트를 만들때 사용하는 클래스 이름이라는 점에 주의하자. - XML에서는 리턴하는 타입을 지정하지 않아도 된다. - class 애트리뷰터에 넣을 클래스 이름은 패키지까지 모두 포함해야 한다. 이제 connectionMaker()메소드를 `<bean>`태그로 전환해보자. ```xml <bean id="connectionMaker" class="springbook.user.dao.DConnectionMaker"></bean> ``` ##### userDao() 전환 이번에는 userDao 메소드를 XML로 변환해보자 userDao()에는 DI 정보의 세 가지 요소가 모두 들어 있다. 여기서 관심을 가질 것은 수정자 메소드를 사용해 의존관계를 주입해주는 부분이다. 스프링 개발자가 수정자 메소드를 선호하는 이유 중에는 XML로 의존관계 정보를 만들 떄 편리하다는 점도 있따. 자바반의 관례를 따라서 수정자 메소드는 프로퍼티가 된다. 프로퍼티 이름은 메소드 이름에서 set을 제외한 나머지 부분을 사용한다. 예를 들어 오브젝트에 setConnectionMaker()라는 이름의 메소드가 있다면 connectionMaker라는 프로퍼티를 갖는다고 할 수 있다. XML에서는 `<property>` 태그를 사용해 의존 오브젝트와의 관계를 정의한다. `<property>`태그는 name과 ref라는 두 개의 애트리뷰트를 갖는다. - name : 프로퍼티의 이름으로, name을 통해 수정자 메소드를 알 수 있다. - ref : 수정자 메소드를 통해 주입해줄 오브젝트의 빈 이름이다. DI할 오브젝트도 역시 빈 이므로 그 빈의 이름을 지정해주면 된다. 만약 `@Bean`메소드에서라면 다음과 같이 지정을 한다. ```java userDao.setConnectionMaker(connectionMaker()); ``` 여기서 userDao.setConnectionMaker()는 userDao 빈의 connectionMaker 프로퍼티를 이용해 의존관계 정보를 주입한다는 뜻이다. 메소드의 파라미터로 넣는 connectionMaker()는 connectionMaker()메소드를 호출해서 리턴하는 오브젝트를 주입하라는 의미다. 바로 이 두가지 정보를 `<property>`의 name 애트리뷰트와 ref 애트리뷰트로 지정해주면 된다. 그 후 이 프로퍼티 태그를 userDao빈을 정의한 `<bean>`태그 안에 넣어주면 된다 ```xml <bean id="userDao" class="springbook.dao.UserDao"> <property name="connectionMaker" ref="connectionMaker" /> </bean> ``` ##### XML의 의존관계 주입 정보 이렇게 해서 두 개의 <bean> 태그를 이용해 @Bean 메소드를 모두 XML로 변환했다. 다음과 같이 `<beans>`로 전환한 두 개의 `<bean>` 태그를 감싸주면 DaoFactory로부터 XML로의 전환 작업이 끝난다. ```xml <beans> <bean id="connectionMaker" class="springbook.user.dao.DConnectionMaker" /> <bean id="userDao" class="springbook.user.dao.UserDao"> <property name="connectionMaker" ref="connectionMaker" /> </bean> </beans> ``` 여기서 `<property>` 태그의 name과 ref는 그 의미가 다르므로 이름이 같아서 헷갈릴수 있는데, 이 둘이 어떤 차이가 있는지 구별할 수 있어야 한다. - name : DI에 사용할 수정자 메소드의 프로퍼티 이름 - ref : 주입할 오브젝트를 정의한 빈의 ID다. 보통 프로퍼티 이름과 DI되는 빈의 이름이 같은 경우가 많다. 프로퍼티 이름은 주입할 빈 오브젝트의 인터페이스를 따르는 경우가 많고, 빈 이름도 역시 인터페이스 이름을 사용하는 경우가 많기 때문이다. 때로는 같은 인터페이스를 구현한 의존 오브젝트를 여러 개 정의해두고 그중에서 원하는 걸 골라서 DI하는 경우도 있다. 이때는 각 빈의 이름을 독립적으로 만들어두고 ref애트리뷰트를 이용해 DI 받을 빈을 지정해주면 된다. ```xml <beans> <bean id="localDBConnectionMaker" class="package...LocalDBConnectionMaker" /> <bean id="testDBConnectionMaker" class="package...TestDBConnectionMaker" /> <bean id="productionDBConnectionMaker" class="package...ProductionDBConnectionMaker" /> <bean id="userDao" class="springbook.user.dao.UserDao"> <property name="connectionMaker" ref="localDBConnectionMaker" /> </bean> </beans> ``` #### XML을 이용하는 애플리케이션 컨텍스트 애플리케이션 컨텍스트가 DaoFactory 대신 XML 설정정보를 활용하도록 만들어보자 XML에서 빈의 의존관계 정보를 이용하는 IoC/DI 작업에는 GenericXmlApplicationContext를 사용한다. GenericXmlApplicationContext의 생성자 파라미터로 XML 파일의 클래스패스를 지정해주면 된다. 이 설정파일은 클래스패스 최상단에 두면 편하다. 애플리케이션 컨텍스트가 사용하는 XML 설정파일의 이름은 관례를 따라 applicationContext.xml 이라고 만든다. ```xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="myConnectionMaker" class="springbook.user.dao.DConnectionMaker"> <property name="driverClass" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost/springbook?characterEncoding=UTF-8" /> <property name="username" value="spring" /> <property name="password" value="<PASSWORD>" /> </bean> <bean id="userDao" class="springbook.user.dao.UserDao"> <property name="connectionMaker" ref="myConnectionMaker" /> </bean> </beans> ``` xml 설정정보를 담은 applicationContext.xml 파일을 생성했으니 UserDaoTest의 애플리케이션 컨텍스트 생성부분을 수정해줘야 한다. DaoFactory를 설정정보로 사용했을 때 썻던 AnnotationConfigApplicationContext 대신 GenericXmlApplicationContext를 이용해 다음과 같이 애플리케이션 컨텍스트를 생성하게 만든다. 이때 생성자에는 applicationContext.xml의 클래스패스를 넣는다. > `/`는 넣을 수도 있고 생략할 수도 있는데 시작하는 `/`가 없는 경우에도 항상 루트에서부터 시작하는 클래스패스라는 점을 기억해두자 ```java ApplicationContext context = new GenericXmlApplicationContext("/applicationContext.xml"); ``` 위처럼 GenericXmlApplicationContext 외에도 ClassPathXmlApplicationContext 를 이용해 XML로부터 설정정보를 가져오는 애플리케이션 컨텍스트를 만들 수 있다. GenericXmlApplicationContext 는 클래스패스뿐 아니라 다양한 소스로부터 설정파일을 읽어올 수 있다. 위에서 언급한 ClassPathXmlApplicationContext는 XML파일을 클래스패스에서 가져올 때 사용할 수 있는 편리한 기능이 추가된 것이다. 또한 클래스패스의 경로정보를 클래스에서 가져오게 하는 것이 있다. 예를 들어 springbook.user.doa 패키지 안에 daoContext.xml 이라는 설정파일을 만들었다고 해보자. GenericXmlApplicationContext가 이 XML 설정파일을 사용하게 하려면 클래스패스 루트로부터 파일의 위치를 지정해야 하므로 다음과 같이 작성해야 한다. ```java new GenericXmlApplicationContext("springbook/user/doa/daoContext.xml"); ``` 반면에 ClassPathXmlApplicationContext는 XML 파일와 같은 클래스패스에 있는 클래스 오브젝트를 넘겨서 클래스패스에 대한 힌트를 제공할 수 있다. UserDao는 springbook.user.dao 패키지에 있으므로 daoContext.xml과 같은 클래스패스 위에 있다. 이 UserDao를 함께 넣어주면 XML 파일의 위치를 UserDao의 위치로부터 상대적으로 지정할 수 있다. ```java new ClassPathXmlApplicationContext("daoContext.xml", UserDao.class); ``` 이 방법으로 클래스패스를 지정해야 할 경우가 아니라면 GenericXmlApplicationContext를 사용하는 편이 무난하다. #### DataSource 인터페이스로 변환 ##### DataSource 인터페이스 적용 ConnectionMaker 는 DB 커넥션을 생성해주는 기능 하나만을 정의한 매우 단순한 인터페이스다. IoC와 DI의 개념을 설명하기 위해 직접 이 인터페이스를 정의하고 사용했지만, 사실 자바에서는 DB커넥션을 가져오는 오브젝트의 기능을 추상화해서 비슷한 용도로 사용할 수 있게 만들어진 DataSource라는 인터페이스가 이미 존재한다. 단, DataSource는 getConnection()이라는 DB커넥션을 가져오는 기능 외에도 여러 개의 메소드를 갖고 있어서 인터페이스를 직접 구현하기는 부담스럽다. 사실 일반적으로 DataSource를 구현해서 DB커넥션을 제공하는 클래스를 만들지는 않고, 이미 다양한 방법으로 DB연결과 풀링 기능을 갖춘 많은 DataSource 구현 클래스가 존재하고, 이를 가져다 사용하면 충분하다. > DataSource 인터페이스와 다양한 DataSource 구현 클래스를 사용할 수 있도록 UserDao를 리팩토링해보자 - UserDao에 주입될 의존 오브젝트의 타입을 ConnectionMaker에서 DataSource로 변경한다. - DB커넥션을 가져오는 코드를 makeConnection()에서 getConnection() 메소드로 바꿔준다. ```java public class UserDao { private DataSource dataSource; public void setDataSource(DataSource dataSource){ this.dataSource = dataSource; } public void add(User user) throws ClassNotFoundException, SQLException { Connection c = dataSource.getConnection(); ... } ``` 다음으로 DataSource 구현 클래스가 필요하다 ##### 자바 코드 설정 방식 먼저 DaoFactory 설정 방식을 이용해보자. - 기존의 connectionMaker() 메소드를 dataSource()로 변경하고, SimpleDriverDataSource 의 오브젝트를 리턴하게 한다. - 이 오브젝트를 넘기기 전에 DB연결과 관련된 정보를 수정자 메소드를 이용해 지정해줘야 한다. > DataSource 타입의 dataSource 빈 정의 메소드 ```java @Bean public DataSource dataSource() { SimpleDriverDataSource dataSource = new SimpleDriverDataSource (); dataSource.setDriverClass(com.mysql.jdbc.Driver.class); dataSource.setUrl("jdbc:mysql://localhost/springbook?characterEncoding=UTF-8"); dataSource.setUsername("root"); dataSource.setPassword("<PASSWORD>"); return dataSource; } ``` 또한 DaoFactory의 userDao()메소드를 UserDao는 이제 DataSource 타입의 dataSource()를 DI 받도록 수정하자 ```java @Bean public UserDao userDao() { UserDao userDao = new UserDao(); userDao.setDataSource(dataSource()); return userDao; } ``` 이렇게 해서 UserDao에 DataSource 인터페이스를 적용하고 SimpleDriverDataSource 오브젝트를 DI로 주입해서 사용할 수 있는 준비가 끝났다. 이제 UserDaoTest 를 DaoFactory를 사용하도록 수정하고 테스트를 실행해보자 ##### XML 설정방식 이번에는 XML 설정 방식으로 변경해보자. - id가 connectionMaker인 `<bean>`을 없애고 dataSource라는 이름의 `<bean>`을 등록한다. - 클래스를 SimpleDriverDataSource로 변경해준다. ```xml <bean id="dataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource" /> ``` 그런데 문제는 이 `<bean>`설정으로 `SimpleDriverDataSource`의 오브젝트를 만드는 것까지는 가능하지만, dataSource()메소드에서 SimpleDriverDataSource 오브젝트의 수정자로 넣어준 DB접속정보는 나타나 있지 않다는 점이다. UserDao처럼 다른 빈에 의존하는 경우에는 `<property>`태그와 ref 애트리뷰트로 의존할 빈 이름을 넣어주면 된다. 하지만 SimpleDriverDataSource 오브젝트의 경우는 단순 Class 타입의 오브젝트나 텍스트 값이다. > 그렇다면 XML에서는 어떻게 해서 dataSource()메소드에서처럼 DB연결정보를 넣도록 설정을 만들 수 있을까? #### 프로퍼티 값의 주입 ##### 값 주입 이미 DaoFactory의 dataSource()메소드에서 본 것처럼, 수정자 메소드에는 다른 빈이나 오브젝트뿐 아니라 스트링 같은 단순 값을 넣어줄 수도 있다. setDriverClass()메소드의 경우에는 Class 타입의 오브젝트이긴 하지만 다른 빈 오브젝트를 DI방식으로 가져와서 넣는 것은 아니다. > 이렇게 다른 빈 오브젝트의 레퍼런스가 아닌 단순 정보도 오브젝트를 초기화하는 과정에서 수정자 메소드에 넣을 수 있다. 이때는 DI에서처럼 오브젝트의 구현 클래스를 다이나믹하게 바꿀 수 있게 해주는 것이 목적은 아니다. 대신 클래스 외부에서 DB연결정보와 같이 변경가능한 정보를 설정해줄 수 있도록 만들기 위해서다. 예를 들어 DB접속 아이디가 바뀌었더라도 클래스 코드는 수정해줄 필요가 없게 해주는 것이다. **텍스트나 단순 오브젝트 등을 수정자 메소드에 넣어주는 것을 스프링에서는 '값을 주입한다'**고 말한다. 이것도 성격은 다르지만 일종의 DI라고 볼 수 있다. 스프링의 빈으로 등록될 클래스에 수정자 메소드가 정의되어있다면 `<property>`를 사용해 주입할 정보를 지정할 수 있다는 점에서는 `<property ref="">`와 동일하다. > 하지만 **다른 빈 오브젝트의 `레퍼런스(ref)`가 아니라 단순 `값(value)`을 주입해주는 것**이기 때문에 ref애트리뷰트 대신 value애트리뷰트를 사용한다. 따라서 dataSource()메소드에서 다음과 같이 수정자 메소드를 호출해서 DB연결정보를 넣었던 아래의 코드는 ```java dataSource.setDriverClass(com.mysql.jdbc.Driver.class); dataSource.setUrl("jdbc:mysql://localhost/springbook?characterEncoding=UTF-8"); dataSource.setUsername("root"); dataSource.setPassword("<PASSWORD>"); ``` 아래처럼 XML로 전환할 수 있다. ```xml <property name="driverClass" ref="com.mysql.jdbc.Driver" /> <property name="url" ref="jdbc:mysql://localhost/springbook" /> <property name="username" ref="root" /> <property name="password" ref="<PASSWORD>" /> ``` `ref` 대신에 `value`를 사용했을 뿐이지 기존의 `<property>`태그를 사용했던 것과 내용과 방법은 동일하다. 주의할점은 `value`에 들어가는 것은 다른 빈의 이름이 아니라 실제로 수정자 메소드의 파라미터로 전달되는 스트링 그 자체다 ##### value값의 자동 변환 그런데 한 가지 이상한 점이 있다. url, username, password는 모두 스트링 타입이니 원래 텍스트로 정의되는 value애트리뷰트의 값을 사용하는 것은 문제 없다. 그런데 `driverClass` 는 스트링 타입이 아니라 `java.lang.Class`타입이다. `DaoFactory`에 적용한 예를 생각해보면 Driver.class라는 `Class` 타입 오브젝트를 전달한다. ```java dataSource.setDriverClass(com.mysql.jdbc.Driver.class); ``` 그런데 XML에서는 별다른 타입정보 없이 클래스의 이름이 텍스트 형태로 `value`에 들어가 있다. 하지만 테스트를 해보면 문제 없이 잘 작동한다. > 이런 설정이 가능한 이유는 스프링이 프로퍼티의 값을, 수정자 메소드의 파라미터 타입을 참고로 해서 적절한 형태로 변환해주기 때문이다. > `setDriverClass()`메소드의 파라미터 타입이 `Class`임을 확인하고 텍스트값을 `class`오브젝트로 자동 변경해주는 것이다. 즉 내부적으로 다음과 같이 변환 작업이 일어난다고 생각하면 된다. ```java Class driverClass = Class.forName("com.mysql.jdbc.Driver"); dataSource.setDriverClass(driverClass); ``` > 이처럼 스프링은 `value`에 지정한 텍스트값을 적절한 자바 타입으로 변환해준다. 최종적으로 수정된 `applicationContext.xml`은 다음과 같다. ```xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="dataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource" > <property name="driverClass" ref="com.mysql.jdbc.Driver" /> <property name="url" ref="jdbc:mysql://localhost/springbook" /> <property name="username" ref="root" /> <property name="password" ref="<PASSWORD>" /> </bean> <bean id="userDao" class="springbook.user.dao.UserDao"> <property name="connectionMaker" ref="myConnectionMaker" /> </bean> </beans> ``` --- ### 정리 지금까지 사용자 정보를 DB에 등록하거나 아이도로 조회하는 기능을 가진 간단한 DAO코드를 만들고, 그 코드의 문제점을 살펴본 뒤, 이를 다양한 방법과 패턴, 원칙, IoC/DI 프레임워크까지 적용해서 개선해왔다. 그 과정을 돌아보자 - 먼저 책임이 다른 코드를 분리해서 두 개의 클래스로 만들었다`(관심사의 분리, 리팩토링)` - 그중에서 바뀔 수 있는 쪽의 클래스는 인터페이스를 구현하도록 하고, 다른 클래스에서 인터페이스를 통해서만 접근하도록 만들었다. 이렇게 해서 인터페이스를 정의한 쪽의 구현방법이 달라져 클래스가 바뀌더라도, 그 기능을 사용하는 클래스의 코드는 같이 수정할 필요가 없도록 만들었다`(전략 패턴)` - 이를 통해 자신의 책임 자체가 변경되는 경우 외에는 불필요한 변화가 발생하지 않도록 막아주고, 자신이 사용하는 외부 오브젝트의 기능은 자유롭게 확장하거나 변경할 수 있께 만들었다`(개방폐쇄원칙)` - 결국 한쪽의 기능변화가 다른 쪽의 변경을 요구하지 않아도 되게 했고`(낮은 결합도)`, 자신의 책임과 관심사에만 순수하게 집중하는`(높은 응집도)` 깔끔한 코드를 만들 수 있었다. - 오브젝트가 생성되고 여타 오브젝트와 관계를 맺는 작업의 제어권을 별도의 오브젝트 팩토리를 만들어 넘겼다. 또는 오브젝트 팩토리의 기능을 일반화한 IoC컨테이너로 넘겨서 오브젝트가 자신이 사용할 대상의 생성이나 선택에 관한 책임으로부터 자유롭게 만들어 줬다`(제어의 역전/IoC)` - 전통적인 싱글톤 패턴 구현 방식의 단점을 살펴보고, 서버에서 사용되는 서비스 오브젝트로서의 장점을 살릴 수 있는 싱글톤을 사용하면서도 싱글톤 패턴의 단점을 극복할 수 있도록 설계된 컨테이너를 활용하는 방법에 대해 알아봤다`(싱글톤 레지스트리)` - 설계 시점과 코드에는 클래스와 인터페이스 사이의 느슨한 의존관계만 만들어넣고, 런타임 시에 실제 사용할 구체적인 의존 오브젝트를 제3자(DI컨테이너)의 도움으로 주입받아서 다이나믹한 의존관계를 갖게 해주는 IoC의 특별한 케이스를 알아봤다`(의존관계 주입/DI)` - 의존 오브젝트를 주입할 때 생성자를 이용하는 방법과 수정자 메소드를 이용하는 방법을 알아봤다(생성자 주입과 수정자 주입) - 마지막으로 XML을 이용해 DI설정정보를 만드는 방법과 의존 오브젝트가 아닌 일반 값을 외부에서 설정해서 런타임 시에 주입하는 방법을 알아봤다(XML 설정) <file_sep>/java/god_of_java/Vol.1/14. 다 배운 것 같지만, 예외라는 중요한 것이 있어요/README.md ## 14. 다 배운 것 같지만, 예외라는 중요한 것이 있어요 ### 1. 자바에서 매우 중요한 예외 자바에서는 `예외(Exception)`라는 것이 있다. 예외를 모르면 자바를 모르는 것과 같다고 생각해도 된다. 예를 들어보자 - 가장일반적인 예로는 `null`인 객체에 메소드를 호출한다든지, - 5개의 공간을 가지는 배열을 만들었는데 6번째 값을 읽으라고 하든지, - 어떤 파일을 읽으라고 했는데 읽을 파일이 존재하지 않는다든지 - 네트워크 연결이 되어있는 어떤 서버가 갑자기 작동을 멈춰서 연결이 끊겨버린다든지 ### 2. try-catch 는 짝이다 가장 일반적인 예로 설명했던 배열 범위 밖의 값을 읽으려고 할 때를 살펴보자. ```java public class ExceptionSample { public static void main(String[] args) { ExceptionSample sample = new ExceptionSample(); sample.arrayOutOfBounds(); } public void arrayOutOfBounds() { int[] intArray = new int[5]; System.out.println(intArray[5]); } } ``` > 위 코드를 보면 당연히 "컴파일이 안되겠지..."라고 생각할 수 있지만 자바에서는 이러한 부분을 컴파일할때 점검해주지 않는다 > 실행결과를 살펴보자 ```java Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at ExceptionSample2.arrayOutOfBounds(ExceptionSample2.java:11) at ExceptionSample2.main(ExceptionSample2.java:6) ``` > `ArrayIndexOutOfBoundsException`라는 것이 발생했다. > 컴파일 할때 에러 메시지가 발생하는 것처럼,(위 에러는 컴파일이 아니라 실행시 에러다) 예외의 첫줄에는 > 어떤 예외가 발생했다고 출력된다. 그다음 줄부터는 탭~tab~을 주고 `at`로 시작하는 `스택 호출 추적`(영어로 call stack trace라고 하고, 보통 스택 트레이스라고 부르는)문장들이 출력된다. > 이 호출 관계의 가장 윗줄에는 예외가 발생한 클래스와 메소드 이름과 줄의 번호를 출력하고, 그 아래에는 그 메소드를 호출한 클래스의 메소드의 이름 및 줄의 번호가 출력된다. > 위 코드는 간단한 소스로 두개의 스택트레이스(`at`가 맨 앞에 있는 줄이 두개)만 찍혔지만 > 실제 운영되는 자바 기반의 시스템들은 그렇게 단순하지 않기 때문에 몇십 줄에서 백줄까지 출력되기도 한다. 그렇다면 이와 같은 예외 메시지가 발생하지 않도록 할 수는 없을까? > 물론 예외가 발생하지 않도록 개발하는 것이 우선이지만 완벽하게 처리하기는 어려운 부분들이 있다 > `arrayOutOfBounds()` 메소드를 다음과 같이 변경하자 ```java public void arrayOutOfBounds() { try{ int[] intArray = new int[5]; System.out.println(intArray[5]); }catch(Exception e){ } } ``` 메소드 괄호 안에 if문처럼 try를 쓰고 중괄호로 감싸고, catch라고 쓰고 메소드를 호출하는 것처럼 소괄호 안에 `Exception` 이라는 클래스 이름과 매개 변수 이름같은 `e`라는 것을 써주었다. > 위와 같이 예외를 처리하는 것이 "try~catch블록"이다. 위와같이 처리를 한후 재 컴파일->실행을 해보면 정상적으로 실행되는 것을 알수있다. 단. 이때 메시지를 출력하지 않을 뿐이지 실제로 예외는 발생한 것이다. > 다시 말하면 `try~catch`의 try블록 안에서 예외가 발생되면 그 이하의 문장은 실행되지 않고 바로 catch 블록으로 넘어간다는 뜻이다. ### 3. try-catch를 사용하면서 처음에 적응하기 힘든 변수 선언 `try-catch`를 사용할 때 가장 하기 쉬운 실수가 있다. 바로 변수의 지정이다 - `try블록` 내에서 선언한 변수를 catch에서 사용할 수 없다. > 위와 같은 문제때문에 일반적으로 `catch` 문장에서 사용할 변수에 대해서는 `try` 전에 미리 선언해 놓는다. 여기서 주의 할점은 `catch 블록`이 실행된다고 해서 `try`블록 내에서 실행된 모든 문장이 무시되는 것은 아니다. 예외가 발생하기 전까지의 문장들은 전부 작동을 한다고 생각하면 된다. 아래 코드를 컴파일 하고 실행해보자 ```java public void arrayOutOfBounds() { int[] intArray = null; try{ intArray=new int[5]; System.out.println(intArray[5]); }catch(Exception e){ System.out.println(intArray.length); } System.out.println("this code shoul run."); } ``` 위 소스를 실행해보면 아래와 같다. ``` 5 this code should run ``` > 위 소스를 보면 `try`내의 모든 문장이 모두 무시되는것이 아닌 배열선언까지는 읽혔다는것을 알수있다 그게 아니라면 `intArray[]` 의 길이를 불러올수 없었을 것이다. ### 4. finally 야 ~ 넌 무슨일이 생겨도 반드시 실행해야 돼 try-catch 구문에 추가로 붙을 수 있는 블록이 하나 더 있다. 바로 `finally`다 - `finally` 블록은 예외 발생여부와 상관없이 실행된다 - 코드의 중복을 피하기 위해서 반드시 필요하다. ### 5. 두개 이상의 catch `try-catch`문을 쓸때 catch에 `Exception e`라고 아무 생각없이 썻다. 이 `catch`블록이 시작되기전에 (중괄호가 시작되기전에) 있는 소괄호에는 예외의 종류를 명시한다. 다시말해서 반드시 `Exception e`라고 쓰는 것은 아니라는 것이다. ```java public void multiCatch() { int[] intArray = new int[5]; try { System.out.println(intArray[5]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("ArrayIndexOutOfBoundsException occured"); } catch (Exception e) { System.out.println(intArray.length); } } ``` >실행결과 `ArrayIndexOutOfBoundsException occured` 위 코드의 실행결과를 보면 `catch`문에 작성된 것만 처리되는구나..라고 생각할 수 있다. 이는 어떻게 보면 맞는말이지만 틀린 말이기도 하다 - `catch`블록의 순서는 매우 중요하다. `catch`블록은 순서를 따진다. 이번에는 위의소스를 순서를 바꾸어 실행해보자 ```java public void multiCatch() { int[] intArray = new int[5]; try { System.out.println(intArray[5]); } catch (Exception e) { System.out.println(intArray.length); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("ArrayIndexOutOfBoundsException occured"); } } ``` > 이렇게 해놓고 컴파일을 해보면 다음과 같은 에러메시지가 출력된다. ``` ExceptionSample2.java:28: error: exception ArrayIndexOutOfBoundsException has already been caught } catch (ArrayIndexOutOfBoundsException e) { ^ 1 error ``` **지난 과정에서 모든 객체의 부모클래스는 바로 java.lang.Object클래스라고 했다**그렇다면 모든 예외의 부모 클래스는 뭘까? > 모든 예외의 부모 클래스는 `java.lang.Exception` 클래스다. `java.lang.Exception` 클래스는 java.lang 패키지에 선언되어 있기 때문에 별도로 import할 필요는 없었다. 그런데 왜 단순히 순서만 바꾼 위 코드는 컴파일조차 되지 않았알까? 예외는 부모 예외 클래스가 이미 catch를 하고, 자식 클래스가 그 아래에서 catch를 하도록 되어 있을 경우에는 자식 클래스가 예외를 처리할 기회가 없다. > 다시 말하면 `Exception`클래스가 모든 클래스의 부모클래스이고, 배열에서 발생시키는 > `ArrayIndexOutOfBoundsException`은 `Exception` 클래스의 자식 클래스이기 때문에 > 절대로 `Exception` 클래스로 처리한 catch블록 이후에 선언한 블록은 처리될 일이 없다. - 그래서 일반적으로 `catch` 문을 여러개 사용할 경우에는 `Exception`클래스로 `catch`하는 것을 가장 아래에 추가할 것을 권장한다. > 정리해보자 - try 다음에 오는 catch 블록은 1개 이상 올 수 있다. - 먼저 선언한 catch 블록의 예외 클래스가 다음에 선언한 catch블록의 부모에 속하면, 자식에 속하는 catch블록은 절대 실행될 일이 없으므로 컴파일이 되지 않는다. - 하나의 try블록에서 예외가 발생하면 그예외와 관련이 있는 catch블록을 찾아서 실행한다 - catch 블록 중 발생한 예외와 관련있는 블록이 없으면, 예외가 발생되면서 해당 쓰레드는 끝난다(이 부분에 대해서는 나중에 쓰레드를 배워야 이해가 쉽다. 일단은 main() 메소드가 종료되어 프로그램이 종료된다고 생각하면 된다.) 따라서, 마지막 catch블록에는 Exception클래스로 묶어주는 버릇을 들여 놓아야 안전한 프로그램이 될 수 있다. ### 6. 예외의 종류는 세가지다 자바에는 세가지 종류의 예외가 존재하며, 각 예외는 다음과 같다 - checked exception - error - runtime exception 혹은 unchecked exception 각 예외의 구분은 간단하다 두번째와 세번째에 있는 error 와 unchecked exception을 제외한 모든 예외는 checked exception이다. 1) error (이하 에러) 에러는 자바 프로그램 밖에서 발생한 예외를 말한다. 가장 흔한 예가 서버의 디스크가 고장났다든지, 메인보드가 맛이가서 자바프로그램이 제대로 동작하지 못하는 경우가 여기에 속한다. > 뭔가 자바 프로그램에 오류가 발생했을 때, 오류의 이름이 Error로 끝나면 에러이고, Exception으로 끝나면 예외다. Error와 Exception으로 끝나는 오류의 가장 큰 차이는 프로그램 안에서 발생했는지, 밖에서 발생했는지 여부이다. 하지만, 더 큰 차이는 프로그램이 멈추어 버리느냐 계속 실행할 수 있느냐의 차이다 > 더 정확하게 말하면 Error는 프로세스에 영향을 주고, Exception은 쓰레드에만 영향을 준다. 2) runtime exception (이하 런타임 예외) - 런타임 예외는 예외가 발생할 것을 미리 감지하지 못했을 때 발생한다. - 컴파일시에 체크를 하지 않기 때문에 unchecked exception 이라고도 부른다. ### 7. 모든 예외의 할아버지는 java.lang.Throwable 클래스다 앞절에서 살펴본 `Exception`과 `Error`의 공통 부모 클래스는 당연히 `Object`클래스다. 그리고 공통 부모 클래스가 또 하나 있는데 , 바로 java.lang 패키지에 선언된 `Throwable`클래스다. Exception 과 Error 클래스는 Throwable 클래스를 상속받아 처리하도록 되어 있다. 그래서, Exception이나 Error를 처리할 때 Throwable로 처리해도 무관하다. 상속 관계가 이렇게 되어 있는 이유는 Exception이나 Error의 성격은 다르지만 모두 동일한 이름의 메소드를 상요하여 처리할 수 있도록 하기 위함이다. > Throwable에 어떤 생성자가 선언되어 있는지 살펴보자 - Throwable() - Throwable(String message) - Throwable(String cause) 아무런 매개변수가 없는 생성자는 기본적으로 제공한다. 그리고, 예외 메시지를 String으로 넘겨줄 수도 있다. 그리고, 별도로 예외의 원인을 넘길 수 있도록 Throwable 객체를 매개 변수로 넘겨 줄 수도 있다. > Throwable 클래스에 선언되어 있고 Exception 클래스에서 오버라이딩 하는 메소드는 10개가 넘지만 그 중에서 가장 많이 사용되는 메소드는 다음과 같다. - getMessage() - toString() - printStackTrace() 1) getMessage() 예외 메시지를 String 형태로 제공 받는다. 예외가 출력되었을 때 어떤 예외가 발생됬는지 확인할 때 매우 유용하다. 그 메시지를 활용하여 별도의 예외 메시지를 사용자에게 보여주려고 할 때 좋다 2) toString() 예외 메시지를 String 형태로 제공 받는다. 그런데 , getMessage()메소드보다는 약간 더 자세하게 , 예외 클래스 이름도 같이 제공한다. 3) printStackTrace() 가장 첫 줄에는 예외 메시지를 출력하고, 두번째 줄부터는 예외가 발생하게 된 메소드들의 호출관계(스택 트레이스)를 출력해준다. ### 8. 난 예외를 던질 거니까 throws라고 써놓을께 지금까지는 예외를 처리하는 방법을 배웠다. 이제부터는 예외를 발생시키는 방법을 알아보자. 예외를 발생시킨다는 표현이 좀 어색할 것이다. 정확하게 말하면 자바에서는 예외를 던질 수 있다. ```java public void throwException(int number) throws Exception { try { if (number > 12) { throw new Exception("Number is over than 12"); } } catch (Exception e) { e.printStackTrace(); } } ``` 이렇게 메소드 선언에 해 놓으면, 예외가 발생했을 때 try-catch로 묶어주지 않아도 그 메소드를 호출한 메소드로 예외처리를 위임하는 것이기 때문에 전혀 문제가 되지 않는다. 즉, 위 코드에서 try-catch블록으로 묶지 않아도 예외를 throw한다고 할지라도, throws가 선언되어 있기 때문에 전혀 문제가 없다. 하지만, 이렇게 throws로 메소드를 선언하면 개발이 어려워진다. 왜냐하면, 이 throwException() 이라는 메소드는 Exception을 던진다고 throw 선언을 해 놓았기 때문에, throwException() 메소드를 호출한 메소드에서는 throwException() 메소드를 수행하는 부분에는 반드시 try-catch 블록으로 감싸주어야만 한다. 정리해보자 - 메소드를 선언할 때 매개변수 소괄호 뒤에 throws 라는 예약어를 적어 준 뒤 예외를 선언하면, 해당 메소드에서 선언한 예외가 발생했을 때 호출한 메소드로 예외가 전달된다 만약 메소드에서 두 가지 이상의 예외를 던질 수 있다면, implements처럼 콤마로 구분하여 예외클래스 이름을 적어주면 된다. - try블록 내에서 예외를 발생시킬 경우에는 throw라는 예약어를 저어 준 뒤 예외 객체를 생성하거나, 생성되어 있는 객체를 명시해준다 throw한 예외 클래스가 catch블록에 선언되어 있지 않거나, throws 선언에 포함되어 있지 않으면 컴파일 에러가 발생한다. - catch 블록에서 예외를 throw 할 경우에도 메소드 선언의 throws 구문에 해당 예외가 정의되어 있어야만 한다. > 예외를 throw하는 이유는 해당 메소드에서 예외를 처리하지 못하는 상황이거나, 미처 처리하지 못한 예외가 있을 경우에 대비하기 위함이다. > 자바에서 예외 처리를 할때 throw와 throws 는 매우 중요하다. ### 9. 자바 예외 처리 전략 자바에 예외를 처리할 때에는 표준을 잡고 진행하는 것이 좋다. > 예외를 직접 만들 때 Exceptioin 클래스를 확장하여 나만의 예외 클래스를 만들었을 경우 > 이 예외가 항상 발생하지 않고, 실행시에 발생할 확률이 매우 높은 경우에는 런타임 예외로 만드는 것이 나을 수도 있다. > 즉 클래스 선언시 extends Exception 대신에 extends RuntimeException 으로 선언하는 것이다 > 이렇게 되면, 해당 예외를 던지는(throw하는) 메소드를 사용하더라도 try-catch 로 묶지 않아도 컴파일시에 예외가 발생하지 않는다. 하지만, 이 경우에는 예외가 발생할 경우 해당 클래스를 호출하는 다른 클래스에서 예외를 처리하도록 구조적인 안전장치가 되어 있어야만 한다. > 여기서 안전장치라고 하는 것은 try-catch로 묶지 않은 메소드를 호출하는 메소드에서 예외를 처리하는 try-catch가 되어 있는 것을 이야기 한다. 정리해보면 - 임의의 예외 클래스를 만들 때에는 반드시 try-catch 로 묶어줄 필요가 있을 경우에만 Exception 클래스를 확장한다. - **일반적으로 실행시 예외를 처리할 수 있는 경우에는 RuntimeException 클래스를 확장하는 것을 권장한다(아주 중요함!!)** - catch문 내에 아무런 작업 없이 공백을 놔 두면 안된다. 예외의 처리 전략에 대해선 구글에 "[자바 에외 전략](https://www.google.co.kr/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=%EC%9E%90%EB%B0%94%20%EC%98%88%EC%99%B8%20%EC%A0%84%EB%9E%B5)" 이나 "[Java Exception Strategy](https://www.google.co.kr/search?q=Java+Exception+Strategy&oq=Java+Exception+Strategy&aqs=chrome..69i57j0.391j0j4&sourceid=chrome&es_sm=122&ie=UTF-8)"로 검색을 해보면 많은 자료들을 찾을 수 있다. > 예제 ```java public class Calculator { public static void main(String[] args) { Calculator calc=new Calculator(); calc.printDivide(1,2); calc.printDivide(1,0); } public void printDivide(double d1, double d2){ double result=d1/d2; System.out.println(result); } } ``` > 실행결과 ``` 0.5 Infinity ``` > 만약 두번째 값이 "0" 이면 "Second value can`t be Zero"라는 메시지를 갖는 예외를 발생시키고, 발생시킨 예외를 throw할 수 있도록 코드를 수정해보자 ```java public class Calculator { public static void main(String[] args) { Calculator calc=new Calculator(); try{ calc.printDivide(1,2); calc.printDivide(1,0); }catch(Exception e){ System.out.println(e.getMessage()); } } public void printDivide(double d1, double d2) throws Exception{ if(d2==0) throw new Exception("Second value can't be Zero"); if(d2==0){ throw new Exception("Second value can't be Zero"); } double result=d1/d2; System.out.println(result); } } ``` #### 정리해 봅시다 1. 예외를 처리하기 위한 세가지 블록에는 어떤 것이 있나요? -> try, catch, fially 2. 1번 문제의 답 중에서 "여기에서 예외가 발생할 것이니 조심하세요"라고 선언하는 블록은 어떤 블록인가요? -> try 3. 1번 문제의 답 중에서 "예외가 발생하던 안하던 얘는 반드시 실행되어야 됩니다."라는 블록은 어떤 블록인가요? -> finally => 4. 예외의 종류 세가지는 각각 무엇인가요? -> errow, checked, unchecked => checked exception error runtime exception 혹은 unchecked exception 5. 프로세스에 치명적인 영향을 주는 문제가 발생한 것을 무엇이라고 하나요? -> error => error는 치명적인 오류를 의미한다. 기본적으로는 프로그램 내에서 발생한다기 보다는 JVM 이나 시스템에서 문제가 발생했을 때 error가 발생한다. 6. try나 catch 블록 내에서 예외를 발생시키는 예약어는 무엇인가요? -> throw => throw를 사용하여 새로운 예외를 발생시키면, 해당 예외를 호출한 메소드로 던진다. 7. 메소드 선언시 어떤 예외를 던질 수도 있다고 선언할 때 사용하는 키워드는 무엇인가요? -> throws => throw가 메소드 내에 있다면 메소드 선언시 throws 를 사용하여 던질 예외의 종류를 명시하는 것이 좋다. 8. 직접 예외를 만들 때 어떤 클래스의 상속을 받아서 만들어야만 하나요? -> Exception => Exception클래스를 확장하여 예외 클래스를 만들 수 있다. 하지만, 이렇게 되면 무조건 해당 예외를 던지는 메소드에서 try-catch로 묶어야 한다는 단점이 있다. 따라서, RuntimeException 클래스를 확장하여 선언하는 것을 권장한다.<file_sep>/java/god_of_java/Vol.2/03. 가장 많이 쓰는 패키지는 자바랭/NumberObject.java public class NumberObject { public static void main(String[] args) { NumberObject no=new NumberObject(); //no.parseLong("r1024"); //no.parseLong("1024"); no.printOtherBase(1024); } public long parseLong(String data){ long longdata=-1; try{ longdata=Long.parseLong(data); System.out.println(longdata); } catch(NumberFormatException ne){ System.out.println(data+" is not a number"); } catch(Exception e){ } return longdata; } public void printOtherBase(long value){ System.out.println("Original:"+value); System.out.println("Binary:"+Long.toBinaryString(value)); System.out.println("Hex:"+Long.toHexString(value)); System.out.println("Octal:"+Long.toOctalString(value)); } } <file_sep>/java/java_web_develop_workBook/1장. 웹 애플리케이션의 이해/README.md ## 1. 데스크톱 애플리케이션 > 데스크톱 애플리케이션의 문제점 데스크톱 애플리케이션은 PC에 설치되어 실행하기 때문에 웹 애플리케이션보다는 실행 속도가 빠르다. 하지만, 다음 문제 때문에 기업용 애플리케이션의 아키텍쳐로 쓰기에 적합하지 않다. 1) 배포가 번거롭다 > 기능을 추가하거나 변경할 때마다 다시 배포해야하므로 매우 번거롭다. > 백 대 이상의 PC에 배포애햐 한다고 생각해보자.. > 또한 출장 중을 예로들면 다른 PC에는 프로그램을 설치해야 하는데 이는 보안에도 좋지 않다. 2) 보안에 취약하다. > 데이터베이스에 접속이 필요한 애플리케이션은 보안에 특이 취약하다. (접속정보가 고스란히 들어가있기때문에) 3) 해결방안 > 배포가 번거로운 문제는 자동갱신을 통하여 해결할 수 있다. > 즉 애플리케이션을 실행할 때 먼저 서버에 갱신된 버전이 있는지 조회하는 방식이다 > 하지만 보안이 취약문제는 여전히 그대로이다 그 문제를 알아보자 클라이언트 - 서버애플리케이션의 특징 - 업무 변화에 대응하기 쉽다 - 서버쪽에서 데이터베이스와 접속 -> 보안이 강화된다. p.27 ~ 34 예제 참조 클라인트 - 서버 구조의 장점 > 예제의 핵심은 서버에서 계산을 수행하고 그 결과를 클라이언트로 보내주는 것이다. > 따라서 신규 연산자가 추가되더라도 서버쪽만 변경하면 됩니다. 클라이언트는 바뀌지 않기 때문에 다시 설치할 필요가 없는 개념이다. > 이와 같이 데스크톱 애플리케이션의 기능 일부를 서버에 이관하는 구조로 만들면 **기능 변경이나 추가에 대해 보다 유연하게 대처**할 수 있다. 위 예제인 CalculatorServer의 문제는 한 번에 하나의 클라이언트 하고만 연결된다는 점이다. 자동적으로 현재 연결된 클라이언트와의 연결이 끊어질 때까지 다른 클라이언트는 기다려야만 한다 > 이런 문제들을 해결하기 위해 대부분의 서버프로그램은 멀티 프로세스 또는 멀티 스레드와 같은 병행처리 방식을 도입했다. #### 멀티프로세스와 멀티쓰레드 1) 멀티 프로세스 방식 - 클라이언트가 연결 요청을 하면 서버 프로그램은 자신을 복제하여 클라이언트에 대응하게 하고, 자신은 다른클라이언트의 요청을 기다린다. - 이 방식은 원본 프로세스의 메모리를 모두 복제하기 때문에 자원낭비가 심하다. 2) 멀티 쓰레드 방식 - 클라이언트 요청을 처리하는 일부 코드만 별도로 분리하여 실행하기 때문에 전체메모리를 복제할 필요가 없어, 멀티 프로세스 방식보다 메모리 낭비가 적다 #### 다중 클라이언트의 요청처리 다중 클라이언트요청의 특징 - 클라이언트의 요청 처리 부분을 별도의 작업으로 분리한다. - 분리된 작업은 스레드에 정의한다. - 다중 클라이언트의 요청이 동시에 병행 처리된다. #### 클라이언트 - 서버 아키텍처의 진화 > 전통적인 클라이언트 서버 아키텍쳐 서버는 데이터 처리를 맡고 클라이언트는 UI와 비즈니스 처리를 담당한다. 즉, 데스크톱 애플리케이션의 데이터 처리 부분을 공통화하여 서버로 이관한 것이다 이렇게 여러 PC에 분산되어 있는 자료를 하나의 서버에서 관리하면 자료의 중복이나 자료가 일치하지 않는 문제를 해소할 수 있다. ######단점 이 방식의 문제는 프로그램이 변경되면 PC에 다시 설치해야 한다는 것이었다. 이전의 메인프레임 방식에서는 프로그램이 서버에 있어서 서버쪽만 변경하면 됬지만 C/S 방식에서는 그럴수가 없다. 전통적인 C/S 환경에서는 클라이언트가 DBMS로 바로 접속하기 때문에 보안 문제가 발생할 수 있다. DBMS에 접속하려면 사용자 정보가 필요한데 이부분들이 보통 프로그램 코드에 들어있기때문이다. > 개선된 클라이언트 - 서버 아키텍쳐 이런 문제들을 개선하기 위해 클라이언트의 업무 처리 부분은 서버로 이관하고, 클라이언트는 오로지 사용자와의 상화작용을 처리하는 UI만을 담당하게 된다. 즉 클라이언트는 데이터를 입력받을 화면을 사용자에게 제공하고, 입력받은 데이터가 형식에 맞는지 검사하고, 필요하다면 서버가 원하는 형식으로 변환하여 서버에 보낸다. 서버로부터 결과를 받으면 사용자가 이해하기 쉽게 화면을 꾸며 출력한다. 업무 처리 부분은 서버에게 위임하는 것이다 > 애플리케이션 서버 이렇게 업무 처리를 전담하는 서버를 '애플리케이션 서버'라고 부른다. 애플리케이션 서버는 클라이언트로부터 요청을 받으면 업무 로직에 따라 DBMS 서버를 사용하여 데이터를 처리한다. 또한, 클라이언트의 접근을 제어하여 무효한 접근을 차단하고, 함께 처리해야 할 작업들이 있다면 하나의 트랜잭션으로 묶어서 관리합니다. > 특징 이방식은 클라이언트가 DB에 직접 접속하지 않기 때문에 DB 접속정보가 노출되는 사고를 막을 수 있다. 또한, 업무 처리 부분을 서버로 이전했기 때문에 서버에서 기능 변경을 하더라도 바로 클라이언트에 적용할 수 있다 물론 서버 쪽 변경만으로 배포 문제를 완전히 해결할 수 는 없지만 어느정도 잦은 배포를 줄일 수 있다. > 웹애플리케이션 서버구조 - 클라이언트와의 통신은 웹 서버가 전담 -> 네트워크 및 멀티 스레드 프로그래밍으로부터 탈출 - 애플리케이션 서버는 애플리케이션 실행 및 관리에 집중 > 웹 어플리케이션 방식이 기존의 C/S 환경과 비교해서 무엇이 다른지 살펴보자 배치 기존의 C/S환경은 비즈니스 처리 부분을 서버에 배치하고 UI 처리 부분을 클라이언트에 배치했다 업무가 변경되면 그에 따라 UI도 바뀌어야 하기 때문에 기능이 추가되거나 변경될 때마다 클라이언트 프로그램을 다시 설치해야 하는 문제가 있었다. 웹 환경에서는 비즈니스 로직과 UI로직을 모두 서버에 배치하기 때문에 기능이 추가되거나 변경되더라도 서버쪽만 바꾸면 된다. 따라서 배치하는 즉시 사용자는 재설치 없이 추가된 기능이나 변경된 기능을 이용할 수 있게 되는것이다. 다만, 웹 환경에서는 어플리케이션을 실행할 때마다 UI로직을 내려받아야 하기 때문에 네트워크 오버헤드(특정 기능을 수행하기 위해 추가로 사용되는 자원)가 발생한다. 실행 웹 환경에서 어플리케이션 실행은 웹 브라우져를 통하여 이루어진다. 웹브라우저가 설치되어 있고 인터넷에 연결되어 있다면 어디에서라도 애플리케이션을 실행할 수 있다. 개발 C/S 환경에서는 데이터 통신을 위해 네트워크 프로그래밍을 해야 한다. 또한, 서버에서는 다중 클라이언트의 요청을 동시에 처리하기 위해 멀티 스레드 프로그래밍을 해야 한다. 그러나 웹 환경에서는 웹 브라우저와 웹 서버가 그부분을 대신 처리해주고, 개발자는 단지 어떤 업무를 처리하고 무엇을 출력할 것인가에 대해서만 고민하면 되게 된것이다. 웹 어플리케이션의 등장 이유 > 기존의 c/s 환경에서는 요즘의 빠른 변화의 추세에 대처할 수 없다. > 한달에도 몇 번씩 기능이 추가되거나 변경되기 때문인데 > 그때마다 매번 클라이언트 프로그램을 재설치해야 한다면 사용자나 IT부서 담당자 모두에게 악몽일 것이다. 웹 어플리케이션의 문제점과 개선방안 > 웹 어플리케이션도 만능은 아니다. > 매번 출력화면을 서버에서 만들고, 클라이언트는 이 화면을 내려받아야 한다는 것이다. > 만약 사용자가 이리저리 화면을 옮겨 다닌다면 서버는 같은 화면을 계속 반복해서 만들어야 하고, 클라이언트는 반복해서 내려받아야 한다. > 이것은 서버 및 네트워크 자원에 대한 오버헤드를 발생시킨다. AJAX > 이를 해결하고자 AJAX라는 기술이 등장했다. > 같은 화면에서 데이터만 바뀔 때는, 서버에서 UI전체를 받아오기보다는 데이터만 받아오는것이 효율적이기 때문인데, 이것을 가능하게 하는 기술이 AJAX이다. <file_sep>/java/god_of_java/Vol.1/09. 패키지와 접근제어자/README.md ## 9장. 자바를 배우면 패키지와 접근 제어자는 꼭 알아야 해요 ### 1. 패키지는 그냥 폴더의 개념이 아니에요 - 클래스들을 구분 짓는 폴더와 비슷한 개념 - 이름이 중복되거나 어떤클래스가 어떤 일을 하는지 혼동되는 일을 방지하고자 만들어졌다 c/javapackage 폴더 생성후 거기에 아래의 자바파일 생성 ```java package c.javapackage; public class Package { public static void main(String[] args) { System.out.println("Package class."); } } ``` > 이때 컴파일과 실행은 다음과 같이 한다. ``` javac c/javapackage/Package.java java c/javapackage/Package ``` > 패키지 선언문 - 소스에 가장 첫줄에 위치해야한다. 패키지 선언 위에 주석이나 공백이 있어도 상관은 없다. 하지만 다른 자바 문장이 하나라도 있으면 컴페일이 제대로 되지 않는다. - php의 header와 기능상은 비슷한다 (물론 개념은 다르지만) - 패키지 선언은 소스 하나에는 하나만 존재해야한다. - 패키지 이름과 위치한 폴더 이름이 같아야만 한다. **주의사항!! 패키지 이름이 `java`로 시작해서는 안된다.** --- ### 2, 패키지 이름은 이렇게 지어요 | 패키지 시작 이름 | 내용 | |-------|--------| | java | 자바 기본 패키지(JDK 벤더에서 개발) | | javax | 자바 확장 패키지(JDK 벤더에서 개발) | | org | 일반적으로 비 영리단체(오픈소스)의 패키지 | | com | 일반적으로 영리단체(회사)의 패키지 | > 꼭 지켜야 하는 것은 아니지만 대부분의 코드는 이렇게 패키지가 시작된다. [아파치 그룹의 오픈소스 프로젝트들 참고](http://apache.org) **패키지 이름을 지정할 때 유의점** - 패키지 이름은 모두 소문자로 지정해야한다. (가이드 권고사항) - 자바의 예약어를 사용하면 절대 안된다 -`int`,`static`등의 예약어가 패키지 이름에 들어 있으면 안된다. - 예를들면 `com.int.util` 이렇게 상위 패키지 이름을 정했으면, 그다음에는 하위 패키지 이름을 정해야만 한다. 자바의 기본 패키지인 java패키지는 java패키지 아래에 io, lang, nio, text, util 등의 여러 패키지가 존재한다. ### 3. import를 이용하여 다른 패키지에 접근하기 패키지가 있을 때, 같은 패키지에 있는 클래스들과 기본~default~ 패키지에 있는 클래스들만 찾을 수 있다. 여기서 기본 패키지에 있는 클래스라고 함은 Package 선언이 되어 있지 않은, 패키지가 없는 클래스들을 말한다. 자세한 내용은 아래 코드를 통해 살펴보자 ```java package c.javapackage.sub; public class Sub { public sub() { } public void subClassMethod() { } } ``` > 위의 `Sub`클래스의 소스는 c/javapackage/sub 라는 폴더에 있어야 한다. 이제 c/javapackage 경로에있는 `Package`클래스의 `main()`메소드에 다음과 같이 `Sub클래스`의 객체를 생성하고 메소드를 호출하자. ```java public class Package { public static void main(String[] args) { Sub sub=new Sub(); sub.subClassMethod(); } } ``` > 위 내용을 컴파일 해보면 `Sub` 클래스를 찾지 못한다는 에러가 뜬다 이처럼 다른 패키지에 있는 클래스를 찾지 못할때 사용하는 것이 바로 import이다. 즉 `Package`클래스에 아래와 같이 import 해줘야 한다. ```java // import 패키지이름.클래스이름 import c.javapackage.sub.Sub; ``` > 또한 `import`해야하는 클래스가 100개일 경우 전부 할수가 없기 때문에 아래와 같이 가능하다. ```java import c.javapackage.sub.*; ``` ___ JDK 5 부터는 `import static`이라는게 추가되었는데 이는 `static`한 변수(클래스변수)와 static 메소드를 사용하고자 할 때 용이하다. 잘 이해가 안가니 Sub클래스에 다음과 같이 추가하자 ```java public final static String CLASS_NAME = "Sub"; public static void subClassStaticMethod() { System.out.println("subClassStaticMethod() is called."); } ``` > 이와 같이 선언되어있는 static변수나 메소드를 사용할때 `import static`을 사용하면된다. 그전에! `import static` 이 없을때 어떻게 하는지를 먼저 알아보자 ```java package c.javapackage; import c.javapackage.sub.Sub; public class Package { public static void main(String[] args) { sub.subClassStaticMethod(); System.out.println(Sub.CLASS_NAME); } } ``` > 위처럼 Sub클래스에 선언된 메소드를 사용하겠다는 것을 명시적으로 지정하기 위해서 `Sub.subClassStaticMethod()`로 사용해야 한다.(static 변수도 마찬가지) 하지만 import static 을 사용한다면 다음과 같이 하면된다. ```java //생략 import static c.javapackage.sub.Sub.subClassStaticMethod; import static c.javapackage.sub.Sub.CLASS_NAME; public class Package { public static void main(String[] args) { subClassStaticMethod(); System.out.println(CLASS_NAME); } } ``` > 그리고 위 import처럼 여러줄 입력하기 귀찮다면 다음과 같은 방법도 있다. ```java import static c.javapackage.sub.Sub.*; ``` 여기서 질문! 만약 Package 클래스에 import한 동일한 이름의 static변수나 메소드가 자신의 클래스에 있으면 어떻게 될까? - 이때는 자신의 변수나 메소드가 import로 불러온 것보다 우선이다. > import는 꼭 기억하고 있어야 하는 자바의 기본 키워드이다. > 그리고, import하지 않아도 되는 패키지는 다음과 같다. - java.lang 패키지 - 같은 패키지 > 지금까지 사용한 `String`과 `System` 클래스가 전부 java.lang 패키지에 있다. - 패키지가 같은지 다른지에 따라서 import 여부가 결정된다. - 폴더구조상 상위 패키지와 하위패키지에 있는 클래스의 상관관계는 전혀 없다. - 참고로 이클립스를 사용하는 경우는 `Ctrl`+`Shift`+`o` 를 동시에 누르면 자동으로 필요한 패키지를 `import` 해준다 ### 4. 자바의 접근 제어자 자바를 배우면 꼭 외우고 이해하고 있어야 하는 것중 하나인 접근제어자에 대해 알아보자 > ##### 접근제어자~Accessmodifier~ 접근제어자는 4개가 있으며 클래스,메소드,인스턴스 및 클래스 변수를 선언할 때 사용된다. 1. public : 누구나 접근가능 2. protected : 같은 패키지 내에 있거나 상속받은 경우에만 접근 가능 3. package-private(접근제어자없음) : 같은 패키지 내에 있을 때만 접근 가능 4. private : 해당 클래스 내에서만 접근 가능 ```java public class Sub { public void publicMethod() { } protected void protectedMethod() { } void packagePrivateMethod() { } private void privateMethod() { } } ``` > 이 클래스를 `Package`클래스의 `main()`메소드에서 호출후 컴파일 해보자 이런 접근 제어자는 다른 사람이 가져다 쓰면 안될경우 필요하다 (가령 암호를 계산하는 로직) 변수의 경우 직접 접근해서 변경하지 못하게 하고 꼭 메소드를 통해서 변경이나 조회만 할 수 있도록 할 때 ==접근제어자== 를 많이 사용한다. > 예를 들어 앞장에서 만든 `MemberDTO` 의 `name` 이라는 변수를 조회만 할 수 있도록 하려면 `name`이라는 변수는 `private`로 선언하고, `name`값을 조회하는 메소드만 만들어 놓으면 된다. > 이렇게 해놓으면 `name`의 값을 생성자로만 선언하고, 아무도 그 값을 변경하지 못할 것이다. ```java public class MemberDTO { private String name; //중간생략 public MemberDTO(String name){ //생성자를 통해서 name값 지정 this.name=name } public String getName(){ // 조회용 return name; } } ``` > 아래표를 참고하자 | | 해당 클래스 안에서 | 같은 패키지에서 | 상속받은 클래스에서 | import한 클래스에서 |--------|--------|--------|-------- | public | O | O | O | O | protected | O | O | O | X | package private | O | O | X | X | private | O | X | X | X > 은행을 예로 들면 - **public : 은행창구** - protected : 은행 창구의 직원 자리 - package-private : 지점장실 - **private : 금고** ### 5. 클래스 접근제어자 선언할때의 유의점 지금까지 알아본 사항은 주로 메소드에 대한 내용이었다. 이 접근 권한은 인스턴스 변수와 클래스 변수에도 동일하게 적용하면 된다. 이 외에, 접근 제어자를 사용할 수 있는 곳은 바로 클래스 선언문이다. - 클래스를 선언할 때에는 반드시 파일 이름에 해당하는 클래스가 존재해야한다. 즉 Profile.java 라는 소스코드에는 `Profile`이라는 클래스를 `public`으로 선언해야한다. - 하나의 파일에 두개의 클래스가 있어도 상관없지만 파일이름과 동일한 이름의 클래스는 `public` 이어야 한다. ==직접해 봅시다== (p.280) ```java package b.array; public class Array{ } ``` ```java package b.control; class ControlOfFlow{ } ``` ```java package b.operator; class Operators{ } ``` **정리해 봅시다** 1. 패키지를 선언할 때 사용하는 예약어는 무엇인가요? -> package 2. 패키지 선언은 클래스 소스 중 어디에 위치해야 하나요? -> 소스 최상단 3. 패키지를 선언할 때 가장 상위 패키지의 이름으로 절대 사용하면 안되는 단어는 무엇인가요? -> java 4. 패키지 이름에 예약어가 포함되어도 되나요? -> 아니오 5. import는 클래스 내에 선언해도 되나요? -> 아니오 => **import는 클래스 선언 전에 명시되어 있어야만 한다.** 6. 같은 패키지에 있는 클래스를 사용할 때 import를 해야 하나요? -> 아니오 => java.lang 패키지도 할필요 없다. 7. 특정 패키지에 있는 클래스들을 모두 import할 때 사용하는 기호는 무엇인가요? -> * 8. 클래스에 선언되어 있는 static한 메소드나 변수를 import하려면 어떻게 선언해야 하나요? -> import static 9. 접근 제어자 중 가장 접근 권한이 넓은 (어떤 클래스에서도 접근할 수 있는) 것은 무엇인가요? -> public 10. 접근 제어자 중 가장 접근 권한이 좁은 (다른 클래스에서는 접근할 수 없는) 것은 무엇인가요? -> private 11. 접근 제어자 중 같은 패키지와 상속관계에 있는 클래스만 접근할 수 있도록 제한하는 것은 무엇인가요? -> protected 12. Calculate.java라는 자바 소스가 있을 경우, 그 소스 내에는 Calculate라는 클래스외에는 ( )으로 선언된 클래스가 있으면 안된다. 여기서 괄호 안에 들어가야 하는 것은 무엇인가요? -> public <file_sep>/javascript/inside_javascript/chapter04 함수와 프로토타입 체이닝/4.js /* *************************************** 4-1 예제 ******************************************* */ // add() 함수 선언문 function add(x, y) { return x + y; } console.log(add(3, 4)); // 7 /* *************************************** 4-2 예제 ******************************************* */ // add() 함수 표현식 var add = function (x, y) { return x + y; }; var plus = add; console.log(add(3,4)); // 7 console.log(plus(5,6)); // 11 /* *************************************** 4-3 예제 ******************************************* */ var add = function sum(x, y) { return x + y; }; console.log(add(3,4)); // 7 console.log(sum(3,4)); // Uncaught ReferenceError: sum is not defined 에러 발생 /* *************************************** 4-4 예제 ******************************************* */ var factorialVar = function factorial(n) { if(n <= 1) { return 1; } return n * factorial(n-1); }; console.log(factorialVar(3)); // 6 console.log(factorial(3)); // Uncaught ReferenceError: factorial is not defined 에러 발생 /* *************************************** 4-5 예제 ******************************************* */ var add = new Function('x', 'y', 'return x + y'); console.log(add(3, 4)); // 7 /* *************************************** 4-6 예제 ******************************************* */ console.log(add(2,3)); // 5 // 함수 선언문 형태로 add() 함수 정의 function add(x, y) { return x + y; } console.log(add(3, 4)); // 7 /* *************************************** 4-7 예제 ******************************************* */ add(2,3); // uncaught type error // 함수 표현식 형태로 add() 함수 정의 var add = function (x, y) { return x + y; }; add(3, 4); /* *************************************** 4-8 예제 ******************************************* */ // 함수 선언 방식으로 add()함수 정의 function add(x, y) { return x+y; } // add() 함수 객체에 result, status 프로퍼티 추가 add.result = add(3, 2); add.status = 'OK'; console.log(add.result); // 5 console.log(add.status); // 'OK' /* *************************************** 4-9 예제 ******************************************* */ // 변수에 함수 할당 var foo = 100; var bar = function () { return 100; }; console.log(bar()); // 100 // 프로퍼티에 함수 할당 var obj = {}; obj.baz = function () {return 200; } console.log(obj.baz()); // 200 /* *************************************** 4-10 예제 ******************************************* */ // 함수 표현식으로 foo() 함수 생성 var foo = function(func) { func(); // 인자로 받은 func() 함수 호출 }; // foo() 함수 실행 foo(function() { console.log('Function can be used as the argument.'); }); /* *************************************** 4-11 예제 ******************************************* */ // 함수를 리턴하는 foo() 함수 정의 var foo = function() { return function () { console.log('this function is the return value.') }; }; var bar = foo(); bar(); /* *************************************** 4-12 예제 ******************************************* */ function add(x, y) { return x + y; } console.dir(add); /* *************************************** 4-13 예제 ******************************************* */ function func0() { } function func1(x) { return x; } function func2(x, y) { return x + y; } function func3(x, y, z) { return x + y + z; } console.log('func0.length - ' + func0.length); // func0.length - 0 console.log('func1.length - ' + func1.length); // func1.length - 1 console.log('func2.length - ' + func2.length); // func2.length - 2 console.log('func3.length - ' + func3.length); // func3.length - 3 /* *************************************** 4-15 예제 ******************************************* */ <!DOCTYPE html> <html> <body> <script> // 페이지 로드시 호출될 콜백 함수 window.onload = function() { alert('This is the callback function.'); }; </script> </body> </html> /* *************************************** 4-16 예제 ******************************************* */ (function (name) { console.log('This is the immediate function --> ' + name); })('foo'); /* *************************************** 4-18 예제 ******************************************* */ // parent() 함수 정의 function parent() { var a = 100; var b = 200; // child() 내부 함수 정의 function child() { var b = 300; console.log(a); console.log(b); } child(); } parent(); child(); /* *************************************** 4-19 예제 ******************************************* */ function parent() { var a = 100; // child() 내부 함수 var child = function () { console.log(a); } // child() 함수 반환 return child; } var inner = parent(); inner(); /* *************************************** 4-20 예제 ******************************************* */ // self() 함수 var self = function () { console.log('a'); return function () { console.log('b'); } } self = self(); // a self(); // b /* *************************************** 4-21 예제 ******************************************* */ function func(arg1, arg2) { console.log(arg1, arg2); } func(); // undefined undefined func(1); // 1 undefined func(1,2); // 1 2 func(1,2,3); // 1 2 /* *************************************** 4-23 예제 ******************************************* */ // myObject 객체 생성 var myObject = { name: 'foo', sayName: function () { console.log(this.name); } }; // ohterObject 객체 생성 var otherObject = { name: 'bar' }; // otherObject.sayName() 메서드 otherObject.sayName = myObject.sayName; // sayName() 메서드 호출 myObject.sayName(); otherObject.sayName(); /* *************************************** 4-24 예제 ******************************************* */ var foo = "I'm foo"; // 전역 변수 선언 console.log(foo); // I’m foo console.log(window.foo); // I’m foo /* *************************************** 4-25 예제 ******************************************* */ var test = 'This is test'; console.log(window.test); // sayFoo() 함수 var sayFoo = function () { console.log(this.test); // sayFoo() 함수 호출 시 this는 전역 객체에 바인딩된다. }; sayFoo(); // this.test 출력 /* *************************************** 4-27 예제 ******************************************* */ // 내부 함수 this 바인딩 var value = 100; var myObject = { value: 1, func1: function () { var that = this; this.value += 1; console.log('func1() called. this.value : ' + this.value); func2 = function () { that.value += 1; console.log('func2() called. this.value : ' + that.value); func3 = function () { that.value += 1; console.log('func3() called. this.value : ' + that.value); } func3(); } func2(); } }; myObject.func1(); // func1 메서드 호출 /* *************************************** 4-28 예제 ******************************************* */ // Person 생성자 함수 var Person = function (name) { this.name = name; }; // foo 객체 생성 var foo = new Person('foo'); console.log(foo.name); // foo /* *************************************** 4-29 예제 ******************************************* */ //객체 리터럴 방식으로 foo 객체 생성 var foo = { name: 'foo', age: 35, gender: 'man' }; console.dir(foo); //생성자 함수 function Person(name, age, gender, position) { this.name = name; this.age = age; this.gender = gender; } // Person 생성자 함수를 이용해 bar 객체, baz 객체 생성 var bar = new Person('bar', 33, 'woman'); console.dir(bar); var baz = new Person('baz', 25, 'woman'); console.dir(baz); /* *************************************** 4-30 예제 ******************************************* */ //생성자 함수 function Person(name, age, gender, position) { this.name = name; this.age = age; this.gender = gender; } var qux = Person('qux', 20, 'man'); console.log(qux); // undefined console.log(window.name); // qux console.log(window.age); // 20 console.log(window.gender); // man /* *************************************** 4-37 예제 ******************************************* */ // Person 생성자 함수 function Person(name) { this.name = name; } // foo 객체 생성 var foo = new Person('foo'); console.dir(Person); console.dir(foo); /* *************************************** 4-38 예제 ******************************************* */ var myObject = { name: 'foo', sayName: function () { console.log('My Name is ' + this.name); } }; myObject.sayName(); console.log(myObject.hasOwnProperty('name')); console.log(myObject.hasOwnProperty('nickName')); myObject.sayNickName(); /* *************************************** 4-39 예제 ******************************************* */ // Person 생성자 함수 function Person(name, age, hobby) { this.name = name; this.age = age; this.hobby = hobby; } // foo 객체 생성 var foo = new Person('foo', 30, 'tennis'); // 프로토타입 체이닝 console.log(foo.hasOwnProperty('name')); // true // Person.prototype 객체 출력 console.dir(Person.prototype); /* *************************************** 4-40 예제 ******************************************* */ String.prototype.testMethod = function () { console.log('This is the String.prototype.testMethod()'); }; var str = "this is test"; str.testMethod(); console.dir(String.prototype); /* *************************************** 4-41 예제 ******************************************* */ function Person(name){ this.name=name; } var foo = new Person('foo'); //foo.sayHello(); Person.prototype.sayHello = function(){ console.log('Hello'); } foo.sayHello(); /* *************************************** 4-42 예제 ******************************************* */ // Person() 생성자 함수 function Person(name) { this.name = name; } // getName() 프로토타입 메서드 Person.prototype.getName = function () { return this.name; }; // foo 객체 생성 var foo = new Person('foo'); console.log(foo.getName()); // foo //Person.prototype 객체에 name 프로퍼티 동적 추가 Person.prototype.name = 'person'; console.log(Person.prototype.getName()); // person /* *************************************** 4-43 예제 ******************************************* */ // Person() 생성자 함수 function Person(name) { this.name = name; } console.log(Person.prototype.constructor); // foo 객체 생성 var foo = new Person('foo'); console.log(foo.country); // 디폴트 프로토타입 객체 변경 Person.prototype = { country: 'korea' }; console.log(Person.prototype.constructor); // bar 객체 생성 var bar = new Person('bar'); console.log(foo.country); console.log(bar.country); console.log(foo.constructor); console.log(bar.constructor); // 출력 결과 /* function Person(name) { this.name = name; } undefined function Object() { [native code] } undefined korea function Person(name) { this.name = name; } function Object() { [native code] } */ /* *************************************** 4-44 예제 ******************************************* */ // Person() 생성자 함수 function Person(name) { this.name = name; } Person.prototype.country = 'Korea'; var foo = new Person('foo'); var bar = new Person('bar'); console.log(foo.country); console.log(bar.country); foo.country = 'USA'; console.log(foo.country); console.log(bar.country); <file_sep>/guide/개발 라이브러리 가이드/CI/04. Board_dao.md <style>.blue {color:#2844de;font-size:18px;}.red {color:#dd4814;font-size:18px;}.ex {color:gray;}p.me{padding:10px 8px 10px;line-height:20px;border:1px solid black;}.center{text-align:center;}</style> ## 04 Board\_dao Board\_dao는 주로 데이터베이스에서 리스트를 가져올때와, 게시물 갯수를 알아낼 때 사용할 수 있습니다. #### controller : controller/사용할\_클래스\_파일.php ```js class 사용할_클래스_파일 extends CI_Controller{ function 사용_될_함수(){ // selectCount : 게시물 갯수 $변수명 = $this->Board_dao->selectCount('테이블_이름', 'where_조건', 'like_조건'); // selectList : 게시물 리스트 $변수명 = $this->Board_dao->selectList('select할_컬럼명','테이블명','where_조건', 'like_조건' , 'order_by', '한페이지당_표시할_게시물_갯수', 'page_번호'); } } ``` #### model : model/Board\_dao ```js <?php /** * @Class Board_dao * @Date 2014. 08. 08 * @Author 비스톤스 * @Brief 게시판 DAO */ class Board_dao extends CI_Model { /** * @brief __construct : 생성자 */ function __construct() { parent::__construct(); } /** * @brief selectCount : 리스트 카운트 * @param String $table_name : 테이블 명 * String $where : WHERE 배열 * String $like : LIKE 배열 * * 리스트의 갯수 출력 */ function selectCount($table_name, $where="", $like="") { // 테이블 이름 : $table_name, where 조건절 값 : $where="", like 조건절 값 : $like="" if($where != "") { // where에 값이 있으면 아래의 foreach구문을 실행합니다. foreach($where as $key => $val){ // $key = 컬럼명 , $val = 값 if($val != "") { // $val에 값이 있으면 [ == where절에서 찾고자하는 값이 있다면 ] $this->db->where($key, $val); // where문에 $key와 $val를 담아서 쿼리를 만듭니다. } } } if($like != "") { // like에 값이 있다면, $count = 1; // $count는 $like조건을 실행할 횟수를 저장하는 변수로, 1로 초기화한 후 시작한다. foreach($like as $key => $val){ // $like에서 컬럼명을 $key로, 컬럼의 값을 $val로 저장한다. if($val != "") { // $val에 값이 있으면, [ == 찾고자하는 값이 있다면, ] $where_text = ""; // $where_text를 초기화합니다. $where_text .= $key." LIKE '%".$val."%'"; // $where_text에 where에 넣을 like구문을 만들어 저장합니다. if(count($like) == "1") { // $like에 값이 1개 이면, $this->db->where($where_text); // 더이상 like구문을 만들지 않아도 됨으로, // where문에 위에서 만들었던 $where_text를 파라미터로 넘겨주어 where절을 만듭니다. } else { // $like에 값이 2개 이상 존재한다면, 아래의 if문을 실행한다. if($count == "1") { // $count 가 1이면 $this->db->where($where_text); // where절에 $where_text를 넘겨서 where절을 만듭니다. } else if($count == count($like)) { // $count가 1이 아니고 $like의 값의 갯수와 같다면 $this->db->or_where($where_text); // or_where절에 $where_text를 넘겨서 or_where절을 만듭니다. // WHERE name != 'Joe' OR id > 50 // ──┬─── ─────┬───── // └────── or_where ──────┘ } else { // $count가 1이 아니고 $like의 값의 갯수와 같지 않다면, $this->db->or_where($where_text); // or_where절에 $where_text를 넘겨서 or_where절을 만듭니다. } } $count++; // $count 횟수 1 증가 } } } return $this->db->count_all_results($table_name); // 반환값으로 실행된 쿼리의 결과를 가집니다. // count_all_results는 쿼리를 통해 적용될 레코드의 수를 반환합니다. } /** * @brief selectList : 리스트 * @param String $field : 컬럼 명 * String $table_name : 테이블 명 * String $where : WHERE 배열 * String $like : LIKE 배열 * String $where_name : WHERE 컬럼명 * int $limit : 페이지 크기 * int $offset : 페이지 번호 * * selectList는 데이터베이스에서 리스트를 출력합니다. * */ function selectList($field="*", $table_name, $where="", $like="", $order, $limit, $offset) { // field = 컬럼 선택 , table_name = 테이블명 , where = where절 , like = like절 , order = 정렬 방식 , limit = 갯수 , offset = 시작번호 $this->db->select($field); // 파라미터로 전달받은 $field로 select쿼리를 만듭니다. if($where != "") { // $where변수에 값이 존재한다면 foreach($where as $key => $val){ // $where변수에서 key와 val를 분리하여 각각 $key, $val에 저장합니다. if($val != "") { // $val 값이 있으면 $this->db->where($key, $val); // $where절을 만듭니다. } } } if($like != "") { // $like에 값이 있으면 $count = 1; // like갯수를 체크할 변수 $count를 만들고 1로 초기화합니다. foreach($like as $key => $val){ // $like에서 key와 val을 분리하여, 각각 $key와 $val에 저장합니다. if($val != "") { // $val에 값이 있다면 $where_text = ""; // $where_text변수를 만들고 초기화 한뒤, $where_text .= $key." LIKE '%".$val."%'"; // $key와 $val변수를 이용하여 Like절을 만들고 $where_text변수에 저장합니다. if(count($like) == "1") { // $like의 값의 갯수가 1이면 $this->db->where($where_text); // 위에서 만든 Like구문인 $where_text를 where함수에 파라미터로 전달하여 where절을 만듭니다. } else { // $like의 갯수가 1보다 크면 아래의 내용을 수행합니다. if($count == "1") { // $count가 1이면 $this->db->where($where_text); // 위에서 만든 Like구문인 $where_text를 where함수에 파라미터로 전달하여 where절을 만듭니다. } else if($count == count($like)) { // $count값이 $like의 값의갯수와 같다면 $this->db->or_where($where_text); // 위에서 만든 Like구문인 $where_text를 or_where함수에 파라미터로 전달하여 where절을 만듭니다. }else { // $count값이 1이 아니고, $like의 값의갯수와 다르다면 $this->db->or_where($where_text); // 위에서 만든 Like구문인 $where_text를 or_where함수에 파라미터로 전달하여 where절을 만듭니다. } } $count++; // $count의 값을 1 증가시킵니다. } } } $this->db->order_by($order); // 파라미터로 전달받은 $order를 이용하여 order_by절을 만듭니다. $query = $this->db->get($table_name, $limit, $offset); // $table_name(테이블이름)과 $limit(갯수), $offset(출력 시작값)을 // get()함수에 파라미터값으로 전달하여 쿼리문을 완성한뒤 , $query에 저장합니다. return $query->result(); // 반환값으로 쿼리실행결과를 갖습니다. } } ?> ```<file_sep>/javascript/inside_javascript/chapter08 jQuery 소스코드 분석/README.md ## 8. jQuery 소스 코드 분석 - jQuery 1.0의 소스코드 구조 - jQuery 1.0의 ID 셀렉터 동작 분석 - jQuery 1.0의 이벤트 핸들러 분석 #### 8.1.1 jQuery 함수 객체 - new 연산자를 이용해 **`jQjery` 객체를 생성하는 기능** ```javascript // If the context is global, return a new object if ( window == this ) return new jQuery(a,c); ``` #### 8.1.2 변수 `$` 를 `jQuery()` 함수로 맵핑 ```javascript // Map the jQuery namespace to the '$' one var $ = jQuery; ``` #### 8.1.3 jQuery.prototype 객체 변경 - 모든 함수 객체는 prototype 프로퍼티가 있다. - 특히 prototype 프로퍼티가 가리키는 프로토 타입 객체는 함수가 생성자로 동작할 때, 이를통해 새로 생성된 객체의 부모 역할을 한다. > 즉 new 연산자로 jQeury() 생성자 함수를호출할 경우~ > 생성된 jQuery 객체는 [[prototype]]링크로 자신의 프로토타입인 jQuery.prototype객체에 접근 가능하다. ```javascript jQuery.fn = jQuery.prototype = { jquery: "$Rev: 509 $", size: function() { return this.length; }, } ``` jQuery의 프로토타입을 jQuery.fn 프로퍼티가 참조하게 하고. 이제 이후에 생성된 jQuery 객체 인스턴스는 **변경된 프로토타입 객체**에 정의된 다양한 메소드를 프로토타입 체이닝으로 사용할 수 있다. #### 8.1.4 객체 확장 - extend() 메소드 - jQuery 소스코드에서는 다음 코드와 같이 다른 객체의 프로퍼티아 메소드 복사등으로 객체의 기능을 추가하는 데 사용가능한 `extend()메소드`를 제공한다. - jQuery 소스코드 곳곳에 jQuery 객체 및 jQuery.prototype 객체를 확장하는 부분으로 볼 수 있다. ```javascript jQuery.extend = jQuery.fn.extend = function(obj,prop) { if ( !prop ) { prop = obj; obj = this; } //1. for ( var i in prop ) obj[i] = prop[i]; //2. return obj; }; ``` 1) 함수를 호출할 때 obj 인자 하나만을 넘겨서 호출하는 경우, prop 인자가 undefind 값을 가지므로 !prop가 참이 되면서 if 문 이하 출력 if 문 내부 코드를 살펴보면 obj 인자로 전달된 객체를 prop 매개변수에 저장한다. 그리고 obj 매개변수에는 this를 저장한다. 여기서 함수 호출 패턴에 따라, 함수 호출 extend()메소드가 어디서 호출되는지에 따라서 다르게 바인딩된다. > jQuery 함수 객체에서 extend()메소드가 호출될 경우 **this** -> **jQuery 함수객체**로 > jQuery.prototype 객체에서 extend() 메소드가 호출될 경우 **this** -> **jQeury.prototype 객체**로 바인딩 된다. 2) `for in` 문으로 prop 인자의 모든 프로퍼티를 obj 인자로 복사하는 코드다. obj 객체에 prop 객체의 프로퍼티가 추가된다. ** 정리해보자면** > extend()메소드는 단어의 뜻 그대로 **객체의 기능을 추가**하는 것이다. > 또한 주의할점은 obj 인자 하나만으로 호출될 경우다. > ==(js는 java와 다르게 파라미터를 유동적으로 보낼수 있다는점 상기!!!!!)== > 만약 obj 인자 하나만으로 호출됬다면, 이메소드를 호출한 객체의 this가 obj가 된다. > 결국, 메소드를 호출한 객체(this)에다 obj 인자로 넘긴 객체를 복사하는 결과가 된다.. #### 8.1.5 jQuery 소스코드의 기본 구성 요소 jQuery 소스코드는 크게 세 부분으로 구성된다. - jQuery 함수객체 - jQuery.prototype 객체 - jQuery 객체 인스턴스 jQuery() 함수의 가장 기본적인 열할은 new 연산자로 **jQuery 객체를 생성**하는 것이고, 이렇게 생성된 **jQuery 객체**는 프로토타입 체이닝으로 **jQuery.prototype 객체**에 포함된 **프로토타입 메소드**를 호출할 수 있다. 이때 jQuery 함수 객체는 자신이 메소드를 포함하고 있는데, 이러한 jQuery 함수 객체의 메소드는 각각 생성된 jQuery 인스턴스 객체에 특화되지 않고 범용적으로 사용되는 jQuery 코어 메소드로 구성된다. --- ### 8.2 jQuery의 id 셀렉터 동작 분석 제일 궁금했던 아래와 같은 클래스 아이디 연산자 컨트롤을 어떠헤 구현했는가?? 에대한 내용을 알아보자 ```javascript <div id="myDiv" >Hello</div> <script>alert($(#myDiv).text());</script> ``` #### 8.2.1 $("#myDiv") 살펴보기 - `$("#myDiv")` 는 곧 `jQuery("#myDiv")` 결국 jQuery 함수의 첫번째 인자 a 에는 문자열`"#myDiv"`가 전달되고, 두번째 인자 c는 아무런 인자값이 전달되지 않았으므로 `undefind`값이 설정된다. > 왜 인자를 a,c 로 표현했는지? > 앞에서 살펴봤던 jQuery 함수객체의 선언부 소스코드를 다시한번 보자 ```javascript function jQuery(a,c) { ////////////////////////////// 1. ////////////////////////////////////// // 인자 a가 함수이고, jQuery.fn.ready가 참이면? if ( a && a.constructor == Function && jQuery.fn.ready ) return jQuery(document).ready(a); /** * 함수를 호출할 때 첫번째 인자 a는 문자열 "#myDiv"이므로 생성자를 확인하는 a.constructor 값은 'String'이 된다. * a.constructor이 Function인 경우는 a 인자가 함수일 때다. 결국 a는 함수가 아니므로 if문 이하는 실행되지 않는다. */ ////////////////////////////// 1. ////////////////////////////////////// ////////////////////////////// 2. ////////////////////////////////////// // Make sure that a selection was provided a = a || jQuery.context || document; /** * 인자 a 의 디폴트값을 저장하는 코드. a는 문자열이므로 || 연산자 오른쪽 부분은 실행되지 않고 그대로 "#myDiv" 값을 가진다 */ ////////////////////////////// 2. ////////////////////////////////////// ////////////////////////////// 3. ////////////////////////////////////// // 인자 a가 jquery 프로퍼티를 가지고 있는 객체라면? if ( a.jquery ) return $( jQuery.merge( a, [] ) ); /** * a는 "#myDiv" 문자열이므로 jquery 프로퍼티를 가지는 객체가 아니다 따라서 if 문 이하는 실행되지 않는다. * 왜 jquery 프로퍼티를 가지는지 확인할까? 소스코드 라인 62 참조!! */ ////////////////////////////// 3. ////////////////////////////////////// ////////////////////////////// 4. ////////////////////////////////////// // 인자 c가 jquery 프로퍼티를 가지고 있는 객체라면? if ( c && c.jquery ) return $( c ).find(a); /** * c의 값은 현재 undefind 이므로 거짓!( "#myDiv" 예제의 경우다 ) */ ////////////////////////////// 4. ////////////////////////////////////// ////////////////////////////// 5. ////////////////////////////////////// // this 값을 살펴서, 현재 jQuery()가 함수 형태로 호출됐는지를 체크한다. if ( window == this ) return new jQuery(a,c); /** * this 값을 살펴서 jQuery()가 어떤 형태로 호출됐는지를 체크한다. * this가 전역객체 window로 바인딩되는 경우는 jQuery()를 함수 형태로 호출하는 경우다. * $("#myDiv") 는 함수 호출 형태이므로 this는 window에 바인딩된다. * 따라서 if 문은 참이 되고, new 연산자와 함께 생성자 함수 형태로 다시 호출된다. * 생성자 함수 형태로 호출돼도 1~4번 까지는 앞의 실행결과와 같은 반면 5. 에서 jQuery 가 생성자 함수로 호출될 경우 * this는 새로 생성되는 빈 객체에 바인딩되므로 window가 아니고 if문 이하는 실행되지 않느다. */ ////////////////////////////// 5. ////////////////////////////////////// ////////////////////////////// 6. ////////////////////////////////////// // Handle HTML strings var m = /^[^<]*(<.+>)[^>]*$/.exec(a); if ( m ) a = jQuery.clean( [ m[1] ] ); /** * js 에서 슬래쉬(/)는 정규표현식 리터럴을 만드는 기호다. * 이 정규표현식은 다음과 같다. * 1. 빈 문자열이나 '<' 문자를 제외한 문자나 문자열로 시작하고, * 2. 중간에 태그(<>) 형태의 문자나 문자열이 있으며, * 3. 빈 문자열이나 '>'문자를 제외한 문자나 문자열로 끝난다. * '<li>' , 'abc<a>def' 는 위의 정규표현식을 만족한다. * '#myDiv' 는 위 정규표현식에 일치하지 않으므로 exec()메소드의 실행결과는 null값이 된다. 즉 if문 이하는 실행되지 않는다. */ ////////////////////////////// 6. ////////////////////////////////////// ////////////////////////////// 7. ////////////////////////////////////// // Watch for when an array is passed in this.get( a.constructor == Array || a.length && !a.nodeType && a[0] != undefined && a[0].nodeType ? // Assume that it is an array of DOM Elements jQuery.merge( a, [] ) : // Find the matching elements and save them for later jQuery.find( a, c ) ); /** * this.get() 메소드를 호출하는 코드다. * 삼항 연산자로 ? 연산의 조건 부분이 true 이면 jQuery.merge()메소드가 호출되고, false면 jQuery.find()메소드가 호출된다. * a.constructor == Array * a는 '#myDiv' 문자열이므로 a.constructor 값은 'String'이다. 따라서 false * a.length * a는 문자열이므로 length 프로퍼티가 있고, 이는 문자열 길이를 의미한다.'#myDiv'는 6 즉 이값은 true * !a.nodeType * a는 문자열이므로 nodeType 프로퍼티가 없으므로 undefined 값을 가지므로 true * a[0] != undefined * a는 문자열이므로 배열의 인덱스 값을 이용해서 접근할 수 있다. * 따라서 a[0]은 문자열의 첫 번째 문자를 의미하므로 예제에서는 '#'가된다. 즉 여기서는 true * a[0].nodeType * 예제에서 a[0]인 '#'는 문자열을 나타낼뿐 nodeType 프로퍼티를 가지는 DOM 객체가 아니므로 이 표현식은 false * 이를 종합해보면 앞의 조건 전체는 false가 되므로 jQuery.find(a.c)문이 실행되게 된다. */ ////////////////////////////// 7. ////////////////////////////////////// // See if an extra function was provided var fn = arguments[ arguments.length - 1 ]; // If so, execute it in context if ( fn && fn.constructor == Function ) this.each(fn); } ``` ##### 8.2.1.1 jQuery.find(a.c) 살펴보기 jQuery.find()는 jQuery 함수 객체 내에 포함된 메소드로서, jQuery의 셀렉터 기능을 처리하는 중요한 함수다. ```javascript find: function( t, context ) { // Make sure that the context is a DOM Element if ( context && context.nodeType == undefined ) context = null; ..... 이하 생략 ``` 예제에서는 `jQuery.find('#myDiv')`형태로 호출하므로 다음 `find()` 메소드의 인자 t에는 문자열 '#myDiv'이 전달되고, 아무 인자도 전달되지 않은 context 매개변수에는 undefined 값이 할당된다. --- ### 8.3 jQuery 이벤트 핸들러 분석 jQuery는 브라우저에서 제공하는 다양한 이벤트를 처리하는 이벤트 핸들러를 제공한다. jQuery로 이벤트 핸들러를 만들어보고, 직접 소스를 보면서 동작 원리를 분석해보자. #### 8.3.1 jQuery 이벤트 처리 예제 ```javascript <!DOCTYPE html> <html lang="ko"> <head> <meta http-equiv="X-UA-Compatible" content="IE=Edge"> <meta charset="UTF-8"> <title>문서 제목</title> <script src="jquery-1.0.js"></script> </head> <body> <div id="clickDiv">Click Here</div> <script> $('#clickDiv').click(function(){ alert('Mouse Click'); }) </script> </body> </html> ``` #### 8.3.2 click() 메소드 정의 우선 .click()메소드가 jQuery에서 어떻게 정의되어 있는지를 살펴보자. ```javascript new function(){ //1. /** * 인자가 없는 생성자 함수를 호출할 경우에 괄호를 생략할 수 있다. */ //2. var e = ("blur,focus,load,resize,scroll,unload,click,dblclick," + "mousedown,mouseup,mousemove,mouseover,mouseout,change,reset,select," + "submit,keydown,keypress,keyup,error").split(","); /** * 각 문자열을 split()메소드로 ','로 구분해서 배열을 만들고, 이것을 변수 e에 저장한다. ( clikc 도 여기에 포함 ) */ for ( var i = 0; i < e.length; i++ ) new function(){ //3. var o = e[i]; /** * 2 에서 구한 배열 e를 for문을 돌려서 1과 유사한 new function(){}문을 수행한다. * 즉 각배열별로 매번 new function(){}함수로 둘러쌓인 코드를 수행한다. */ // Handle event binding jQuery.fn[o] = function(f){ //4. return f ? this.bind(o, f) : this.trigger(o); }; /** * click을 포함해서 2에서 지정한 blur, focus, load 등과 같은 이벤트 처리 메서드가 jQuery.prototype 객체에 추가된다. * click을 예로 들면 다음과 같다 * function(f){ * return f ? this.bind(click,f) : this.trigger(click); * } */ ... 생략 }; ... 생략 }; ``` #### 8.3.3 $('#clickDiv').click() 호출 코드 분석 ```javascript function(f){ return f ? this.bind(click,f) : this.trigger(click); } ``` `$('#clickDiv').click(...)` 메소드가 호출되면, 앞 절에서 알아본 것처럼 click()메소드가 호출된다. 이때 인자 `f` 로는 click() 메소드를 호출할 때 인자로 넘긴 함수 표현식 `function(){alert('Mouse Click');}`이 그대로 전달된다. 즉 삼항 연산자의 조건문이 true가 되어 내부적으로는 `this.bind(click,f)`메소드가 다시 호출된다. ==이때 click()메소드에서 사용된 `this`는 무엇일까?== 이에 대한 답은 click()메소드를 누가 호출했는지에 달려있는데 `click()`메소드를 호출하는 주체는 `#('#clickDiv')의 실행결과인 jQuery 객체`이므로 메소드 호출패턴으로 객체가 this로 바인딩된다. #### 8.3.4 $('#clickDiv').bind() 메소드 분석 ##### 8.3.4.1 bind() 메소드 정의 `bind()`메소드 또한 jQuery 객체 인스턴스에 정의되어 있지 않다. 짐작할 수 있듯이 bind()메소드는 jQuery.prototype 객체에 정의되어 있는 프로토타입 메소드일 것이고, 결국 프로토타입 체이닝으로 호출될 것이다. 하지만 jQuery 소스코드를 얼핏 봐서는 bind()메소드가 어디에 정의되어 있는지 찾기 쉽지 않은데. 그 이유는 여러 단계의 코드를 거쳐 이 메소드가 동적으로 생성되기 때문이다. ##### 8.3.4.2 $('#clickDiv').bind() 호출 ```javascript ////////////// 1. ////////////// // click 메소드 실행 $('#clickDiv').click(function(){ alert('Mouse Click'); }); ////////////// 1. ////////////// ////////////// 2. ////////////// // click() 메소드 정의 function click(f){ return f ? this.bind('click', f) : this.trigger('click'); } ////////////// 2. ////////////// ////////////// 3. ////////////// // bind() 메소드 정의 jQuery.fn["bind"] = function(){ return this.each(n, arguments); } ////////////// 3. ////////////// ////////////// 4. ////////////// // bind() 메소드의 매개변수 n으로 전달된 익명함수 function( type, fn ){ if(fn.constructor == String) fn = new Function("e", (!fn.indexOf(".") ? "$(this)" : "return " ) + fn); jQuery.event.add( this, type, fn ); } ////////////// 4. ////////////// ``` **2.** > `1.` 에서 .click()메소드를 호출할 때 매개변수 f로 익명 함수가 전달됐으므로 `this.bind('click',f)`메소드가 호출된다. > 또한 this는 `$('#clickDiv')`에 해당하는 jQuery 객체로 바인딩된다 > 따라서 이 코드는 `$('#clickDiv').bind('click',f)`가 호출되는 것과 같다 **3.** > `2.` 에서 `$('#clickDiv').bind('click',f)` 메소드가 호출될 경우 `.bind()` 메소드가 호출되고 결국 다음 코드가 수행된다. > ```javascript > this.each(n, arguments); > ``` > this는 메소드 호출 패턴으로 `$('#clickDiv')`객체에 바인딩된다. > `each()`메소드의 첫 번째 인자 `n`에는 4번 영역에 해당하는 익명함수가 할당된다. > 두번째 인자인 arguments 에는 bind()메소드를 호출할때 전달한 인자가 배열 형태로 저장된 유사배열 객체다 > `bind('click',f)` 와 같이 bind()메소드를 호출했으므로, > arguments 객체 값은 `arguments[0] = 'click'` `arguments[1] = f`와 같다 ##### 8.3.4.4 jQuery.event.add(this, type, fn)메소드 호출 분석 jQuery.event 객체는 jQuery에서 실제로 이벤트 핸들러를 처리하는 역할을 담당한다. jQuery.event 객체에는 이벤트 핸들러를 등록하고, 삭제하는 `add()`, `remove()메소드`, 특정 이벤트가 발생할 때 이에 해당하는 이벤트 핸들러를 수행하는 `handle() 메소드`등이 정의되어있다. > 참고로 jQuery 1.0 에서는 <NAME>라는 개발자가 작성한 이벤트 핸들러 라이브러리를 그대로 차용하고 있다. jQuery 에서는 이렇게 브라우저가 호출할 DOM 이벤트 핸들러를 모두 같은 `jQuery.event.handle()`메소드로 설정한다. ==결국 브라우저는 jQuery에서 등록한 이벤트(click, focus등)가 발생하면 jQuery.event.hanle() 메소드만을 호출한다.== jQuery는 브라우저가 제공하는 이벤트 핸들러 메커니즘을 jQuery 기반으로 다시 재구성하는 과정이라고 생각하면 된다. #### 8.3.5 Click 이벤트 핸들러 실행 과정 `<div id='clickDiv'>` 태그가 실제 클릭됐을때, 브라우저는 이 태그에 해당하는 DOM 객체의 onclick 프로퍼티에 등록된 이벤트 핸들러 함수를 호출한다. 이에 반해 jQuery에서는 onclick,onmousedown 등과 같은 DOM 이벤트 핸들러를 `jQuery.event.handle() 메소드`로 변경하고, 이 메소드로 하여금 사용자가 등록한 실제 이벤트 핸들러를 처리하고 있다. ```javascript handle: function(event) { if ( typeof jQuery == "undefined" ) return; event = event || jQuery.event.fix( window.event ); // If no correct event was found, fail if ( !event ) return; var returnValue = true; var c = this.events[event.type]; for ( var j in c ) { if ( c[j].apply( this, [event] ) === false ) { event.preventDefault(); event.stopPropagation(); returnValue = false; } } return returnValue; }, ``` DOM 객체의 onclick 프로퍼티 `jQuery.event.handle()` 메소드를 호출했으므로 클릭이 발생할 경우 위의 `handle() 메소드`가호출된다. `handle()메소드`는 event 인자를 받는 함순데, 여기에는 발생한 이벤트에 따라 다양한 정보를 가지고 있다. 가령 click이나 mousemove 과 같은 이벤트 타입, 이벤트가 발생한 노드 같은 기본정보 뿐만 아니라, click 같은 마우스 이벤트의 경우 마우스가 클릭된 자표 정보, 마우스의 어떤 버튼이 눌렸는지 등의 정보를 포함하고 있다. > 또한 여기서 this는 `이벤트가 발생한 DOM 객체`가 된다. #### 8.3.6 jQuery 이벤트 핸들러 특징 jQuery의 이벤트 핸들러 처리는 onclick 프로퍼티 같은 DOM 이벤트 핸들러를 직접 사용하지 않고, DOM 객체 내에 자체 `이벤트 관련 프로퍼티(events 객체)`를 생성하고 각 이벤트 타입별로 여러개의 이벤트 핸들러를 동시에 등록할 수 있다. 때문에 jQuery에서는 여러 개의 이벤트 핸들러가 동시에 수행될 수 있는 장점이 있다. ```javascript <!DOCTYPE html> <html lang="ko"> <head> <meta http-equiv="X-UA-Compatible" content="IE=Edge"> <meta charset="UTF-8"> <title>문서 제목</title> <script src="jquery-1.0.js"></script> </head> <body> <div id="clickDiv" onclick="alert('Mouse Click1')">Click Here</div> <script> $('#clickDiv').click(function(){ alert('Mouse Click2'); }) $('#clickDiv').click(function(){ alert('Mouse Click3'); }) </script> </body> </html> ``` 직접 콘솔창에 `$('#clickDiv')`객체를 찍어보면 events.click 객체의 프로퍼티로 등록했음을 볼 수 있다. <file_sep>/guide/개발 라이브러리 가이드/CI/07 . bs_html_helper.md <style>.blue {color:#2844de;font-size:18px;}.red {color:#dd4814;font-size:18px;}.ex {color:gray;}p.me{padding:10px 8px 10px;line-height:20px;border:1px solid black;}.center{text-align:center;}</style> ## 07 . bs\_html\_helper ──────────────────────순서────────────────────── 1. 셀렉트 박스 생성 and 값 세팅 2. 코드값을 키로 변환 3. 문자열 자르고 ... 붙이기 ──────────────────────────────────────────────── bs_html_helper 클래스는 html페이지에 <b class="blue">select</b> 박스 생성과 값 출력, <b class="blue">코드값을 키로 변환</b> ( [ ex ] 1 = 지구, 2 = 태양 , 3 = 달) , <b class="blue">문자열을 자르고 ... 을 붙이기</b>의 기능을 가지고 있습니다 --------------------- ### 셀렉트 박스 생성 and 값 세팅 ```js <?php function getSelectBox($arrName, $intRsValue, $intInterval) { // getSelectBox()의 첫번째 파라미터 값으로 셀렉트의 value와 text가 들어있는 배열, // 두번째 파라미터 값으로 select될 값, // 세번째 파라미터 값은 배열 안에서 value에들어갈 값 사이의 간격입니다. // ex ] getSelectBox($arrSelectType, $selectType, 2) // $arrSelectType = array( // '','전체', // 'reserve_name','성명', // 'reserve_email','이메일', // 'reserve_phone','핸드폰 번호', // 'reserve_seq','번호', // 'reserve_chanel','예약 채널' // ); // $selectType = reserve_name; // 일 때, // 배열 $arrSelectType 에서 0번, 2번, 4번 , .. n+2번째 위치한 값이 option의 value로, // 배열 $arrSelectType 에서 1번, 3번, 5번 , .. n+(2-1)번째 위치한 값이 option의 text로 사용됩니다. // $strHtml 변수 초기화 $strHtml = ''; // 함수 사용시, $intInterval을 지정하지 않으면 1이 부여됩니다. if ( $intInterval == '' ) { $intInterval = 1; } // $strHtml에 select구문을 저장합니다. for ( $i=0; $i<sizeof($arrName); $i = $i + $intInterval) { if ( $intRsValue == $arrName[$i] ) { $strHtml .= "<option value='".$arrName[$i]."' selected>".$arrName[$i+($intInterval-1)]."</option>"; } else { $strHtml .= "<option value='".$arrName[$i]."'>".$arrName[$i+($intInterval-1)]."</option>"; } } // 작성이 완료된 $strHtml을 출력합니다. echo $strHtml; } ?> ``` ------------------------------- ### 코드값을 키로 변환 데이터베이스에 저장된값이 1, 2, 3, 4 등과 같은 기호로 되어있는 경우에, 배열에 미리 기호와 그에 해당하는 문자열을 입력하여 getCodeKeyChange()함수를 이용, 간단하게 표시할 수 있습니다. ```js function getCodeKeyChange($arrName, $intRsValue) { // getCodeKeyChange()의 첫번째 파라미터 : 기호와 문자열이 정의된 배열 // getCodeKeyChange()의 두번째 파라미터 : 선택된 값 // ex ] getCodeKeyChange($arrReserveChanel , $reserveVo['reserve_chanel']) // $arrReserveChanel = array ( // 'P','PC', // 'm','Mobile' // ); // $reserveVo['reserve_chanel'] = 'P'; // 일 때, // 배열 $arrReserveChanel 에서 0번, 2번, 4번 , .. n+2번째 위치한 값이 비교될 값이고, // 배열 $arrReserveChanel 에서 1번, 3번, 5번 , .. n+1번째 위치한 값이 출력될 값으로 사용됩니다. for ( $i=0; $i<sizeof($arrName); $i = $i+2) { if($intRsValue == $arrName[$i]) { echo $arrName[$i+1]; } } } ``` ------------------------------- ### 문자열 자르고 ... 붙이기 > strcut()함수는 > 문자열의 길이가 보여졌으면 하는 길이보다 길때, > 문자열을 원하는 길이만 보이게하고, 뒤에 '...'을 붙여 출력하게 해주는 함수 입니다. ```js function strcut($str,$len) { // strcut()의 첫번째 파라미터 : 출력할 문자열 // strcut()의 두번째 파라미터 : 출력하고자 하는 문자열 길이 // ex ] strcut($str , 7) // $str = "abcdefghijklmn 하하하하하하"; // 일 때, // strlen()함수를 이용하여 $str의 길이를 알아낸후, $len값과 비교하여 , // ..을 포함한 길이가 $len이 될 때까지 값을 출력합니다. // // 결과 : abcde.. if (strlen($str) > $len){ $len = $len-2; for ($pos=$len; $pos>0 && ord($str[$pos-1])>=127;$pos--); // ord:특정 문자를 아스키 값으로 변환하는 함수 if (($len-$pos)%2 == 0) $str = mb_strcut($str, 0, $len,'utf-8') . ".."; else $str = mb_strcut($str, 0, $len+1,'utf-8') . ".."; // mb_strcut() : 글자 자르는 함수. // ※ UTF-8의 글자당 byte수는 3byte입니다. } return $str; } ```<file_sep>/java/diskstaion_java_lec/03/DataType3.java public class DataType3 { public static void main(String[] args) { System.out.println("1.-------------"); //제어문자: 인쇄할 수 없거나 키보드로 표현할 수 없는 특별한 문자를 가리키며, 역슬래시(\)와 한개의 문자와 결합하여 작성. } }<file_sep>/python/algorithm/README.md # algorithm with python ##**학습목표** 파이썬의 기초문법과 기능등을 손에 익히고, 더불어 뉴런 어딘가에서 방황하고 있을 10년전의 지식을 끄집에 내기위해 위해 가장 기초적인 알고리즘을 풀어보자 --- ###1) `1`부터 정수`n`까지의 합 - for문과 연산자 ```python def sum_n(n): s=0 for i in range(1,n+1): s= s+i return s print(sum_n(5)) print(sum_n(100)) ``` ```bash 55 5050 ``` ##### Q1) 시간복잡도를`O(n)`개선할 방법은 없을까? ```python def sum_n(n): # //는 정수 나눗셈을 할때 사용 return n*(n+1)//2 ``` ### 2) 최대값 구하기 - python의 리스트 | 함수 | 설명 | |--------|--------| | `len(a)` | 리스트 길이 | |`append(v)`|리스트 맨 뒤에 값`v` 추가| |`insert(i,v)`|`i`번째에 값`v` 추가| |`pop(i)`|`i`번째에 값을 리스트에서 빼면서 값 리턴| |`clear()`|리스트 모든 값 삭제| |`v in a`|값`v`가 리스트`a` 안에 있는지 `boolean`으로 리턴| ```python def max(a): n=len(a) r = a[0] for i in range(0,n): if r < a[i]: r = a[i] return r # 대괄호에 쉼표로 구분 v=[17,92,18,33,58,7,33,42] print(max(v)) ``` ```bash 92 ``` ### 3) 같은 이름 찾기 - python의 집합`set` > 리스트와 달리 같은자료가 중복으로 들어가지 않고 자료 순서도 의미가 없다 | 함수 | 설명 | |--------|--------| | `len(a)` | 집합의 값 갯수 | |`add(v)`|값`v`추가| |`discard(v)`|값`v`가 존재한다면 삭제(없으면 변화 무)| |`clear()`|모든 값 삭제| |`v in a`|값`v`가 집합`a` 안에 있는지 `boolean`으로 리턴| ```python def same_name(a): n=len(a) result = set() for i in range(0, n-1): for j in range(i+1, n): if a[i] == a[j]: result.add(a[i]) return result v=["Risa", "Jenny", "Jisoo", "Jenny","Rose","Risa"] print(same_name(v)) ``` ```bash # 순서가 의미 없는 set이므로 {'Risa', 'Jenny'} or {'Jenny', 'Risa'} ``` ### 4) factorial 구하기 - Recursion ```python ``` <file_sep>/게시판만들기/c-cgi-mysql 게시판 만들기/cgi-bin/list.c #include "common.h" #include "db_lib.h" #include "pagination.h" // gcc -o list.cgi list.c cgic.c -I/usr/include/mysql -L/usr/local/lib/mysql -lmysqlclient // gcc -o mysqltest mysqltest.c -I /usr/include/mysql -L /usr/local/lib/mysql -lmysqlclient int cgiMain(void) { // 헤더 속성 최상단에 위치 - 헤더위에 print 문등이 있으면 500 error 발생 printf("%s%c%c\n","Content-Type:text/html;charset=utf-8",13,10); unsigned int count; // form 데이터 cgiFormString("title", title, MAX_LEN); cgiFormString("name", name, MAX_LEN); cgiFormString("content", content, MAX_LEN); cgiFormInteger("page", &page, 1); cgiFormString("search", search, MAX_LEN); cgiFormString("search_type", search_type, MAX_LEN); // DB연결 및 연결실패시 에러 console 출력 함수 mysqlDbConn(); // DB 셀렉트 함수 total_count = mysqlDbSelect(search_type, search); /* * 페이징에 필요한 변수 * page : 현재 페이지 * list : 한 페이지에 보여질 게시물수 (defaultt 10) * block_page_num_list : 한번에 보여질 블록(페이지묶음)의 수 (default 5) * total_count : 쿼리로 계산되는 총 게시물수 * * list는 10 block_page_num_list는 5로 기본값이 설정되어있다. 필요시 아래처럼 두개의 변수값만 바꿔서 사용한다. * list = 5; * block_page_num_list = 10; */ // 페이징 수식 계산함수 // pagingInit(page, list, block_page_num_list, total_count); // Limit 적용한 최종 쿼리(페이징 데이터용) mysqlDbSelectLimit( search_type, search, limit, list ); if( strcheck(search_type) ){ sprintf(search_query, "&search_type=%s&search=%s", search_type, search); } else{ sprintf(search_query, ""); } /* // 페이징 변수 확인 printf("page : %d - 1,2,3 등의 실제 페이지 번호 <br>", page); printf("page_num : %d - 페이지번호를 페이징에서 사용하기위해 구분한 변수 <br>", page_num); printf("block_page_num_list : %d - 한블록에 노출될<br>", block_page_num_list); printf("block : %d <br>", block); printf("block_start_page : %d <br>", block_start_page); printf("block_end_page : %d <br>", block_end_page); printf("total_count : %d <br>", total_count); printf("total_page : %d <br>", total_page); printf("limit : %d <br>", limit); printf("list : %d <br>", list); */ printf("<!DOCTYPE html>\n\n"); printf("<HTML lang=\"ko\">\n\n"); printf("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n\n"); printf("<HEAD> \n\n"); printf(" <TITLE>CGI - board</TITLE>\n\n"); //printf(" <link href=\"https://maxcdn.bootstrapcdn.com/bootswatch/3.3.6/paper/bootstrap.min.css\" rel=\"stylesheet\" > \n"); printf(" <link href=\"https://maxcdn.bootstrapcdn.com/bootswatch/3.3.6/slate/bootstrap.min.css\" rel=\"stylesheet\" > \n"); printf(" <script src=\"https://code.jquery.com/jquery-1.12.1.min.js\"></script> \n\n"); printf(" <script > \n"); printf(" function goWrite(){ \n"); printf(" location.href='write.cgi'; \n"); printf(" }; \n"); printf(" $(function(){ \n"); printf(" var form = document.search_frm; \n"); printf(" form.submit \n"); printf(" }); \n"); printf(" </script> \n"); printf("<HEAD>\n\n"); printf("<BODY>\n"); printf("<div class='container' style='margin-bottom: 20px;'>\n"); printf(" <div class='row' >\n"); printf(" <h2 class='pull-left '>CGI - board</h2>\n"); printf(" <form class='form-inline pull-right' style='margin-top:30px;' name='search_frm' id='search_frm' > \n"); printf(" <div class='form-group '> \n"); printf(" <select class='form-control' name='search_type' id='search_type'>"); printf(" <option value=''>선택</option>"); printf(" <option value='title'>제목</option>"); printf(" <option value='name'>작성자</option>"); printf(" </select> \n"); printf(" <input type='text' name='search' class='form-control' id='search' value='%s'> \n", search); printf(" </div> \n"); printf(" <button class='btn btn-default' >검색</button> \n"); printf(" </form> \n"); printf(" <table width='600' class='table table-bordered'>\n"); printf(" <tr>\n"); printf(" <th class='col-xs-1 active' style='text-align:center' >번호</th>\n"); printf(" <th class='col-xs-10 active'>제목</th>\n"); printf(" <th class='col-xs-1 active'>작성자</th>\n"); printf(" </tr>\n"); // 데이터 뿌리기 // while( (row = mysql_fetch_row(res)) != NULL ){ printf(" <tr>"); printf(" <td style='text-align:center' >%s</td>\n", row[0]); printf(" <td><a href='write.cgi?seq=%s'>%s</a></td> \n", row[0], row[1]); printf(" <td>%s</td> \n", row[2]); printf(" <tr>"); } printf(" </table> \n"); printf("<nav style='text-align:center; height:24px' > \n"); printf(" <ul class='pagination' > \n"); // 페이징 // pagingData(); printf(" </ul> \n"); printf("</nav> \n"); printf(" <button class='btn btn-default pull-right' onclick='goWrite();' >글쓰기</button> \n"); printf(" </div>\n"); printf("</div>\n"); printf("</body>\n\n</html>"); // db 열결 해제 // mysqlDbClose(); } <file_sep>/Front-End/snippet/layerPopUp/README.md ## 레이어팝업 > HTML ```html <div class="dim"></div> <div class="modal_box"> <div class="alert_con"> <div class="alert_msg"><h3>LayerPopup</h3></div> <button onclick="confirm();" class="btn_confirm btn_default btn1">확인</button> <button class="close btn_default btn1">닫기</button> </div> </div> <div class="info_btn"> <a href="" onclick="layer_pop(); return false;"><button class="btn_default">Click</button></a> </div> ``` > CSS ```CSS .dim {position:absolute; left:0; top:0; z-index:99; background:#000; display:none; } .modal_box {width:250px; height:170px; display:none; position:absolute; left:50%; top:50%; margin-left:-125px; margin-top:-85px; z-index:100;} ``` - `left : 50%` - `top :50%` - `margin-left:'모달박스 width값의 반만큼 빼기` - `margin-top:'모달박스 height값의 반만큼 빼기` 일반적인 경우 위 형식으로 레이어 팝업의 위치를 중앙정렬 시킬수 있지만 스크롤이 있는 경우나 기타 특별한 경우 height값에서 문제가 생기므로 그럴경우엔 스크립트로 제어해서 중앙정렬 시키면 된다. > Script ```javascript function layer_pop(){ // 상황 별로 left,top 50% 후 margin값으로 중앙정렬 가능할 경우는 아래처럼 사용 // 그게 힘들경우는 offsetWidth, ScrollTop, 등으로 교체하여 사용 var docWidth = $(document).width(); var docHeight = $(document).height(); $('.dim').css( {'width' : docWidth, 'height' : docHeight } ); $('.dim').fadeTo('slow',0.65); $('.modal_box').show(); } function confirm(){ // 확인 메시지 alert('confirm event'); }; $(document).ready(function(){ // 닫기버튼 클릭시 닫기 이벤트 $('.close').click(function(e){ e.preventDefault(); $('.dim, .modal_box').fadeOut('slow'); }); // dim 클릭시 닫기 이벤트 $('.dim').click(function () { $(this).fadeOut('slow'); $('.modal_box').fadeOut('slow'); }); }); // 터치이벤트시 이벤트 발생하지 않도록 unbinding 처리 $('.dim').one('touchstart', function () { $(this).unbind('click'); }); // 브라우져 크기가 조정될때 dim 크기 조절 $(window).resize(function(){ var width = $(document).width(); var height = $(document).height(); $(".dim").width(width).height(height); }); ``` <file_sep>/python/README.md # python - algorithm - python 기초 - (미정...) <file_sep>/Front-End/snippet/README.md # Snippet ## HTML ## CSS ## Javascript & jQuery <file_sep>/javascript/inside_javascript/chapter06 객체지향 프로그래밍/README.md ## 6. 객체지향 프로그래밍 다음에 나오는 객체지향 언어의 특성을 자바스크립트로 구현하는 방법을 알아보자 1. 클래스, 생성자, 메소드 2. 상속 3. 캡슐화 - `C++`이나 `Java` 같은 클래스 기반의 언어와 달리 프로토타입 기반의 언어인 자바스크립트는 객체의 자료구조, 메소드등을 동적으로 바꿀 수 있다. - 정확성, 안정성, 예측성 등의 언어는 클래스 기반의 언어가 좀다 나은 결과를 보인다는 단점이 있고, - 반면 프로토타입 기반인 자바스크립트는 동적으로 자유롭게 객체의 구조와 동작 방식을 바꿀 수 있다는 장점이 있다. ### 6.1 클래서, 생성자, 메소드 C++이나 Java와 같은 경우 class 라는 키워드를 제공하여 클래스를 만들 수 있다. 클래스와 같은 이름의 메소드로 생성자를 구현해 낸다. 하지만 자바스크립트에는 이러한 개념이 없다. 자바스크립트는 거의 모든 것이 객체이고, 특히 함수 객체로 많은 것을 구현해 낸다. 클래스, 생성자, 메소드도 모두 함수로 구현이 가능하다. ```javascript function Person(arg){ this.name=arg; this.getName=function(){ return this.name; } this.setName=function(value){ this.name=value; } } var me = new Person("zzoon"); console.log(me.getName()); me.setName("iamhjoo"); console.log(me.getName()); ``` > 위 코드를 차근 차근살펴보자 아래 형태는 기존 객체지향 프로그래밍 언어에서 한 클래스의 인스턴스를 생성하는 코드와 매우 유사하다. 여기서 함수 `Person`이 **클래스**이자 **생성자**의 역할을 한다. ```javascript var me = new Person("zzoon"); ``` 자바스크립트에서 클래스 기반의 객체지향 프로그래밍은 기본적인 형태가 이와 같다. 클래스 및 생성자의 역할을 하는 함수가 있고, 사용자는 new키워드로 인스턴스를 생성하여 사용할 수 있다. 예제에서 생성된 `me`는 Person의 인스턴스로서 `name`변수가 있고, `getName()`과 `setName()`함수가 있다. > 하지만 이 예제는 문제가 많다. > 정확히는 이 예제의 Person함수의 구현히 바람직하지 못하다 > 이 Person을 생성자로 하여 여러개의 객체를 생성한다고 가정해보자 ```javascript var me = new Person("me"); var you = new Person("you"); var him = new Person("him"); ``` 위와 같이 객체를 생성하여 사용하면 겉으로는 별 문제 없이 작동하지만, 각각의 객체는 자기 영역에서 공통적으로 사용할 수 있는 setName(), getName()함수를 따로 생성하고 있다. 이는 불필요하게 중복되는 영역을 메모리에 올려놓고 사용함을 의미하고 자원낭비를 가져온다. > 따라서 앞의 문제를 해결하려면 다른 방식의 접근이 필요한데, 여기서 활용할 수 있는 자바스크립트의 특성이 > 함수 객체의 프로토타입이다. ```javascript function Person(arg) { this.name = arg; } Person.prototype.getName = function() { return this.name; } Person.prototype.setName = function(value) { this.name = value; } var me = new Person("me"); var you = new Person("you"); console.log(me.getName()); console.log(you.getName()); ``` > 위처럼 Person 함수 객체의 prototype프로퍼티에 getName()과 setName()함수를 정의했다. > 이 Person으로 객체를 생성한다면 각 객체는 각자 따로 함수 객체를 생성할 필요 없이 프로토타입 체인으로 접근할 수 있다. > 이와 같이 자바스크립트에서 클래스 안의 메소드를 정의할 때는 프로토타입 객체에 정의한 후, > new 로 생성한 객체에서 접근할 수 있게 하는 것이 좋다. > 더글라스 크락포드는 다음과 같은 함수를 제시 하면서 메소드를 정의하는 방법을 소개한다. ```javascript Function.prototype.method = functioin(name,func){ if(!this.prototype[name]){ this.prototype[name] = func; } } ``` > 위의 함수를 이용한다면 다음과 같은 형태가 된다 ```javascript Function.prototype.method=function(name,func){ this.prototype[name] = func; } function Person(arg){ this.name = arg; } Person.method("setName", function(value){ this.name = value; }); Person.method("getName", function(){ return this.name }); var me = new Person("me"); var you = new Person("you"); console.log(me.getName()); console.log(you.getName()); ``` ### 6.2 상속 - 자바스크립트는 클래스를 기반으로 하는 전통적인 상속을 지원하지는 않는다. - 하지만 객체 프로토타입 체인을 이용하여 상속을 구현해낼 수 있다. 이러한 상속의 구현방식은 크게 두 가지로 구분할 수 있다. - 클래스 기반 전통적인 상속방식을 흉내 내는 것 - 클래스 개념 없이 객체의 프로토타입으로 상속을 구현하는 방식이다. - 이를 프로토타입을 이용한 상속이라고 한다. #### 6.2.1 프로토타입을 이용한 상속 > 아래코드는 더글라스 크락포드가 자바스크립트 객체를 상속하는 방법으로 오래전에 소개한 코드다. > 조금 과장해서 말하면 이 세줄의 코드를 이해하면 자바스크립트에서의 프로토타입 기반의 상속을 다 배운것이나 다름없다. ```javascript function create_object(o){ function F(){} F.prototype = o; return new F(); } ``` create_object() 함수는 인자로 들어온 객체를 부모로 하는 자식객체를 생성하여 반환한다. 순서를 살펴보자면 1. 새로운 빈 함수 객체 F를 만들고 2. F.prototype 프로퍼티에 인자로 들어온 객체를 참조한다. 3. 함수 객체 F를 생성자로 하는 새로운 객체를 만들어 반환한다. 4. 반환된 객체는 부모객체의 프로퍼티에 접근할 수 있고, 자신만의 프로퍼티를 만들 수도 있다. > 이와 같이 프로토타입의 특성을 활용하여 상속을 구현하는 것이 프로토타입 기반의 상속이다. > 참고로 위의 create_object() 함수는 ECMAScript 5에서 Object.create() 함수로 제공되므로 따로 구현할 필요없다. 그럼 create_object() 함수를 이용하여 상속을 구현해보자 ```javascript var person = { name : "zzoon", getName : function() { return this.name; }, setName : function(arg) { this.name = arg; } }; function create_object(o) { function F() {}; F.prototype = o; return new F(); } var student = create_object(person); student.setName("me"); console.log(student.getName()); ``` > 앞서 말했듯이 "반환된 객체는 부모객체의 프로퍼티에도 접근할 수 있지만 자신만의 프로퍼티를 만들 수도 있다"고 했다. ```javascript student.setAge = function(age){} student.getAge = function(){} ``` 단순하게 앞과 같이 그 기능을 더 확장시킬수 도 있다. 하지만 이렇게 구현하면 코드가 지저분해지기 십상이다. 보다 깔끔한 방법을 생각해보자.. 자바스크립트에서는 범용적으로 `extend()` 라는 이름의 함수로 객체에 자신이 원하는 객체 혹은 함수를 추가시킨다. > 자세한 내용은 p.177~178 참조 ( jQuery.extend 분석 내용 ) ```javascript var person = { name : "zzoon", getName : function() { return this.name; }, setName : function(arg) { this.name = arg; } }; function create_object(o) { function F() {}; F.prototype = o; return new F(); } function extend(obj,prop) { if ( !prop ) { prop = obj; obj = this; } for ( var i in prop ) obj[i] = prop[i]; return obj; }; var student = create_object(person); student.setName("me"); console.log(student.getName()); var added = { setAge : function(age) { this.age = age; }, getAge : function() { return this.age; } }; extend(student, added); student.setAge(25); console.log(student.getAge()); ``` > 위 코드에서는 얕은 복사를 사용하는 extend()함수를 사용하여 student 객체를 확장시켰다. #### 6.2.2 클래스 기반의 상속 **원리는 프로토타입을 이용한 상속**과 원리는 거의 같다. 다만 프로토타입형 상속은 객체리터럴로 생성된 객체의 상속을 소개했지만, 여기서는 클래스의 역할을 하는 함수로 상속을 구현한다. ```javascript function Person(arg){ this.name = arg; } Person.prototype.setName = function(value){ this.name = value; }; Person.prototype.getName = function(){ return this.name; } function Student(arg){ Person.apply(this,arguments); } var you = new Person("iamgjoo"); Student.prototype = you; var me = new Student("zzoon"); me.setName("zzoon"); console.log(me.getName()); ``` > 현재는 자식 클래스의 객체가 부모 클래스의 객체를 프로토타입체인으로 직접 접근한다. > 하지만 부모 클래스의 인스턴스와 자식 클래스의 인스턴스는 서로 독립적일 필요가 있다.. 두 클래스의 프로토타입 사이에 중개자를 하나 만들어 보자 ```javascript function Person(arg){ this.name = arg; } Function.prototype.method = function(name, func){ this.prototype[name] = func; } Person.prototype.setName = function(value){ this.name = value; }; Person.prototype.getName = function(){ return this.name; } function Student(arg){ Person.apply(this,arguments); } function F(){}; F.prototype = Person.prototype; Student.prototype = new F(); Student.prototype.constructor = Student; Student.super = Person.prototype; var me = new Student(); me.setName("zzoon"); console.log(me.getName()); ``` --- ### 6.3 캡슐화 - 관련된 여러가지 정보를 하나의 틀 안에 담는 것을 의미한다. - 이를 응용하면 멤버 변수와 메소드가 서로 관련된 정보가 되고 클래스가 이것을 담는 하나의 큰 틀이라고 할 수 있다. - 여기서 중요한 것은 정보의 공개 여부이다. 자바스크립트에서는 Java의 public, private 같은 접근지정좌 관련 예약어를 지원하지 않는다. 그렇다고 해서 자바스크립트에서 정보 은닉이 불가능한 것은 아니다. ```javascript var Person = function(arg) { var name = arg ? arg : "zzoon" ; this.getName = function() { return name; } this.setName = function(arg) { name = arg; } }; var me = new Person(); console.log(me.getName()); me.setName("iamhjoo"); console.log(me.getName()); console.log(me.name); // undefined ``` > this객체의 프로퍼티로 선언하면 외부에서 new 키워드로 생상한 객체로 접근 할 수 있다. 하지만 var로 선언된 멤버들은 외부에서 접근히 불가능하다. 그리고 public 메소드가 클로저 역할을 하면서 private 멤버인 name 에 접근할 수 있다. ```javascript var Person = function(arg) { var name = arg ? arg : "zzoon" ; return { getName : function() { return name; }, setName : function(arg) { name = arg; } }; } var me = Person(); /* or var me = new Person(); */ console.log(me.getName()); ``` > Pseson( 함수를 호출하여 객체를 반환한다.) > 이 객체에 Person 함수의 private멤버에 접근할 수 있는 메소드들이 담겨있다. 사용자는 반환받는 객체로 메소드를 호출할 수 있고, private 멤버에 접근할 수 있다. > 이렇게 메소드가 담겨있는 객체를 반환하는 함수는 여러 유명 자바스크립트 라이브러리에서 쉽게 볼 수 있는 구조이다. 이 코드를 개선해보자 ```javascript var Person = function(arg) { var name = arg ? arg : "zzoon" ; var Func = function() {} Func.prototype = { getName : function() { return name; }, setName : function(arg) { name = arg; } }; return Func; }(); var me = new Person(); console.log(me.getName()); ``` --- ### 6.4 객체지향 프로그래밍 응용 예제 #### 6.4.1 클래스의 기능을 가진 subClass 함수 **프로토타입을 이용한 상속**과 **클래스 기반의 상속**에서 소개한 내용을 바탕으로 기존 클래스와 같은 기능을 하는 자바스크립트 함수를 만들어 보자. 여기서는 다음 세가지를 활용해서 구현한다. - 함수의 프로토타입 체인 - extend 함수 - 인스턴스를 생성할 때 생성자 호출(여기서는 생성자를 _int 함수로 정한다.) ##### 6.4.1.1 subClass 함수 구조 subClass는 상속받을 클래스에 넣을 변수 및 메소드가 담긴 객체를 인자로 받아 부모 함수를 상속 받는 자식 클래스를 만든다. 여기서 부모 함수는 subClass() 함수를 호출할 때 this 객체를 의미한다. ```javascript var SuperClass = subClass(obj); var SubClass = SuperClass.subClass(obj); ``` > 이처럼 SuperClass를 상속받는 subClass를 만들고자 할때, SuperClass.subClass()의 형식으로 호출하게 구현한다. > 참고로 최상위 클래스인 Superclass는 자바스크립트의 Function을 상속 받게 한다. 함수 subClass의 구조는 다음과 같이 구성된다. ```javascript function subClass(obj){ /* 1) 자식 클래스 (함수객체) 생성 */ /* 2) 생성자호출 */ /* 3) 프로토타입 체인을 활용한 상속 구현 */ /* 4) obj를 통해 들어온 변수 및 메소드를 자식 클래스에 추가 */ /* 5) 자식 함수 객체 반환 */ } ``` ##### 6.4.1.2 자식 클래스 생성 및 상속 ```javascript function subClass(obj){ //생략 var parent = this; var F = function(){}; var child = function(){ }; F.prototype = parent.prototype; child.prototype = new F(); child.prototype.constructor = child; child.parent = parent.prototype; child.parent_constructor = parent; // 생략 return child; } ``` 자식 클래스는 child 라는 이름의 함수 객체를 생성함으로써 만들어졌다. 부모 클래스를 가리키는 parent는 this를 그대로 참조한다. ##### 6.4.1.3 자식 클래스 확장 이제 사용자가 인자로 넣은 객체를 자식 클래스에 넣어 자식 클래스를 확장할 차례다. ```javascript for(var i in obj){ if(obj.hasOwnProperty(i)){ child.prototype[i] = obj[i]; } } ``` 프로토타입을 이용한 상속에서 살펴본 extend()함수의 역할을 하는 코드를 추가했다 여기서는 간단히 얕은 복사로 객체의 프로퍼티를 복사하는 방식을 택했다 ##### 6.4.1.4 생성자 호출 클래스의 인스턴스가 생성될 때, 클래스 내에 정의된 생성자가 호출돼야 한다. 이를 자식 클래스 안에 구현하자. ```javascript var child = function(){ if(parent.hasOwnProperty("_init")){ parent._init.apply(this, arguments); } if(child.prototype.hasOwnProperty("_init")){ child.prototype._init.apply(this, arguments); } }; ``` > 위 코드에서 한 가지를 더 고려해야 한다. > 앞 코드는 단순히 부모와 자식이 한쌍을 이루었을 때만 제대로 동작한다. > 자식을 또 다른 함수가 다시 상속 받았을 때는 어떻게 될 것인가? ```javascript var Superclass = subClass(); var SubClass = SuperClass.subClass(); var Sub_SubClass = SubClass.subClass(); var instance = new Sub_SubClass(); ``` 이 코드에서 instance를 생성할 때, 그 상위 클래스의 상위 클래스인 SuperClass의 생성자가 호출이 되지 않는다. 따라서 부모 클래스의 생성자를 호출하는 코드는 재귀적으로 구현할 필요가 있다. > 보다 자세한 사항은 p.190 (6.5 객체지향 프로그래밍 응용 참고) `subClass`함수의 전체코드는 다음과 같다. ```javascript function subClass(obj) { var parent = this === window ? Function : this; // Node.js의 경우에는 global를 사용한다. var F = function() {}; var child = function() { var _parent = child.parent; if (_parent && _parent !== Function) { _parent.apply(this, arguments); } if (child.prototype._init) { child.prototype._init.apply(this, arguments); } }; F.prototype = parent.prototype; child.prototype = new F(); child.prototype.constructor = child; child.parent = parent; child.subClass = arguments.callee; for (var i in obj) { if (obj.hasOwnProperty(i)) { child.prototype[i] = obj[i]; } } return child; } ``` > 이제 subClass 함수로 상속 에제를 만들어 보자 ```javascript function subClass(obj) { var parent = this === global ? Function : this; var F = function() {}; var child = function() { var _parent = child.parent; if (_parent && _parent !== Function) { _parent(); } if (child.prototype._init) { child.prototype._init.apply(this, arguments); } }; F.prototype = parent.prototype; child.prototype = new F(); child.prototype.constructor = child; child.parent = parent; child.subClass = arguments.callee; for (var i in obj) { if (obj.hasOwnProperty(i)) { child.prototype[i] = obj[i]; } } return child; } var person_obj = { _init : function() { console.log("person init"); }, getName : function() { return this._name; }, setName : function(name) { this._name = name; } }; var student_obj = { _init : function() { console.log("student init"); }, getName : function() { return "Student Name: " + this._name; } }; var Person = subClass(person_obj); var person = new Person(); person.setName("zzoon"); console.log(person.getName()); var Student = Person.subClass(student_obj); var student = new Student(); student.setName("iamhjoo"); console.log(student.getName()); console.log(Person.toString()); ``` > 위 에제에서 다음의 내용을 다시 한번 살펴보자 > - 생성자 함수가 호출되는가? > - 부모의 메소드가 자식인스턴스에서 호출되는가? > - 자식클래스가 확장 가능한가? > - 최상위 클래스인 Person은 Function을 상속받는가? ㄴ<file_sep>/java/god_of_java/Vol.1/06. loop/ControlOfFlow2.java public class ControlOfFlow2 { public void switchStatatement(int numberOfWheel) { switch(numberOfWheel){ case 1: System.out.println("It is one foot bicycle"); //break; case 2: System.out.println("It is a motor cycle or bicycle"); //break; case 3: System.out.println("It is a Three whell car."); break; case 4: System.out.println("It is a Three whell car."); break; /* 이하 케이스 생략 */ } } public void switchStatement2(int month) { switch(month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: System.out.println(month + " has 31 days." ); break; case 4: case 6: /* 이하 생략 각각 30일 , 28 || 29 그리고 기본값 코드 작성이다. */ } } public void whileLoop() { int loop = 0; while(loop<12) { loop++; swtichStatement2(loop); if(loop == 6) break; } } // do while /* do~ while 문은 적어도 한번은 꼭 실행된다. 아래 조건문은 whileLoop 와 동일한 로직이다. */ public void whileLoop2() { int loop=0; do { loop++; switchStatement2(loop); } while(loop<12); // 세미콜론을 반드시 찍어줘야한다. } }<file_sep>/java/god_of_java/Vol.2/02. String/README.md ## 2장. String ### 자바에서 가장 많이 사용하는 String 클래스 - 자바 클래스들 중에서 VVIP 일정도로 특별 취급을 받는 중요 클래스 - 클래스 중에서 더하기 연산을 제공하는 유일한 클래스 > String 클래스가 어떻게 선언되어 있는지 다시한번 살펴보자 ```java public final class String extends Object implements Serializable, Comparable<String>, CharSequence ``` - `public` 로 설정되어있다 (누구나 접근 가능~) - `final` 로 선언되어 있다. > 클래스가 `final`로 선언되어있으면 "이 클래스는 확장할 수 없다~"는 뜻! (다시말해서 String클래스는 자식클래스가 없다) - `extends Object` 를 보면 모든 클래스으 부모 클래스는 `Object`이므로 이 외에 따로 확장한 클래스는 없다는 말 - `implements` 라고 선언. 즉 해당 인터페이스에 선언된 메소드들을 이 클래스에서 `구현`한다는 뜻!!! > 따라서, `String`은 `Serializable`, `Comparable`, `CharSequence`라는 인터페이스를 구현한 클래스다 - 여기서 `Serializable` 인터페이스는 구현해야 하는 메소드가 하나도 없는 아주 특이한 인터페이스다. - 이 `Serializable` 인터페이스를 구현한다고 선언해 놓으면, 해당 객체를 파일로 저장하거나 다른 서버에 전송 가능한 상태가 된다. - (`Serializable`에 대한 더욱 자세한 사항은 11장 참고!) - `Comparable` 인터페이스는 `compareTo()`라는 메소드 하나만 선언되어 있다. - 이 메소드는 매개변수로 넘어가는 객체와 현재 객체가 같은지를 비교하는 데 사용된다. - 간단하게 이름과 내용만으로 보기에는 그냥 `equals()`메소드와 무슨차이지?????? 물음표가 뜬다.. > 하지만 이 메소드의 리턴 타입은 `int`다. > 같으면 `0`이지만, 순서 상으로 앞에 있으면 `-1`, 뒤에 있으면 `1`을 리턴한다. > 다시 말해서 객체의 순서를 처리할 때 유용하게 사용될 수 있다. - 선언문의 `<>`안에 `String`이라고 적어 주었는데, 이는 `제네릭~Generic~`이라는 것을 의미한다.(4장참고) - `CharSequence` 인터페이스는 해당 클래스가 문자열을 다루기 위한 클래스라는 것을 명시적으로 나타내는 데 사용된다. - 이 장의 가장 끝 부분에서 설명하는 `StringBuilder`와 `StringBuffer`클래스도 이 `CharSequence`인터페이스를 구현해 놓았다. ### String의 생성자에는 이런 애들이 있다. 먼저 생성자를 살펴보자. 대부분 문자열을 만들 때에는 다음과 같이 간단하게 만든다. ```java String name = "<NAME>"; ``` -대부분의 경우 이렇게 선언하지만, String의 생성자는 매우 많다. 그중에서 많이 사용하는 생성자를 보자 ```java String(byte[] bytes) String(byte[] bytes, String charsetName) ``` > 위 생성자들은 한글을 사용하는 우리나라에서는 자주 사용할 수 밖에 없다. > 왜냐면, 대부분의 언어에서는 문자열을 변환할 때 기본적으로 영어로 해석하려고 하기 때문이다. --- ### String 문자열을 byte로 변환하기 생성자의 매개변수로 받는 `byte`배열은 어떻게 생성하지? 라는 의문이 든다. > String 클래스에는 현재의 문자열 값을 `byte` 배열로 변화하는 다음과 같은 `getBytes()`라는 메소드를 사용하면 된다. | 리턴타입 | 메소드이름 및 매개변수 | 설명 | |--------|--------|---| | byte[] | getBytes() | 기본 캐릭터 셋의 바이트 배열을 생성한다. | | byte[] | getBytes(Charset charset) |지정한 캐릭터 셋 객체 타입으로 바이트 배열을 생성한다.| | byte[] | getBytes(String charsetName) | 지정한 이름의 캐릭터 셋을 갖는 바이트 배열을 생성한다. | - 보통 캐릭터 셋을 잘 알고 있거나, 같은 프로그램 내에서 문자열을 byte 배열로 만들 때에는 `getByte()`메소드를 사용하면 된다. - 한글을 처리하기 위해서 많이 사용하는 캐릭터 셋은 `UTF-16`이다. (예전에는 UTF-8이나 EUC-KR을 많이 썻지만 요즘에는~) > 더욱 자세한건 코드를 통해 알아보자 ```java public class StringSample { public static void main(String[] args) { StringSample sample=new StringSample(); sample.constructors(); } public void constructors(){ try{ //"한글"이라는 값을 갖는 String객체 str생성 String str="한글"; // str을 byte배열로 만듬 byte[] array1=str.getBytes(); for(byte data:array1){ System.out.print(data + " "); } System.out.println(); // byte배열(array1)을 매개변수로 갖는 String객체 생성후 출력 String str1=new String(array1); System.out.println(str1); } catch(Exception e){ e.printStackTrace(); } } } ``` > 출력결과 ```java -57 -47 -79 -37 한글 ``` - 원래 만들어 놓았던 "한글"이라는 값이 그대로 출력되네? > `getBytes()` 메소드는 플랫폼의 기본 캐릭터 셋으로 변환을 하고, String(byte[])생성자도 플랫폼의 기본 캐릭터 셋으로 변환을 하기 때문에 전혀 문제가 발생하지 않았다. 만약 이 소스가 실무라고 생각하면 byte 배열의 값을 출력하는 부분이 자주 사용될 것같으니 다음과 같이 별도의 메소드로 만들어보자 ```java public void printByteArray(byte[] array){ for(byte data:array){ System.out.print(data+" "); } Systesm.out.println(); } ``` > 이렇게 메소드 내에 자주 사용되는 부분을 별도의 메소드로 빼 놓는 버릇을 들이는 것이 향후에 재사용성을 위해서 좋다. 이번에는 캐릭터 셋을 변환해서 출력해보자 ```java String str="한글"; byte[] array1=str.getBytes(); printByteArray(array1); String str1=new String(array1); System.out.println(str1); byte[] array2=str.getBytes(); printByteArray(array2); String str2=new String(array2, "UTF-8"); System.out.println(str2); ``` > 출력결과 ```java -57 -47 -79 -37 한글 -57 -47 -79 -37 ??? ``` > 잘못된 캐릭터 셋으로 변환을 하면 이와같이 알아볼수 없는 문자료 표기된다. 그렇다면, byte 배열로 변환할 때 캐릭터 셋을 변경해 버릴수는 없을까? > 그럴때는 아래와같이 `getBytes()` 매개변수로 캐릭터 셋을 지정해주면 된다. ```java byte[] array3=str.getBytes("UTF-16"); printByteArray(array3); String str3=new String(array3, "UTF-16"); System.out.println(str3); ``` > 참고로 EUC-KR 은 한글 두 글자를 표현하기 위해서 4바이트를 사용하지만 UTF-16은 6바이트를 사용한다. > 글자수와 상관없이 2바이트의 차이가 발생함을 볼수 있다. > 또한 위 코드들을 try 블록으로 감싼 이유는, getBytes() 메소드 중에서 String 타입의 캐릭터 셋을 받는 메소드는 > UnsupporteEncodingException을 발생시킬 수 있기 때문이다. > 반드시 이처럼 try~catch 문으로 감싸주거나 constuctors() 메소드 선언시 throws 구문을 추가해 줘야 한다. --- ### 객체의 널 체크는 반드시 필요하답니다. - 어떤 참조 자료형도 널이 될 수 있다. - 객체가 널이라는 말은 객체가 아무런 초기화가 되어 있지 않으며, 클래스에 선언되어 있는 어떤 메소드도 사용할 수 없다는말 - 널 체크를 하지 않으면 객체에 사용할 수 있는 메소드들은 모두 예외를 발생시킨다. > 돈이 없으면 주문도 할 수 없는 선불 식당을 떠올려 보자 ```java public boolean nullCheck(String text){ int textLength=text.length(); System.out.println(textLength); if(text=null) return true; else return false; } ``` > 출력결과 ```java Exception in thread "main" java.lang.NullPointerException at StringSample3.nullCheck(StringSample3.java:12) at StringSample3.main(StringSample3.java:7) ``` - null인 객체의 메소드에 접근하면 `NullPointerException`이 발생한다. - 객체가 널인지 아닌지 체크하는 것은 이처럼 `!=`이나 `==`를 사용하면 된다. --- ### String의 내용을 비교하고 검색하는 메소드들도 있어요 - String클래스는 문자열을 나타낸다. - 문자열 내에 특정 위치를 찾거나, 값을 비교하는 등의 작업은 아주 빈번히 발생된다. > String클래스객체의 내용을 비교하고 검색하는 메소드들을 알아보자 - 문자열의 길이를 확인하는 메소드 - 문자열이 비어 있는지 확인하는 메소드 - 문자열이 같은지 바교하는 메소드 - 특정 조건에 맞는 문자열이 있는지를 확인하는 메소드 > 위 글만 보고 " 이 메소드 이름이 뭐지?" 하고 생각해보자 메소드 이름을 직관적으로 지어야 한다. ##### 1) 문자열의 길이를 확인하는 메소드 ```java public void comparecheck(){ String text="You must know String class."; System.out.println("text.length()="+text.length()); } ``` > 출력결과 ```java text.length()=27 ``` ##### 2) 문자열이 비어 있는지 확인하는 메소드 ```java System.out.println("text.isEmpty()="+text.isEmpty()); ``` > 출력결과 ```java text.isEmpty()=false ``` - 만약 text가 공백 하나로 되어 있는 문자열이라도, 이 메소드는 false를 리턴한다. ##### 3) 문자열이 같은지 비교하는 메소드 - String클래스에서 제공하는 문자열이 같은지 비교하는 메소드들은 매우 많다. | 리턴타입 | 메소드 이름 및 매개변수 | |--------|--------| | boolean | equals(Object anObject)| | boolean | equalsIgnoreCase(String anotherStr)| | int | compareTo(String anotherStr)| | int | compareToIgnoreCase(String str)| | boolean | contentEquals(CharSequence cs)| | boolean | contentEquals(StringBuffer sb)| > `IgnoreCase` 가 붙은 메소드들은 대소문자 구분을 할지 안할지 여부만 다르다. ###### ㄱ) equals() ```java public void equalCheck(){ String text="Check value"; String text2="Check value"; if(text==text2){ System.out.println("text==text2 result is same"); } else{ System.out.println("text==text2 result is different"); } if(text.equals("Check value")){ System.out.println("text.equals(text2) result is same"); } } ``` > 출력결과 ```java text==text2 result is same text.equals(text2) result is same ``` **객체는 `equals()`메소드로 비교 해야 한다고 배웠는데 왜 `if(text==text2)`구문도 정상적으로 출력이 되지???** > 이는 자바에 `Constant Pool`이라는 것이 존재하기 때문이다. > 자바에서는 객체들을 재사용하기 위해서 `Constant Pool`이라는 것이 만들어져 있고, > String의 경우 동일한 값을 갖는 객체가 있으면, 이미 만든 객체를 재사용한다. > 따라서 text와 text2객체는 실제로는 같은 객체다 > 이 첫번째 연산결과가 우리가 원하는 대로 나오도록 하려면 다음과 같이 변경하면 된다. ```java //String text2="Check value"; String text2=new String("Check value"); ``` > 이렇게 String객체를 생성하면 값이 같은 String 객체를 생성한다고 하더라도 > `Constant Pool`의 값을 재활용하지 않고 별도의 객체를 생성한다. ###### ㄴ) equalsIgnoreCase() ```java String text3="check value"; if(text.equalsIgnoreCase(text3)){ System.out.println("text.equalsIgnoreCase(text3) result is same"); } ``` > 출력결과 ```java text.equalsIgnoreCase(text3) result is same ``` ###### ㄷ) compareTo() - `compareTo()` 메소드는 `Comparable`인터페이스에 선언되어 있다. - `compareTo()` 메소드는 보통 정렬을 할 때 사용한다. - 따라서 true,false의 결과가 아니라, 비교하려는 매개 변수로 넘겨준 String 객체가 알파벳 순으로 앞에 있으면 양수를, 뒤에 있으면 음수를 리턴한다. ```java public void compareToCheck(){ String text="a"; String text2="b"; String text3="c"; System.out.println(text2.compareTo(text)); System.out.println(text2.compareTo(text3)); System.out.println(text.compareTo(text3)); } ``` > 출력결과 ```java 1 -1 -2 ``` ###### ㄹ) contentEquals() - 매개 변수로 넘어오는 `CharSequence`와 `StringBuffer` 객체가 String 객체와 같은지를 비교하는 데 사용된다. - 뒤에서 자세히 알아보자 ###### ㅁ) 특정 조건에 맞는 문자열이 있는지를 확인하는 메소드 여러가지가 있지만 가장 많이 사용하는 것이 `startWith()`메소드다. `startWith()`메소드는 이름 그대로 매개 변수로 넘겨준 값으로 시작하는지를 확인한다. 예를 들어 "서울시 구로구 신림동", "경기도 성남시 분당구"와 같이 주소를 나타내는 문자열들이 있을 때 "서울시"의 주소를 갖는 모든 문자열을 쉽게 찾을 수 있다. 마찬가지로 `endsWith()`메소드는 매개변수로 넘어온 값으로 해당 문자열이 끝나는지를 확인하는 메소드다. > 위 두개의 메소드를 사용하여 점검대상의 문자열에 확인하고자 하는 문자열로 시작하는 개수와 끝나는 개수를 세어보는 예제를 살펴보자 ```java public void addressCheck(){ String addresses[]=new String[]{ "서울시 구로구 신도림동", "경기도 성남시 분당구 정자동 개발 공장", "서울시 구로구 개봉동", }; int startCount=0,endCount=0; String startText="서울시"; String endText="동"; for(String address:addresses){ if(address.startsWith(startText)){ startCount++; } if(address.endsWith(endText)){ endCount++; } } System.out.println("Starts with "+startText+" count is "+startCount); System.out.println("Ends with "+endText+" count is "+endCount); } ``` > 출력결과 ```java Starts with 서울시 count is 2 Ends with 동 count is 2 ``` > 그렇다면 중간에 있는 값은 어떻게 확인 가능할까? 그래서 존재하는 것이 `contains()`메소드다. - 이 메소드는 매개 변수로 넘어온 값이 문자열에 존재하는지를 확인한다. - 사용법은 위 두개 메소드와 동일하다 `matches()`메소드는 매개변수로 넘어오는 값이 `정규표현식`으로 되어 있어야만 한다. > 정규표현식은 `java.util.regex`패키지의 `Pattern`클래스 API를 참고하자. > 인사이트의 <손에 잡히는 정규 표현식> 책 참고 `regionMatches()`메소드는 문자열 중에서 특정영역이 매개 변수로 넘어온 문자열과 동일한지를 확인하는데 사용한다. 매개변수가 많으니 5개인 메소드를 기준으로 각각이 어떤 값인지 알아보자 ```java regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) ``` ```java public void matchCheck(){ String text="This is a text"; String compare1="is"; String compare2="this"; // 매개변수가 4개인 메소드 System.out.println(text.regionMatches(2,compare1,0,1)); // 매개변수가 4개인 메소드 System.out.println(text.regionMatches(5,compare1,0,2)); // 매개변수가 5개인 메소드 System.out.println(text.regionMatches(true,2,compare2,0,4)); } ``` --- ### String 내에서 위치를 찾아내는 방법은 여러가지에요 "Java technology is both a programming language and a platform." 이 문장에서 "both"라는 단어가 시작하는 위치를 알고 싶을 때 어떻게 해야 할까? - 자바의 String클래스에서는 `indexof`라는 단어가 포함되어 있는 메소드를 제공한다. - 이 메소드를 사용하면 해당 객체의 특정 문자열이나 char가 있는 위치를 알 수 있다. - 만약 찾고자 하는 문자열이 없으면 이 메소드는 `-1`을 리턴한다. > 그럼 위에서 설명한 위치를 찾는 메소드의 종류를 살펴보자 - `indexOf(int ch)` - `indexOf(ing ch, int fromIndex)` - `indexOf(String str)` - `indexOf(String str, int fromIndex)` - `lastIndexOf(int ch)` - `lastIndexOf(int ch, int fromIndex)` - `lastIndexOf(String str)` - `lastIndexOf(String str, int fromIndex)` > `indexOf()` 메소드는 String클래스의 가장 많이 사용되는 메소드 중 하나다. indexOf()는 앞에서부터, lastIndexOf()는 뒤에서부터 문자열을 찾는다. ```java public void indexOfCheck(){ String text="Java technology is both a programming language and ad platform."; System.out.println(text.indexOf('a')); System.out.println(text.indexOf("a ")); System.out.println(text.indexOf('a',20)); System.out.println(text.indexOf("a ",20)); System.out.println(text.indexOf('z')); } ``` > 출력결과 ```java 1 3 24 24 -1 ``` --- ### String 값의 일부를 추출하기 위한 메소드들은 얘네들이다. 문자열에서 특정 값을 추출할 때 사용하는 메소드를 알아보자 그 종류는 크게 다음과 같이 나눌 수 있다. - char 단위의 값을 추출하는 메소드 - char 배열의 값을 String으로 변환하는 메소드 - String의 값을 char배열로 변환하는 메소드 - 문자열의 일부 값을 잘라내는 메소드 - 문자열을 여러 개의 String배열로 나누는 메소드 #### char 단위의 값을 추출하는 메소드 - 생략 #### char 배열의 값을 String으로 변환하는 메소드 - static 메소드이기 때문에 현재 사용하는 문자열을 참조하여 생성하는 것이 아닌, static 하게 호출하여 사용해야 한다 ```java char values[]=new char[]{'J', 'a', 'v', 'a'}; String javaText=String.copyValueOf(values); ``` #### String의 값을 char배열로 변환하는 메소드 - 어떤 String객체를 만들더라고, 그 객체는 내부에 char배열을 포함한다. #### 문자열의 일부 값을 잘라내는 메소드 - 문자열을 다룰 때 `indexOf()`메소드와 더불어 가장 많이 사용하는 메소드 ```java public void substringCheck1(){ String text="Java technology"; } ``` > 위 문자열 중 "technology"라는 단어만 추출하려고 한다면? ```java public void substringCheck1(){ String text="Java technology"; String technology=text.substring(5); System.out.println(technology); } ``` > 그런데, 만약 "tech"라는 단어만 잘라내고 싶을때는 어떻게 해야 할까? ```java String tech=text.substring(5,9); System.out.println(tech); ``` > 여기서 주의 할점은 두번째 매개변수는 **데이터 길이가 아닌 끝나는 위치다.** #### 문자열을 여러 개의 String배열로 나누는 메소드 - String클래스에 선언된 split()메소드를 사용하는 것과 java.util 패키지에 선언되어 있는 StringTokenizer라는 클래스를 사용하는 것이다. - 정규표현식을 사용하여 문자열을 나누려고 한다면 String클래스의 split()메소드를 사용하면 된다. - 그냥 특정 String으로 문자열을 나누려고 한다면 StringTokenizer클래스를 사용하는 것이 편하다. - 물론 특정 알파벳이나 기호하나로 문자열을 나누려고 한다면 뭘쓰든 큰 상관없다 ```java public void splitCheck(){ String text="Java technology is both a programming language and ad platform."; String[] splitArray=text.split(" "); for(String temp:splitArray){ System.out.println(temp); } } ``` --- ### String 값을 바꾸는 메소드들도 있어요 문자열의 값을 바꾸고, 변환하는 메소드도 다음과 같이 구분할 수 있다. - 문자열을 합치는 메소드와 공백을 없애는 메소드 - 내용을 교체~replace~하는 메소드 - 특정 형식에 맞춰 값을 치환하는 메소드 - 대소문자를 바꾸는 메소드 - 기본 자료형을 문자열로 변환하는 메소드 #### 문자열을 합치는 메소드와 공백을 없애는 메소드 - `trim()`메소든느 공백을 제거할 때 매우 유용하게 사용된다. ```java public void trimCheck() { String strings[] = new String[] { " a", " b ", " c", "d ", "e f", " " }; for (String string : strings) { System.out.println("[" + string + "] "); System.out.println("[" + string.trim() + "] "); } } ``` > `trim()`메소드의 용도는 매우 많지만, 작업하려는 문자열이 공백만으로 이루어진 값인지, 아니면 공백을 제외한 값이 있는지 확인하기에 매우 편리하다. > > 다음의 if 문을 통과하여 "OK"를 출력하면, 해당 문자열은 공백을 제외한 char값이 하나라도 존재한다는 의미다. ```java String text=" a "; if(text!=null && text.trim().length()>0 ){ System.out.println("OK"); } ``` > 만약 null 체크를 하지 않으면, 값이 null인 객체의 메소드를 호출하면 `NullPointerException`이 발생한다. > 이와 같이 String을 조작하기 전에 null체크하는 습관을 갖자. #### 내용을 교체~replace~하는 메소드 - `replace`로 시작하는 메소드는 문자열에 있는 내용 중 일부를 변경하는 작업을 수행한다. - 참고로, 이 메소드를 수행한다고 해서, 기존 문자열의 값은 바뀌지 않는다. ```java public void replaceCheck() { String text = "The String class represents character strings."; System.out.println(text.replace('s', 'z')); System.out.println(text); System.out.println(text.replace("tring", "trike")); System.out.println(text.replaceAll(" ", "|")); System.out.println(text.replaceFirst(" ", "|")); } ``` > 참고로 `replace`관련 메소드는 대소문자를 구분한다. #### 특정 형식에 맞춰 값을 치환하는 메소드 - format()메소드는 정해진 기준에 맞춘 문자열이 있으면, 그 기준에 있는 내용을 변환한다. - `%s`는 String - `%d`는 정수형 - `%f`는 소수점이 있는 숫자 - `%%`는 `%`fmf dmlalgksek. ```java public void formatCheck() { String text = "제 이름은 %s입니다. 지금까지 %d 권의 책을 썼고, " + "하루에 %f %%의 시간을 책을 쓰는데 할애하고 있습니다."; String realText = String.format(text, "이상민", 3, 10.5); // String realText=String.format(text, "이상민",3); System.out.println(realText); } ``` > 만약 출력만을 위해서 이 메소드를 사용하면 굳이 이렇게 사용할 필요 없이 `System.out.format()`을 쓰자 #### 대소문자를 바꾸는 메소드 - `toLower`로 시작하는 메소드는 모든 대문자를 소문자로 - `toUpper`로 시작하는 메소드는 모든 소문자를 대문자로 #### 기본 자료형을 문자열로 변환하는 메소드 - 기본자료형을 String 타입으로 변환한다. > `valueOf()`메소드를 사용하여 기본 자료형 값들을 문자열로 변경해도 되지만 다음고 같이 써도 된다. ```java byte b = 1; String byte1=String.valueOf(b); String byte2=b+""; ``` ### 절대로 사용하면 안되는 메소드가 하나 있어요 intern() 메소드를 사용하지 말자 ### immutable한 String의 단점을 보완하는 클래스에는 StringBuffer와 StringBuilder가 있다. - String은 immutable한 객체다. (사전적인 의미로 "불변의") - 다시 말해서 한번 만들어지면 더 이상 그 값을 바꿀 수 없다. ##### "무슨말이지? 더하기 하면 잘만 더해지는데....." > 위 생각은 틀렸다. String객체는 변하지 않는다. 만약 String문자열을 더하면 새로운 String객체가 생성되고, 기존객체는 버려진다. 그러므로, 계속 하나의 String을 만들어 계속 더하는 작업을 한다면, 계속 쓰레기를 만들게 된다. 즉 다음과 같은 경우다 ```java String text="Hello"; text=text+" wolrd"; ``` 이 경우 "Hello"라는 단어를 갖고 있는 객체는 더 이상 사용할 수 없다. 즉, 쓰레기가 되며, 나중에 GC~Garbagecollection~(가비지 컬렉션)의 대상이 된다. > 이러한 String클래스의 단점을 보완하기 위해서 나온 클래스가 `StringBuffer`와 `Stringbuilder`다. - 두 클래스에서 제공하는 메소드는 동일하다. - 하지만, `StringBuffer`는 **Thread safe하다**고 하며, - `StringBuilder`는 **Thread safe 하지 않다**고 한다. > `StringBuffer` 가 `StringBuilder` 보다 더 안전하다고만 기억해두자. (속도는 `Stringbuilder`가 더 빠르다) - 이 두 클래스는 문자열을 더하더라도 새로운 객체를 생성하지 않는다. - 이 두개의 클래스에서 가장 많이 사용하는 메소드는 `append()`라는 메소드다 - `append()`메소드는 매개 변수로 모든 기본자료형과 참조 자료형을 모두 포함한다. 따라서 어떤 값이라도 이 메소드의 매개변수로 들어갈 수 있다. > 보통 다음과 같이 사용한다. ```java StringBuilder sb=new Stringbuilder(); sb.append("Hello"); sb.append(" world"); ``` > 그냥 보기엔 별 차이가 없어보인다. > 하지만, append()메소드에 넘어가는 매개 변수가 이처럼 정해져 있는 문자열이라면 사용하나 마나지만, > 매개변수가 변수로 받은(항상변하는)값이라면 이야기는 달라진다. 또한 다음과같이 사용할 수 도 있다 ```java StringBuilder sb=new StringBuilder(); sb.append("Hello").append(" world"); ``` > 추가로, JDK 5 이상에서는 String의 더하기 연산을 할 경우, 컴파일할 때 자동으로 해당 연산을 Stringbuilder로 변환해 준다. 세 메소드의 공통점 - 모두 문자열을 다룬다. - CharSequence 인터페이스를 구현했다는 점 > 따라서 이 세가지중 하나의 클래스를 사용하여 매개 변수로 받는 작업을 할 때 String이나 StringBuilder 타입으로 받는 것보다 > CharSequence 타입으로 받는 것이 좋다. - 하나의 메소드 내에서 문자열을 생성하여 더할 경우에는 StringBuilder 를 사용해도 전혀 상관없다. - 어떤 문자열을 생성하여 더하기 위한 문자열을 처리하기 위한 인스턴스 변수가 선언되었고, 여러 쓰레드에서 이 변수를 동시에 접근하는 일이 있을 경우에는 반드시 StringBuffer를 사용해야만 한다. --- ### 직접해봅시다 ```java public class UseStringMethods { public static void main(String[] args) { UseStringMethods usm=new UseStringMethods(); String text="The String class represents character strings."; String fstr="string"; char c='s'; String fstr2="ss"; //usm.printWords(text); //usm.findString(text, fstr); //usm.findAnyCaseString(text, fstr); //usm.countChar(text, c); usm.printContainWords(text, fstr2); } public void printWords(String str){ String str2[]=str.split(" "); for(String tmp:str2){ System.out.println(tmp); } } public void findString(String str, String findStr){ System.out.println("string is appeared at "+str.indexOf(findStr)); } public void findAnyCaseString(String str, String findStr){ String str2 = str.toLowerCase(); System.out.println("string is appeared at "+str2.indexOf(findStr)); } public void countChar(String str,char c){ int charCount=0; char[] strArray=str.toCharArray(); for(char tmp:strArray){ if(tmp=='s'){ charCount++; } } System.out.println("char 's' count is "+charCount); } public void printContainWords(String str, String findStr){ String[] strArray=str.split(" "); for(String tmp:strArray ){ if(tmp.contains(findStr)){ System.out.print(tmp+" contains ss"); } } } } ``` --- ### 정리해 봅시다 1) String 클래스는 final 클래스인가요? 만약 그렇다면, 그 이유는 무엇인가요? - 그렇다. 자식클래스가 없다. 더이상 상속을 줄 수 가 없다. > 자바의 String클래스는 final로 선언되어 있으며, 더 이상 확장해서는 안된다. 2) String 클래스가 구현한 인터페이스에는 어떤 것들이 있나요? - Serializable, Comparable, CharSequence를 구현했다. 3) String 클래스의 생성자 중에서 가장 의미없는 (사용할 필요가 없는) 생성자는 무엇인가요? - ~~new String(String str)~~ > new String() 생성자는 가장 의미가 없는 String 클래스의 생성자이다. 왜냐하면, 생성된 객체는 해당 변수에 새로운 값이 할당되자마자 GC의 대상이 되어버리기 때문이다. 4) String 문자열을 byte 배열로 만드는 메소드의 이름은 무엇인가요? - getBytes 5) String 문자열의 메소드를 호출하기 전에 반드시 점검해야 하는 사항은 무엇인가요? - null 체크 6) String 문자열의 길이를 알아내는 메소드는 무엇인가요? - length() 7) String 클래스의 equals() 메소드와 compareTo() 메소드의 공통점과 차이점은 무엇인가요? - 값이 같은지 확인하는 메소드지만 compareTo() 메소드는 리턴값이 int이며 보통 정렬에 사용한다. > equals()메소드와 compareTo()메소드의 공통점은 두 개의 문자열을 비교한다는 것이고, 다른 점은 리턴 타입이 다르다는 것이다. equals() 메소드는 boolean 타입의 리턴을, compareTo() 메소드는 int 타입의 리턴값을 제공한다. 8) 문자열이 "서울시"로 시작하는지를 확인하려면 String의 어떤 메소드를 사용해야 하나요? - startWith() 9) 문자열에 "한국"이라는 단어의 위치를 찾아내려고 할 때에는 String의 어떤 메소드를 사용해야 하나요? - ~~indexOf()~~ > contains()나 matches()메소드를 사용하여 원하는 문자열이 존재하는지 확인할 수 있다. 고전적인 방법으로는 indexOf() 메소드를 사용할 수도 있다. 10) 9번 문제의 답에서 "한국"이 문자열에 없을 때 결과값은 무엇인가요? - ~~-1~~ > contains()나 matches() 메소드의 리턴타입은 boolean 이다. 11) 문자열의 1번째부터 10번째 위치까지의 내용을 String으로 추출하려고 합니다. 어떤 메소드를 사용해야 하나요? - ~~split()~~ > substring()이나 subSequence()메소드를 사용하면 원하는 위치에 있는 문자열을 자를 수 있다. 12) 문자열의 모든 공백을 * 표시로 변환하려고 합니다. 어떤 메소드를 사용하는 것이 좋을까요? - replace > replace()나 replaceAll() 메소드를 사용하면 문자열의 특정 부분을 바꿀 수 있다. 여기서 중요한 것은 원본 문자열은 변경되지 않는다는 것이다. 변경된 값을 사용하려면 해당 메소드의 리턴값을 사용해야만 한다. 13) String의 단점을 보완하기 위한 두개의 클래스는 무엇인가요? - StringBuilder, StringBuffer 14) 13번 문제의 답에서 문자열을 더하기 위한 메소드의 이름은 무엇인가요? - ~~StringBuilder~~ > StringBuilder와 StringBuffer클래스의 append() 메소드를 사용하여 문자열을 더할 수 있다. <file_sep>/java/god_of_java/Vol.2/02. String/StringSample3.java public class StringSample3 { public static void main(String[] args) { StringSample3 sample=new StringSample3(); //sample.constructors(); System.out.println(sample.nullCheck(null)); } public boolean nullCheck(String text){ int textLength=text.length(); System.out.println(textLength); if(text==null) return true; else return false; } public void printByteArray(byte[] array){ for(byte data:array){ System.out.print(data+" "); } System.out.println(); } public void constructors(){ try{ String str="ÇѱÛ"; byte[] array1=str.getBytes(); printByteArray(array1); String str1=new String(array1); System.out.println(str1); byte[] array2=str.getBytes(); printByteArray(array2); String str2=new String(array2, "EUC-KR"); System.out.println(str2); byte[] array3=str.getBytes("UTF-8"); printByteArray(array3); String str3=new String(array3, "UTF-8"); System.out.println(str3); } catch(Exception e){ e.printStackTrace(); } } }<file_sep>/java/java_web_develop_workBook/4장. 서블릿과 JDBC/README.md ## 3. 서블릿과 JDBC > 이번장의 학습과제 - GenericServlet 클래스를 확장한 HttpServlet 클래스를 이용한 서블릿 생성 - 클라이언트의 요청을 GET과 POST등으로 구분하여 처리하는 방법 - 리다이렉트, 리프레시 - 초기화 매개변수를 이용하여 설정 정보를 외부 파일에 두는 방법 - 서블릿에서 이를 참고하는 방법 - 서블릿 실행 전, 후에 필터를 끼우는 방법 - JDBC를 이용하여 데이터베이스에 회원정보를 등록, 조회, 변경, 삭제하는 회원 관리 예제를 생성 (이와 같은 기능을 보통 CRUD라고 부른다.) ### 1) 데이터베이스에서 데이터 가져오기 - 서블릿이 하는 주된 일은 클라이언트가 요청한 데이터를 다루는 일이다. - 데이터를 가져오거나 입력, 변경, 삭제 등을 처리하려면 데이터베이스의 도움을 받아야 한다. #### sql 준비 > MySQL 설치및 테스트를 위한 테이블 생성 ( p.163~ 165 참조 ) #### JDBC 드라이버 자바에서 데이터베이스에 접근하려면 JDBC 드라이버가 필요하다. 자바실행환경(JRE)에는 기본으로 Type 1 JDBC 드라이버가 포함되어 있다. Type 1 드라이버는 ODBC 드라이버를 사용하기 때문에 개발 PC에 MySQL ODBC 드라이버를 설치해야 한다. 따라서 JRE에서 기본제공하는 JDBC 드라이버를 쓰지 않고 MySQL에서 제공하는 Type 4 드라이버를 사용해보자. Type 4 JDBC 드라이버는 MySQL 통신 프로토콜에 맞추어 데이터베이스와 직접 통신하기 때문에 ODBC드라이버를 필요로 하지 않는다. 이러한 이유로 실무에서도 Type 4 드라이버를 주로 사용하고 있다. > 아래 클래스를 통해 알아보자 ```java package spms.servlets; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import javax.servlet.GenericServlet; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebServlet; @WebServlet("/member/list") public class MemberListServlet extends GenericServlet { private static final long serialVersionUID = 1L; @Override public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { DriverManager.registerDriver(new com.mysql.jdbc.Driver()); conn = DriverManager.getConnection( "jdbc:mysql://localhost/jsp", //JDBC URL "root", // DBMS 사용자 아이디 "apmsetup"); // DBMS 사용자 암호 stmt = conn.createStatement(); rs = stmt.executeQuery( "SELECT MNO,MNAME,EMAIL,CRE_DATE" + " FROM MEMBERS" + " ORDER BY MNO ASC"); response.setContentType("text/html; charset=UTF-8"); PrintWriter out = response.getWriter(); out.println("<html><head><title>회원목록</title></head>"); out.println("<body><h1>회원목록</h1>"); while(rs.next()) { out.println( rs.getInt("MNO") + "," + rs.getString("MNAME") + "," + rs.getString("EMAIL") + "," + rs.getDate("CRE_DATE") + "<br>" ); } out.println("</body></html>"); } catch (Exception e) { throw new ServletException(e); } finally { try {if (rs != null) rs.close();} catch(Exception e) {} try {if (stmt != null) stmt.close();} catch(Exception e) {} try {if (conn != null) conn.close();} catch(Exception e) {} } } } ``` > GenericServlet을 상속받음 > 서블릿을 만들고자 javax.servlet.GenericServlet 클래스를 상속받고 service()메소드를 구현한다 ```java public class MemberListServlet extends GenericServlet { ``` > 데이터베이스 관련 객체의 참조 변수 선언 > service()에서 처음 부분은 JDBC 객체 주소를 보관할 참조 변수의 선언이다. ```java Connection conn = null; Statement stmt = null; ResultSet rs = null; ``` > 데이터베이스 관련 코드를 위한 try~catch > 예외발생을 고려한 try~catch 블록으로 에외가 발생하면 그 예외를 `ServletException`객체에 담아서 이 메소드를 호출한 서블릿 컨테이너에 던진다. > 서블릿 컨테이너는 예외에 따른 적절한 화면을 생성하여 클라이언트에게 출력할 것이다. ```java try{ }catch(Exception e){ throw new ServletException(e); }finally{ } ``` > DriverManager가 사용할 JDBC 드라이버 등록 JDBC 프로그래밍의 첫 번째 작업은 DriverManager를 이용하여 java.sql.Driver 인터페이스 구현체를 등록하는 일이다. JDBC 드라이버의 문서를 찹조하여 해당 클래스를 찾자 `DriberManager.registerDriver(new com.mysql.jdbc.Driver());` > MySQL 드라이버의 경우`com.mysql.jdbc.Driber`클래스가 해당 인터페이를 구현한 클래스다. registerDriver()를 호출하여 구현체를 등록한다. ##### 데이터베이스에 연결 다음과 같이 DriverManager의 getConnection(0을 호출하여 MySQL서버에 연결할 수 있다. ```java conn = DriverManager.getConnection( "jdbc:mysql://localhost/jsp", //JDBC URL "root", // DBMS 사용자 아이디 "apmsetup"); // DBMS 사용자 암호 ) ``` - getConnecttion()의 첫 번째 인자값은 MySQL 서버의 접속정보다. (JDBC URL) - DriverManager는 등록된 JDBC드라이버 중에서 이 URL을 승인하는 드라이버를 찾아 java.sql.Driver 구현체를 사용하여 데이터베이스에 연결한다. - JDBC URL의 형식을 살펴보면 'jdbc.:mysql'은 JDBC 드라이버의 이름이고, '//localhost/jsp'는 접속할 서버의 주소(localhost)와 데이터베이스 이름(jsp)이다. - 이때 JDBC URL 형식은 드라이버에 따라 조금씩 다르므로 자세한 내용은 각 드라이버에서 제공하는 개발 문서를 참고하자 ``` jdbc:mysql:thin:@localhost:3306:jsp 사용할 JDBC드라이버 : 드라이버타입 : @서버주소:포트번호 : DB서비스 아이디 ``` - getConnection()의 두 번째와 세번째 인자값은 데이터베이스의 사용자 아이디와 암호다 - 이렇게 JDBC URL정보와 사용자 아이디, 암호를 가지고 MySQL서버에 연결을 요청하고, 연결에 성공하면 DB접속 정보를 다루는 객체를 반환한다. - 반환된 객체는 java.sql.Connection 인터페이스의 구현체 이다. - 이 반환 객체를 통해서 데이터베이스에 SQL문을 보내는 객체를 얻을 수 있다. > `java.sql.Connection` 인터페이스의 구현체 > 이 인터페이싀 정의된 주요 메소드는 다음과 같다 > - createStatement(), prepareStatement(), prepareCall()은 SQL 문을 실행하는 객체를 반환한다. > - commit(), rollback()은 트랜잭션 처리를 수행하는 메소드다. > **즉 이 구현체를 통해 SQL문을 실행할 객체를 얻을 수 있다.** ##### SQL 실행 객체 준비 Connection 구현체를 이용하여 SQL문을 실행할 객체를 준비한다. ```java stmt = conn.createStatement(); ``` - createStatement()가 반환하는 것은 java.sql.Statement 인터페이스의 구현체이다. - 이 객체를 통해 데이터베이스에 SQL문을 보낼 수 있다. - Statement 인터페이스에는 데이터베이스에 질의하는 데 필요한 메소드가 정의되어 있고, 이 인터페이스를 구현했다는 것은 반환 객체가 이러한 메소드들을 가지고 있다는 뜻이다. - 즉 반환 객체를 이용하면 SQL문을 서버에 보낼 수 있다. > `java.sql.Statement` 인터페이스의 구현체 > 이 인터페이스의 주요 메소드는 다음과 같다 > - excuteQuery() : 결과가 만들어지는 SQL문을 실행할 때 사용한다. 보통 SELECT문에 사용 > - excuteUpdate() : `DML`과 `DDL`관련 SQL문을 실행할 때 사용한다. > DML에는 `INSERT`, `UPDATE`, `DELETE` 명령문이 있고, `DDL`에는 `CREATE`, `ALTER`, `DROP` 명령문이 있다. > - excute() : SELECT, DML, DDL 명령문 모두에 사용 가능하다. > - excuteBatch() : addBatch()로 등록한 여러 개의 SQL문을 한꺼번에 실행할 대 사용한다. > **즉 이 구현체를 통해 연결된 데이터베이스에 SQL문을 보낼 수 있다.** ##### 데이터베이스에 SQL문을 보내기 아래 코드는 회원정보를 조회하는 SQL 문을 서버에 보내는 명령문이다. (SELECT 명령문은 excuteQuery) ```java rs = stmt.excuteQuery( "select MNO, MNAME, EAMIL, CRE_DATE from MEMBERS order by MNO ASC" ); ``` - `excuteQuery()`가 반환하는 객체는 java.sql.ResultSet 인터페이스의 구현체이다. - 이 반환객체를 통하여 서버에서 질의 결과를 가져올 수 있다. > `java.sql.ResultSet` 인터페이스의 구현체 > 이 인터페이스의 주요 메소드는 다음과 같다 > - `first()`는 서버에서 첫 번째 레코드를 가져온다 > - `last()`는 서버에서 마지막번째 레코드를 가져온다 > - `previous()`는 서버에서 이전 레코드를 가져온다. > - `next()`는 서버에서 다음 레코드를 가져온다 > - `getXXX()`는 레코드에서 특정 칼럼의 값을 꺼내며 XXX는 칼럼의 타입에 따라 다른 이름을 갖는다 > - `updateXXX()` 는 레코드에서 특정 칼럼의 값을 변경한다. > - `deleteRow()`는 현재 레코드를 지운다. > **즉 이 구현체를 사용하여 서버에 만들어진 SELECT결과를 가져올 수 있고, 가져온 레코드에서 특정 칼럼 값을 꺼낼수 있다.** ##### HTML페이지에 쿼리결과 뿌려주기 ```java while(rs.next()) { out.println( rs.getInt("MNO") + "," + rs.getString("MNAME") + "," + rs.getString("EMAIL") + "," + rs.getDate("CRE_DATE") + "<br>" ); } ``` - 서버에서 받은 레코드는 ResultSet 객체에 보관된다 - next()는 서버에서 레코드를 받으면 true, 없으면 false를 반환한다. > 레코드에서 칼럼값을 꺼낼 때는 getXXX()를 호출한다. - getXXX의 인자값은 SELECT결과의 칼럼 인덱스나 칼럼 이름이 될 수 있다. - 이때 주의할점은 칼럼 인덱스는 `1`부터 시작한다는 것이다. ```sql select MNO from MEMBERS order by MNO ASC ``` > 예를 들어 위 쿼리의 결과 값인 `MNO`를 꺼내온다면 다음과 같다 ```java // MNO가 숫자이기 때문에 getInt 만약 이름(MNAME)을 불러온다면 getString(MNAME) getInt(1); getInt("MNO"); // 인덱스는 순서에 영향을 받기 때문에 보통 이와같이 칼럼명으로 사용하면 된다. ``` ##### 마무리 JDBC 프로그래밍을 할 때 주의할 점은 정상적으로 수행되든 오류가 발생하든 간에 반드시 자원해제를 수행하는 것이다. 자원을 해제하기 가장 좋은 위치는 `finally 블록`이다. 자원을 해제할 때는 역순으로 처리한다. ##### 서블릿 배치 정보 설정 > `@WebServlet` 어노테이션으로 서블릿의 배치 정보를 설정한다. > 만약 서블릿 컨테이너가 Servlet2.5 사양을 따른다면 어노테이션을 이용한 설정 방법은 사용할 수 없기때문에 > Web.xml 파일에 배치 정보를 작성하잗. ```java @WebServlet("/member/list") ``` --- ### 2) HttpServlet 으로 GET 요청 다루기 HttpServlet 클래스를 사용하여 서블릿을 만드는 방법을 이용하면, 지금까지 처럼 서블릿 클래스를 만들 때 service() 메소드를 정의했는데, HttpServlet 클래스를 상속받게 되면 service() 대신 doGet()이나 doPost()를 정의한다. ```java package servlets; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/member/add") public class MemberAddServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html; charset=UTF-8"); PrintWriter out = response.getWriter(); out.println("<html><head><title>회원 등록</title></head>"); out.println("<body><h1>회원 등록</h1>"); out.println("<form action='add' method='post'>"); out.println("이름: <input type='text' name='name'><br>"); out.println("이메일: <input type='text' name='email'><br>"); out.println("암호: <input type='<PASSWORD>' name='password'><br>"); out.println("<input type='submit' value='추가'>"); out.println("<input type='reset' value='취소'>"); out.println("</form>"); out.println("</body></html>"); } } ``` > 우선 아래처럼 `GenericServlet` 추상 클래스 대신 `HttpServlet`추상 클래스를 상속받자. ```java @WebServlet("/member/add") public class MemberAddServlet extends HttpServlet { ``` - `HttpServlet` 클래스는 `GenericServlet` 클래스의 하위 클래스기때문에 `HttpServlet`을 상속받으면`GenericServlet` 클래스를 상속받는 것과 마찬가지로 `java.servlet.Servlet`인터페이스를 구현한 것이 된다. > doGet() 메소드의 오버라이딩 ```java protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ``` `HttpServlet` 클래스에 정의된 메소드 중에서 doGet() 메소드를 오버라이딩 한다. - 클라이언트 요청이 들어오면 서블릿 컨테이너는 service()를 호출하기 때문에 지금까지 서블릿을 만들때 service()메소드를 작성해왔다. > 그러나 `service()`가 아닌 `doGet()`을 작성하는 이유는 다음과 같다 클라이언트 요청이 들어오면, 첫째로 상속받은 HttpServlet의 service() 메소드가 호출되고, 둘재 service()는 클라이언트 요청방식에 따라 doGet()이나 doPost(), doPut()등의 메소드를 호출한다. 따라서. HttpServlet을 상속받을 때 service()메소드를 직접 구현하기 보다는 클라이언트의 요청방식에 따라 doXXX() 메소드를 오버라이딩 하는 것이다. --- ### 3) HttpServlet 으로 POST 요청 다루기 doGET 처럼 doPOST()메소드를 작성하자. ```java @Override protected void doPost( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Connection conn = null; PreparedStatement stmt = null; try { DriverManager.registerDriver(new com.mysql.jdbc.Driver()); conn = DriverManager.getConnection( "jdbc:mysql://localhost/studydb", //JDBC URL "study", // DBMS 사용자 아이디 "study"); // DBMS 사용자 암호 stmt = conn.prepareStatement( "INSERT INTO MEMBERS(EMAIL,PWD,MNAME,CRE_DATE,MOD_DATE)" + " VALUES (?,?,?,NOW(),NOW())"); stmt.setString(1, request.getParameter("email")); stmt.setString(2, request.getParameter("password")); stmt.setString(3, request.getParameter("name")); stmt.executeUpdate(); response.setContentType("text/html; charset=UTF-8"); PrintWriter out = response.getWriter(); out.println("<html><head><title>회원등록결과</title></head>"); out.println("<body>"); out.println("<p>등록 성공입니다!</p>"); out.println("</body></html>"); } catch (Exception e) { throw new ServletException(e); } finally { try {if (stmt != null) stmt.close();} catch(Exception e) {} try {if (conn != null) conn.close();} catch(Exception e) {} } } ``` > JDBC 객체를 위한 참조 변수 선언 - '회원목록조회' 와 마찬가지로 JDBC 객체를 보관할 참조 변수를 선언한다. - 이번에는 insert SQL 문을 실행하기 때문에 ResultSet의 참조변수는 선언하지 않는다. ```java Connection conn = null; PreparedStatement stmt = null; ``` 이전 소스(MemberListServlet)와 다른점은 SQL 문을 실행하는데 `Statement` 대신 `PreparedStatement`를 사용한다는 것이다.. `PreparedStatement`는 반복적인 질의를 하거나, 입력 매개변수가 많은 경우에 유용하다. 특히 바이너리 데이터를 저장하거나 변경할 때는 `PreparedStatement` 만이 가능하다 ##### 입력 매개변수의 값 설정 입력 매개변수는 SQL문에서 `?` 문자로 표시된 입력 항목을 가리키는 말이다. 입력항목의 값은 SQL문을 실행하기 전에 setXXX() 메소드를 호출하여 설정한다. ```java stmt.setString(1, request.getParameter("email")); ``` getXXX와 마찬가지로 문자열이면 setString() 정수형이면 setInt(), 날짜형이면 setDate()을 호출하면 된다. 매개변수의 번호 역시 배열의 인덱스와 달리 `0`이 아닌 `1`로 시작한다. ##### SQL 질의 수행 SQL문을 준비하고 입력 매개변수에 값을 할당했으면 데이터베이스에 질의하면 된다 이때 excuteUpdate()를 호출하여 SQL을 실행한다. ```java stmt.executeUpdate(); ``` > 결과를 반환하는 SELECT 문을 실행할 때는 `excuteQuery()`를 호출하고, INSERT처럼 결과 레코드를 만들지 않는 DDL이나 DML종류의 SQL문을 실행할 때는 `excuteUpdate()`을 호출한다. ##### Statement vs.PreparedStatement | 비교항목 | Statement | PreparedStatement |--------|--------|---------| | 실행속도 | 질의할 때마다 SQL문을 컴파일한다. | SQL문을 미리 준비하여 컴파일해둔다. 입력 매개변수 값만 추가하여 서버에 전송한다. 특히 여러 번 반복하여 질의하는 경우, 실행속도가 빠름. | |바이너리 데이터전송 |불가능 | 가능 | 프로그래밍 편의성 |SQL문 안에 입력 매개변수 값이 포함되어 있어서 SQL문이 복잡하고 매개변수가 여러개인경우 코드관리가 힘들다. | SQL문과 입력 매개변수가 분리되어 있어서 코드 작성이 편리하다 --- ### 4) 요청매개변수의 한글 깨짐 처리 웹 브라우저에서 보낸 한글 데이터를 서블릿에서 꺼낼 때 글자가 깨지는 경우가 있다. 그 이유와 해결책을 알아보자 - 웹브라우저(내 경우엔 크롬) 기본 문자집합설정이 유니코드(UTF-8)로 설정된걸 확인 할수 있다. > 웹 브라우저가 웹 서버에 데이터를 보낼 때 문자형식 웹브라우저가 웹 서버로 데이터를 보낼 때는 웹 페이지의 기본 문자집합으로 인코딩하여 보내기 때문에 사용자가 입력한 값은 UTF-8 로 인코딩되어 서버에 전달된다. > 서블릿에서 데이터를 꺼낼 때 문자 형식 - 서블릿에서 getParameter()를 호출하면 이 메소드는 기본적으로 매개변수의 값이 ISO-8859-1(다른 말로 ISO-Latin-1)로 인코딩되었다고 가정하고 각 바이트를 유니코드로 바꾸고 나서 반환하게된다. - 즉, 클라이언트가 보낸 문자를 영어라고 간주하고 유니코드로 바꾼다는 말이다. - 바로 여기서 문제가 발생한다. - 서블릿이 웹 브라우져로부터 받은 한글 데이터는 UTF-8로 인코딩된 값이다. - UTF-8은 한글 한 자를 3바이트로 표현한다. - 서블릿은 3바이트를 하나의 문자로 인식하지 않고 각각의 바이트를 개별문자로 취급하여 유니코드로 변환한다. - 이렇게 각각의 의미없는 바이트들을 유니코드로 바꿨기 때문에 한글이 깨진것이다. > 한글깨짐 해결책 - getParameter()를 호출하기 전에 클라이언트가 보낸 매개변수의 값이 어떤 인코딩으로 되어 있는지 지정해야 한다. ```java throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); <<이부분을 추가했다. Connection conn = null; PreparedStatement stmt = null; ``` > HttpServletRequest의 setCharacterEncoding()은 매개변수 값의 인코딩 형식을 지정하는 메소드다. > 단, 이 메소드가 호출되기 전에 getParameter()가 먼저 호출된다면 아무 소용이 없다. GET요청의 쿼리스트링에 대해서는 위 내용이 적용안되기 때문에 GET요청으로 받아오는 문자열이 깨질때는 톰캣서버의 server.xml을 수정하자 --- ### 5) 리프레시 일정시간이 지나고 나서 자동으로 서버에 요청을 보내는 방법을 알아보자 실행 프로세스는 다음과 같다. 1. 웹 브라우저에서 '회원 등록 입력폼'을 요청 2. `MemberAddServlet`은 회원 등록폼을 클라이언트로 보낸다. 3. 웹 브라우저는 회원 등록폼을 화면에 출력한다. 사용자가 회원정보를 입력하고 나서 '추가'버튼을 누르면 서버에 등록을 요청한다. 4. `MemberAddServlet`은 회원 등록 결과를 클라이언트로 보낸다. 5. 웹 브라우저는 회원 등록 결과를 출력한다. 그리고 1초후에 서버에 '회원목록'을 요청한다. 6. `MemberListServlet`은 회원 목록을 클라이언트로 보낸다. > 위 내용의 골자는 `MemberAddServlet`에서 회원 등록 결과를 웹 브라우져로 보낼 때 리프래시 정보를 함께 보내면 된다. > 아래코드를 try블록 제일 하단에 입력한다. ```java response.addHeader("Refresh", "1;url=list"); ``` > 또다른 방법은 HTML의 meta태그를 이용한 방법이다. ```java out.println("<meta http-equiv='Refresh' content='1; url=list'>"); ``` > 당연한 얘기지만 `meta태그`이므로 `<head>`안에 선언해야 한다. --- ### 6) 리다이렉트 리프레시와 비슷하지만 결과를 출력하지 않고 곧바로 회원목록 화면으로 이동하게 하는 방법이다. > 리다이렉트 메소드 `sendRedirect()` ```java // 리다이렉트를 이용한 리프래시 response.sendRedirect("list"); ``` --- ### 7) 서블릿 초기화 매개변수 ##### 서블릿 초기화 매개변수란? - 서블릿을 생성하고 초기화할 때, 즉init()를 호출할 때 서블릿 컨테이너가 전달하는 데이터이다. - 보통 DB 연결 정보와 같은 정적인 데이터를 서블릿에 전달할 때 사용한다. - 서블릿 초기화 매개변수는 DD파일(web.xml)의 서블릿 배치 정보에 설정할 수 있고, 어노테이션을 사용하여 서블릿 소스 코드에 설정할 수 있다. - 가능한 소스 코드에서 분리하여 외부 파일에 두는 것을 추천하는 데 이는 외부파일에 두면 변경하기 쉽기 때문이다. - 실무에서도 데이터베이스 정보와 같은 시스템 환경과 관련된 정보는 외부 파일에 두어 관리한다. ##### 회원 정보 조회와 변경 1. 웹 브라우저가 회원 목록을 요청(/member/list, GET) 한다 2. MemberListServlet 은 회원 목록을 웹브라우저로 보낸다, 웹 브라우저는 회원 목록을 출력한다. 3. 사용자가 회원 목록에서 이름을 클릭하면 회원 상세정보를 요청(/member/update, GET)한다 4. MemberUpdateServlet은 회원 상세 정보를 웹 브라우저에 보낸다. 5. 사용자가 회원 정보를 변경하고 저장을 클릭하면 회원 정보 변경을 요청(/member/update, POST 요청)한다. 6. MemberUpdateServlet은 회원 정보 변경 결과를 웹 브라우저에 보낸다. 웹브라우저는 그 결과를 출력한다. > 앞서 말했듯이 `web.xml`에 서블랫 배치 정보를 작성할 수 있다. > `<int-param>` 이 서블릿 초기화 매개변수를 설정하는 태그로, 이 엘리먼트는 `<servlet>`태그의 자식 엘리먼트이다. > `<int-param>` 에도 두 개의 자식 엘리먼트가 있는데, > `<param-name>`에는 매개변수의 이름을 지정하고 `<param-value>` 에는 매개변수의 값을 지정하면 된다. ```xml <init-param> <param-name>매개변수 이름</param-name> <param-value>매개변수 값</param-value> </init-param> ``` 매개 변수 값을 여러개 설정하고 싶으면 `<init-param>` 엘리먼트를 여러개 작성하면 된다 서블릿 초기화 매개변수들은 오직 그 매개변수를 선언한 서블릿에서만 사용할 수 있으며 다른 서블릿은 사용할 수 없다. 이처럼 서블릿 초기화 매개변수에 `DB` 정보를 두면 나중에 정보가 바뀌더라도 `web.xml` 만 편집하면 되기 때문에 유지보수도 쉬워진다. 실무에서도 이처럼 변경되기 쉬운 값들은 XML파일(.xml)이나 프로퍼티 파일(.properties)에 두어 관리한다. > 즉 내가 dbcon.jsp 파일로 별도로 만들어 import 했던 내용을 web.xml 로 셋팅해둘수 잇다는 말이다. ##### 초기화 매개변수를 이용하여 JDBC 드라이버 로딩 > 드디어 JSP 게시판 만들기와 다른 점이 나왔다. 참고사항! > 지금 까지는 아래와 같이 jdbc드라이버를 로드했었다면.. ```java DriverManager.registerDriver(new com.mysql.jdbc.Driver()); ``` `Class.forName()`을 사용하여 JDBC 드라이버클래스, 즉 java.sql.Driver를 로딩할 수 있다. > 클래스 로딩 ```java Class.forName(/* JDBC 드라이버 클래스의 이름 */) ``` > 아래는 JSP 로 처음 기본 게시판 셋팅시 내가 작성했던 코드다..비교해보자 ```java Class.forName("com.mysql.jdbc.Driver"); conn = DriverManaget.getConnection(디비주소,디비유저명,디비비밀번호); ``` - `Class.forName`은 인자값으로 클래스 이름을 넘기면 해당 클래스를 찾아 로딩한다. - 클래스 이름은 반드시 패키지 이름을 포함해야 한다. 보통 영어로 'fully qualified name' 또는 'QName'이라고 표현한다. - 자바 API에서 많이 등장하는 용어이니 반드시 기억하고 넘어가자 JDBC 드라이버 클래스의 이름은 서블릿 초기화 매개변수에서 얻어온다. 다음과 같이 `HttpServlet` 클래스에서 상속받은 `getInitParameter()`를 이용하면 서블릿 초기화 매개변수의 값을 꺼낼수 있다. > 서블릿 초기화 매개변수의 값 꺼내기 ```java this.getInitParameter(/* 매개변수 이름 */); ``` - getInitParameter() 은 해당 서블릿의 배치 정보가 있는 web.xml로부터 `<init-param>`의 매개변수 값을 꺼내준다. - 이때 반환하는 값은 문자열이다. > 최종적으로 아래와 같이 작성하면 된다. ```java Class.forName(this.getInitParameter("driver")); ``` > 데이터베이스 연결도 같은 방법으로 하면 된다. ```java conn=DriverManager.getConnection( this.getInitParameter("url"), this.getInitParameter("username"), this.getInitParameter("password") ) ``` > 쿼리 결과는 회원정보 상세보기인 만큼 한개의 정보만 가져오기 때문에 아래와 같이 next()를 한번만 호출하면된다. ```java rs = stmt.excuteQuery(select 쿼리 문); rs.nest(); ``` > 또한 web.xml이 아닌 `@WebServlet`어노테이션으로 설정할수도 있지만 소스코드에 정보가 들어가는만큼 추천하지않는다. > 언제라도 바뀔 수 있는 정보는 소스 파일이 아닌 외부 파일에 두어야 개발자가 아닌 시스템 운영자도 변경할 수 있기 때문이다. ```java @WebInitParam(name="driver". value="com.mysql.jdbc.Driver"); @WebInitParam(name="url". value="localhost/jsp"); // 이하 생략 ``` @WebInitParams 어노테이션의 initParams는 서블릿 초기화 매개변수를 설정하는 속성으로 이속성의 값은 @WebInitParam의 배열이다. `initParams={@WebInitParam(), @WebInitParam(), ...}` @WebInitParam은 두 개의 필수 속성과 한 개의 선택 속성이 올 수 있다. ```java @WebInitParam( name="매개변수 이름", // 필수 value="매개변수 값", // 필수 description="매개변수에 대한 설명" // 선택 ) ``` --- ### 8) 컨텍스트 초기화 매개변수 서블릿 초기화 매개변수는 말 그대로 그 매개변수가 선언된 서블릿에서만 사용할 수 있으며, 다른 서블릿은 참조할 수 없다. 따라서 JDBC 다르이버와 데이터베이스 연결정보에 대한 초기화 매개변수를 각 서블릿마다 설정해 줘야 하는 문제가 있다. 이런 경우에 컨텍스트 초기화 매개변수를 사용한다. `컨텍스트 초기화 매개변수`는 같은 웹 어플리케이션에 소속된 서블릿들이 공유하는 매개변수이다. > web.xml 에 아래와 같은 파라미터로 작성가능하며 작성양식은 서블릿 초기화 매개변수와 거의 흡사하다. ```xml <context-param> <param-name>driver</param-name> <param-value>com.mysql.jdbc.Driver</param-value> </context-param> <context-param> <param-name>url</param-name> <param-value>jdbc:mysql://localhost/studydb</param-value> </context-param> <context-param> <param-name>username</param-name> <param-value>study</param-value> </context-param> <context-param> <param-name>password</param-name> <param-value>study</param-value> </context-param> ``` > 컨텍스트 초기화 매개변수의 값을 얻으려면 `ServletContext 객체` 가 필요하다. > `HttpServlet`으로부터 상속받은 `getServletContext()`를 호출하여 `ServletContext()`객체를 준비한다. ```java ServletContext sc = this.getServletContext(); ``` --- ### 9) 필터 사용하기 - 필터는 서블릿 실행 전후에 어떤 작업을 하고자 할 때 사용하는 기술이다. - 예를 들면 클라이언트가 보낸 데이터의 암호를 해제한다거나, - 서블릿이 실행되기전에 필요한 자원을 미리준비한다거나, - 서블릿이 실행될 때마다 로그를 남긴다거나 하는 작업을 필터를 통해 처리할 수 있다. > 만약 이런 작업들을 서블릿에 담는다면 서블릿마다 해당 코드를 삽입해야 하고, > 필요가 없어지면 그 코드를 삽입한 서블릿을 모두 찾아서 제거해야 하므로 관리하기가 매우 번거로울 것이다. 예를 들면 지난 예제에서 `setCharacterEncoding()`을 호출하여 메시지 바디의 데이터 인코딩을 설정해줬었는데 이를 각 서블릿마다 매번 작성하기는 매우 번거롭다. 바로 이럴때 서블릿 필터를 이용하여 간단히 처리할 수 있다. - 필터클래스는 javax.servlet.Filter 인터페이스를 구현해야 한다. ```java package filters; 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.annotation.WebFilter; import javax.servlet.annotation.WebInitParam; @WebFilter( urlPatterns="/*", initParams={ @WebInitParam(name="encoding",value="UTF-8") }) public class CharacterEncodingFilter implements Filter{ FilterConfig config; @Override public void init(FilterConfig config) throws ServletException { this.config = config; } @Override public void doFilter( ServletRequest request, ServletResponse response, FilterChain nextFilter) throws IOException, ServletException { request.setCharacterEncoding(config.getInitParameter("encoding")); nextFilter.doFilter(request, response); } @Override public void destroy() {} } ```<file_sep>/guide/server/Nginx/Nginx.MD # NGINX ---------------- ##### 1. 개요 참고 URL : [dkatlf900.tistory.com/32](http://dkatlf900.tistory.com/32) --------------- ##### 2. 설치 및 실행 [다운로드 nginx.org/en/download.html](http://nginx.org/en/download.html) nginx는 다운로드 후 압축만 풀면 완료되기에 따로 설치가 필요 없습니다. 압축을 풀면 안의 exe파일을 실행합니다. 그 후 [localhost:80](http://localhost:80)을 입력하면 실행된 nginx를 사용하 실 수 있습니다.<file_sep>/java/god_of_java/Vol.1/11. 모든 클래스의 부모 클래스는 Object에요/README.md ## 11장. 모든 클래스의 부모 클래스는 Object에요 ### 1. 모든 자바 클래스의 부모인 `java.lang.Object` 클래스 > 아래소스를 `javap`로 확인해보자 ```java public class InheritanceObject{ public static void main(String[] args){ } } ``` > 클래스 선언문이 다음과 같이 되어있다. `public class InheritanceObject extends java.lang.Object` > 즉 자동으로 Object 클래스를 확장한 것을 알 수 있다. - 여기서 주의점은 자바는 이중상속은 안되지면 여러단계로 상속은 가능하다 --- ### 2. 가장 많이 쓰이는 `toString()` 메소드 객체를 처리하기 위한 메소드 - toString() - equals() - hashCode() - getClass() - clone() - finalize() > `to String()` 메소드 ```java public void toStringMethod(InheritanceObject obj) { System.out.println(obj); System.out.println(obj.toString()); System.out.println("plus " + obj); } ``` > 결과를 보면 그냥 출력하는 것과 toString() 메소드를 호출하는 것은 동일한 것을 볼수 있다. > 위 코드를 개선해보자 ```java public void toStringMethod2() { System.out.println(this); System.out.println(toString()); System.out.println("plus " + this); } ``` `toString()`메소드는 그냥 사용하는게 아니라 직접 구현해야한다( 오버라이딩 ) ```java public String toString() { return "InheritanceObject class"; } ``` > 변수가 몇개 안될경우는 상관없지만 10개를 넘어가거나 할 경우 효율이 떨어질 우려가 있다 > 이런 상황은 이클립스같은 IDE를 통해 추후 알아보자 > --- ### 3. 객체는 == 만으로 확인이 안 되므로, equals()를 사용한다. - 비교연산자인 `==`, `!=`는 기본자료형에서만 사용가능하다 > 정확하게는 "값"을 비교하는 것이 아니라 "주소값"을 비교한다고 생각하자. ```java MemberDTO obj1 = new MemberDTO("Sangmin"); MemberDTO obj2 = new MemberDTO("Sangmin"); ``` > 두 객체는 각각의 생성자를 사용하여 만들었기 때문에 주소값이 다름을 알 수 있다. > 속성값은 같지만 서로 다른 객체라는 말이다. > 바로 이때 사용하는것이 `equals()`메소드 이다. > 이 메소드 역시 Object 클래스에 선언되어있는 `equals()`메소드를 오버라이딩 해 놓아야지만 > 제대로 된 비교가 가능하다. > 그럼 비교를 아래와 같이 해보자 ```java if (obj1.equals(obj2)) { System.out.println("obj1 and obj2 is same"); } ``` > 이래도 결과는 다르다고 나온다 > 바로 이게 equals()메소드를 오버라이딩 하지 않았기 때문이다 > 즉 `hashCode()` 값을 비교하기 때문이다. > 아무리 클래스의 인스턴스 변수값들이 같다고 하더라도 , 서로 다른 생성자로 객체를 생성했으면 > 해시 코드가 다르니 위처럼 객체가 다르다는 결과가 나오는 것이다. `equals()`메소드를 Overriding 할때는 다음의 다섯가지 조건을 충족해야 한다. - 재귀 : null이 아닌 x라는 객체의 x.equals(x)결과는 항상 true 여야만 한다. - 대칭 : null이 아닌 x와 y객체가 있을 때 y.equals(x)가 true를 리턴했다면, x.equals(y)도 반드시 true를 리턴해야만 한다. - 타동적 : null이 아닌 x,y,z가 있을 때 x.equals(y)가 True를 리턴하고, y.equals(z)가 true 를 리턴하면, x.equals(z)는 반드시 true를 리턴해야만 한다. - 일관 : null이 아닌 x와y가 있을 때 객체가 변경되지 않은 상황에서는 몇 번을 호출하더라도, x.equals(y)의 결과는 항상 true이거나 항상 false여야 한다. - null과의 비교 : null이 아닌 x라는 객체의 x.equals(null) 결과는 항상 false여야만 한다. > `equals()`메소드를 Overriding 할때에는 `hashCode()`메소드도 같이 Overriding 해야만 한다. --- <file_sep>/python/algorithm/factorial.py def fact(n): return result print(fact(1)) print(fact(5)) print(fact(10)) <file_sep>/guide/android/gcm.MD #GCM(Google Cloud Messaging) ## 푸시 #### GCM 시스템 푸시를 보내고 싶은 해당 앱의 토큰을 얻어다가 푸시서버에서 얻어진 토큰들을 상대로 푸시를 발송하면 푸시가 발송된다. 1. 안드로이드 개발자 센터를 통해 GCM API KEY를 생성한다. 2. 앱 소스에 GCM 토큰생성 및 알림발생 코드를 삽입한다. 3. 토큰생성 소스를 통해 생성된 토큰을 푸시서버에 발송하고 푸시서버에서는 발송된 토큰을 저장한다. 4. 이렇게 저장된 토큰을 가지고 푸시서버에서 해당 토큰들에게 푸시를 발송한다. 5. 푸시가 발송되면 해당 앱의 리시버가 전달받아 알림발생코드를 통해 알림을 출력한다. #### 테스트 방법 푸시서버에서 발송을 했다고 가정하고 |앱 설치 |핸드폰 상태 |인터넷 상태 |백그라운드 상태|앱 실행 |알림 | |-----------|-----------|-----------|-------------|-----------|-----------| |O |실행 |O |O |O |O | |O |실행 |O |O |X |O | |O |실행 |O |X |X |O | |O |실행 |X |- |- |O | |O |종료 |- |- |- |O | |O |- |X |- |- |X | |X |- |- |- |- |X | - 앱이 설치되어 있으며 핸드폰은 실행중이고 인터넷이 연결되어 있다면 즉시 알람을 받을 수 있다. - 인터넷이 연결되어 있지 않은 경우는 인터넷이 연결되면 알림이 실행된다. - 핸드폰 전원이 꺼있다면 켜진 후에 인터넷이 연결되면 알림이 실행된다. - 즉 앱이 삭제 상태만 아니라면 알림을 받을 수 있다. ---------------------------------------------------------------------------- #### 참고자료 - GCM 테스트 [http://blog.saltfactory.net/android/implement-push-service-via-gcm.html](http://blog.saltfactory.net/android/implement-push-service-via-gcm.html) - GCM 전송 [https://gcmsender.herokuapp.com/](https://gcmsender.herokuapp.com/) - 안드로이드 개발자 센터 [https://developers.google.com](https://developers.google.com) - GCM 관리 [https://console.firebase.google.com](https://console.firebase.google.comㅊ) #### 푸시서버 구축 및 통계 푸시를 위한 토큰관리, 메시지 제목입력, 통계데이터 등 푸시서버 구축에 관한 부분은 구글에서 지원하는 방식을 사용해도 되고 따로 구축해도 되는 것으로 판단된다.<file_sep>/guide/전자정부프레임워크/README.md # 전자정부프레임워크 Guide ## 목차 1. 전자정부 프레임워크 개요 2. 전자정부 프레임워크 기능 소개 3. 전자정부 프레임워크 구성 4. 결론 ## 1. 전자정부프레임워크 개요 ### 1-1. 스펙 (3.X) - egovFrame 버전 : 3.5,1 - JDK : 1.7/1.8(권장) - Spring Framework : 3.2.9 - Spring Security : 3.2.4 - log4j : 2.0 (SLF4J 도입) - eclipse : 4.4(Luna) - 공통컴포넌트 : 250개(모바일포함) ### 1-2. 3.X 버전의 주요 개선기능 #### 코드표준화 로그 표준화 및 성능 개선 - XML 환경설정 단순화 - 파라미터 메시지 방식으로 log 메시지 출력 - 로깅방식 표준화 `SLF4J + Log4j 2` #### 신규기능 기존 XML 상에 설정되는 정보를 DB 상으로 관리할 수 있는 DB기반 설정관리 기능`(Property'Service)`을 통해 개발/운영 시스템 간의 유연한 관리가 가능하게 됨 > 특장점 - Spring Framework(Container) 설정 정보 DB 분리 관리 가능 - 운영시스템(개발/운영 등)에 따른 설정 분리 가능 - 보안이 필요한 설정정보를 DB로 관리함으로써 보안 강화 (ex:암복호화 키 DB저장 등) > 표준 프레임워크 3.1 - 공통컴포넌트 및 표준프레임워크 KISA'보안 점검 및 보완' > 표준 프레임워크 3.2 - 공통컴포넌트 기능 확대 (229종 -> 250종) - 이중등록(Double Submit)방지 - 약도관리, 도로명 주소 연계 - 기존 에디터를 `ckEditor` 로 교체 ## 2. 전자정부프레임워크 기능 소개 - Spring Security 간소화 - MyBatis - Spring Data JPA - DB Property - SLF4J - Cache Abstraction ### 2-1. Spring Security 간소화 - XML 스키마(egov"security)를 통해 설정 최소화 기능 제공 - 기존 Security 기능과 호환 (설정 기능만 제공) > XML 네임스페이스 및 스키마 설정 ```xml <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:egov-security="http://www.egovframe.go.kr/schema/egov-security" xmlns:security="http://www.springframework.org/schema/security" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.egovframe.go.kr/schema/egov-security http://www.egovframe.go.kr/schema/egov-security/egovsecurity-3.0.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/springsecurity-3.2.xsd"> </beans> ``` > egov-security 기본설정 예제코드 ```xml <egov-security:config id="securityConfig" // 하기 1) egov-security 필수 설정 표 참조 loginUrl="/cvpl/EgovCvplLogin.do" logoutSuccessUrl="/cvpl/EgovCvplLogin.do" loginFailureUrl="/cvpl/EgovCvplLogin.do?login_error=1" accessDeniedUrl="/system/accessDenied.do" // 하기 2) egov-security 선택 설정 표 참조 dataSource="dataSource" /** * jdbcUsersByUsernameQuery * 해당 쿼리는 3번째까지는 정해져있다.(컬럼명이 아닌 순서가 필수) * 1. USER_ID * 2. PASSWORD * 3. ENABLED : 임시 Lock 등의 처리를 위해 지원 * 예)로그인 5회 실패시.. */ jdbcUsersByUsernameQuery="SELECT USER_ID,PASSWORD,ENABLED,USER_NAME,BIRTH_DAY,SSN FROM USERS WHERE USER_ID = ?" jdbcAuthoritiesByUsernameQuery="SELECT USER_ID,AUTHORITY FROM AUTHORITIES WHERE USER_ID = ?" // Map 기반으로 jdbcUsersByUsernameQuery 조회결과 처리 jdbcMapClass= "e.r.f.security.userdetails.EgovUserDetailsMapping" requestMatcherType="ant" // md5 방식은 보안상 확실하게 뚤렸기때문에 sha 방식으로 지원 hash="sha256" /> ``` > 1) egov-security 필수 설정 | 속성 | 설명 | 부가설명 |--------|--------|-------| | loginUrl | 로그인 페이지 URL | 특정 보안통제가 되는 Url 에 접근시 로그인 페이지로 전환하고 그때 사용되는 URl 뭔지 지정하는 속성 | logoutSuccessUrl | 로그아웃 처리 시 호출되는 페이지 URL | - | | loginFailureUrl | 로그인 실패 시 호출되는 페이지 URL | 주로 로그인 페이지로 이동하지만 로그인 실패후 로그인페이지 이동등을 구별할 겨웅 사용 | accessDeniedUrl | 권한이 없는 경우 호출되는 페이지 | 로그인 성공했지만 권한이 없을경우 (접근할 수 없는 페이지에 접근했을때 리다이렉트 되는 페이지)| > 2) egov-security 선택적 설정 | 속성 | 설명 | |--------|--------| | dataSource | DBMS 설정 dataSource | | jdbcUsersByUsernameQuery | 인증에 사용되는 쿼리 | | jdbcAuthoritiesByUsernameQuery | 인증된 사용자의 권한(authority) 조회 쿼리 | | jdbcMapClass | 사용자 정보 mapping 처리 class | > egov-security 초기화 설정 예제코드 ```xml <egov-security:initializer id="initializer" // method 방식 지원 여부 supportMethod="true" // 포인트컷 방식 지원 여부 supportPointcut="false" /> ``` > egov-security 추가 설정 예제코드 ```xml <egov-security:secured-object-config id="securedObjectConfig" /** * roleHierarchyString * 계층처리를 위한 설정 문자열 지정 * 미 지정시 DB로부터 지정된 설정정보 사용 */ roleHierarchyString=" ROLE_ADMIN > ROLE_USER ROLE_USER > ROLE_RESTRICTED ROLE_RESTRICTED > IS_AUTHENTICATED_FULLY IS_AUTHENTICATED_FULLY > IS_AUTHENTICATED_REMEMBERED IS_AUTHENTICATED_REMEMBERED > IS_AUTHENTICATED_ANONYMOUSLY" sqlRolesAndUrl=" SELECT auth.URL url, code.CODE_NM authority FROM RTETNAUTH auth, RTETCCODE code WHERE code.CODE_ID = auth.MNGR_SE" />``` ### 2-2. MyBatis - 표준프레임워크에서는 실행환경 2.6 부터 지원 - DAO 처리방식은 3가지를 지원한다. > DAO 처리 방식 - 1) class 방식 ```java public class DeptMapper extends EgovAbstractmapper { public void insertDept(DeptVO vo){ ...생략 } } ``` - 2) interface 방식 `package` 네임과 `method` 네임의 조합으로 쿼리를 맵핑 - 3) Annotation 방식 `Annotation`에 직접 쿼리 입력 (다이나믹쿼리 지원 X) ### 2-3. Spring Data - 다양한 NoSql 지원을 위한 Spring Data 하위 프로젝트 - Spring Data의 Repository 지원을 통해 DataStorage에 대한 통일된 인터페이스 제공 - 표준프레임워크 2.6 부터 지원 > Spring Data 개요 - RDB -> `JPA`, `JDBC Extentions` - Big Data -> `Hadoop` - Data-grid -> `GemFire` - HTTP -> `REST` - Key Value Stores -> `Redis` - Document Stores -> `MongoDB` - Graph db -> `Neo4j` - Column Stores -> `HBase` 스프링 기반의 통일되어있는 데이터 엑세스에 대한 프로그램 모델을 지원한다. > 기존방식과의 차이점 기존에는 컨트롤러가 VO 등을 통해 `Data Access` 를 활용해서, 주로 `MyBatis`, 하이버네이트, JPA 등이 RDB에 접근하는 역할을 해왔다. 하지만 `다양한 Storage` 와 새로운 여러 DB 등이 나오게 되면서 (`GemFire`, `MongoDB`, `Neo4j` 등등...) 기존에 쓰던 데이터엑세스 기술을 활용하지 못해, 새로운 기술들이 필요할경우 전부 개별적으로 구현을 해야 했고 이에 따라 당연히 관리도 어려웠다. 하지만 `Spring Data Repository` 방식으로 구현을 해놓으면 다양한 DB 들과 여러가지 기술들을 통일된 방식으로 쓸 수 있다. > `spring Data Repository` 마틴파울러가 정의한 내용으로 데이터를 맵핑하는데 콜렉션 기반의 인터페이스다 참고 URL : http://marNnfowler.com/eaaCatalog/repository.html > 실질적인 활용방법 1. `Repositry` 정의 데이터 스토리지 기술마다 `Repositry`를 정의하고 2. `Repositry` 안에 데이터오브젝트 정의 `Repositry` 에서 표준적으로 사용하는 인터페이스 - CrudRepository - 기본적인 CRUD, findOne, exists, findAll, cound 등... ```java public interface BoardRepository extends CrudRepository<Board, String> { } ``` - PagingAndSortingRepository - CrudRepository를 상속해서 페이징 처리와 정렬을 위한 기능을 확장지원해준다. ```java public interface UserRepository extends PagingAndSortingRepository<User, String> { } ``` - 필요시 페이징에 검색 조건도 추가해서 사용할 수도 있다. ```java public interface ArticleRepository extends PagingAndSortingRepository<Article, Integer> { public List<Article> findByBoardKeyAndDeletedFalse( String boardKey); public Page<Article> findByBoardKeyAndDeletedFalse( String boardKey, Pageable pageable); } ``` ### 2-4. DB PropertySouce - DB로부터 설정 정보를 가져와 Spring 설정 property로 사용 - 개발/운영 등 환경에 따른 설정 관리에 대한 유연성 제공 - 보안이 필요한 설정정보를 DB로 관리함 (ex: 암복호화 키 DB 저장등) - 표준프레임워크 3.0부터 제공 > DB 테이블 설정 예제 SQL ```sql CREATE TABLE PROPERTY ( PKEY VARCHAR(20) NOT NULL PRIMARY KEY , PVALUE!VARCHAR(20) NOT NULL ); INSERT INTO PROPERTY (PKEY, PVALUE) VALUES ('encryptKey', 'user'); INSERT INTO PROPERTY (PKEY, PVALUE) VALUES ('encryptPassword', '<PASSWORD>'); ``` > XML 설정 예제코드 ```xml <jdbc:embeddedMdatabase id="dataSource" type="HSQL"> <jdbc:script location="classpath:db/ddl.sql" /> <jdbc:script location="classpath:db/dml.sql" /> </jdbc:embeddedMdatabase> <bean id="dbPropertySource" class="egovframework.rte.fdl.property.db.DbPropertySource"> <constructorMarg value="dbPropertySource"/> <constructorMarg ref="dataSource"/> <constructorMarg value="SELECT PKEY, PVALUE FROM PROPERTY"/> </bean> ``` > web.xml 설정 예제코드 > 주의할 점은 DB에서 설정정보를 가져와서 xml를 설정하기 때문에 `ApplicaNonContextIniNalizer`에 의해 Spring context 기동 전에 처리해야 한다. ```xml <contextMparam> <paramMname>contextInitializerClasses</paramMname> <paramMvalue>egovframework.rte.fdl. property.db.initializer.DBPropertySourceInitializer </paramMvalue> </contextMparam> <contextMparam> <paramMname>propertySourceConfigLocation</paramMname> <paramMvalue> classpath:/initial/propertysource.xml </paramMvalue> </contextMparam> ``` ### 2-5. SLF4J - `SLF4J`는 특정 Logging 서비스 구현체에 비종속적으로 추상화 계층을 제공한다. (기본 구현체는 log4j ) - `JCL`, `Log4j`, `LogBack` 등의 다양한 로거와 함께 사용가능하다. - 표준프레임워크 3.0부터 지원한다. > SLF4J 사용 ( Log4J 기준) 예제코드 ```java // log4j 에서 import와 logger 선언 이름 정도만 바꿔주면 되며, 사용방법은 log4j 와 동일하다. import org.slf4j.Logger; import org.slf4j.LoggerFactory; private static final Logger LOGGER = LoggerFactory.getLogger(ClassName.class); ``` ### 2-6. Cache Abstraction - SLF4J 처럼 추상화 계층을 제공한다. (기본 구현체는 ehCache ) - 메소드 단위 cache 지정방식 - 표준프레임워크 3.0 부터 제공 > 추상화 계층을 제공 많이 사용하는 `ehCache`를 기본 구현체로 했으며 필요시 변경하여 사용할 수 있다. > 메소드 단위 cache 지정방식 말그대로 특정 리스트 메소드를 분리하여 `cache`설정을 할 수 있고, (예) 공지사항 리스트에는 적용, 댓글리스트에는 미적용 ) 리스트에 Insert, update, delete 등으로 변화가 생겼을시에 `cache`를 무효하는 등의 기본적이 어노테이션등을 지원한다. ## 3. 전자정부 프레임워크 구성 ### 3-1. 구성 요소의 기능과 역할 전자정부 프레임워크의 전체적인 구성은 아래 그림과 같다. ![](http://uiux.bstones.co.kr/docs_images/egovMD/table_07.jpg) 구성요소중 사실상 주가 되는부분은 개발환경, 실행환경, 공통 컴포넌트로 개발환경은 === > eclipse 기반에 개발환경과 형상서버를 포함한 CI라고 하는 서버 개발환경을 제공한다. > 이 부분은 선택적이라 필요에 따라 적용하면 되며, > Maven 이 필요하다면 Maven만이라도 사용하면되는 구조다. 그외에 운영환경 같은 경우는 모니터링도구와 커뮤니케이션 도구를 제공한다. 실행환경은 === > Spring 프레임워크 기반의 몇몇 오픈소스SW로 framework의 기능들을 제공한다. > 그 중 표준화된 아키텍쳐와 몇 가지 준수사항만을 만족하면 표준프레임워크를 사용한 것으로 인정이 된다 > - (Annotation 기반의 Spring MVC 사용 > - layered 아키텍처 준수 -> @Controller, @Service, @Repository를 사용 > - Data Access 부분은 iBatis 또는 MyBatis, 또는 JPA 사용 그 외에 Cache 서비스, 암복호화 서비스 등의 30여종 서비스를 제공하지만 이는 선택사항이다. > 모니터링 도구 동작 정보와 수행로그를 수집하고 시스템 상태에 대한 모니터링 기능제공 - 에이전트 관리 : 스케쥴, 로깅등의 설정을 기반으로 모니터링 대상 시스템에서 실행 - 모니터링 정보 수집 : 에이전트가 실행되면서 시스템 정보 및 프로그램 로그 수집 기록 - 운영자 GUI : 운영자에게 수집된 정보를 그래프, 차트등으로 표현 > 커뮤니케이션 도구 프로젝트에서 발생하는 각종 관리항목에 대한 등록 및 관리기능을 제공한다. - 일정관리 - 개선요청 - 설정관리 - 운영정보 - 산출물관리 - 결재관리 - 게시판자료실 #### 배치운영 도구 - 일괄(배치) 개발/실행환경에서 작성된 배치Job을 등록/실행하고 수행현황을 모니터링하며 처리결과를 확인하기 위한 표준화된 운영환경을 제공 ![](http://uiux.bstones.co.kr/docs_images/egovMD/img_batchtool.jpg) --- ### 3-2. 공통컴포넌트 구성 ![](http://uiux.bstones.co.kr/docs_images/egovMD/EgovCommonArchitecture.JPG) > 공통 컴포넌트란? 말뜻 그대로 공통적으로 재사용이 가능한 기능위주로 개발한 컴포넌트의 집합을 뜻하며, 현 시점에서 공통컴포넌트는 모바일을 포함해 250개 정도된다. 이 공통컴포넌트들의 경우 사실상 컴포넌트 보다는 템플릿(재사용 용도)에 가깝고 대다수의 사람들은 공통 컴포넌트를 **쓸 수 없다**로 축약하고 있다. 그 예로는 준수사항중에 DAO 를 egov 에서 제공하는 특정 클래스를 반드시 상속받아야 한다거나 하는 규칙등이 있어서 사내 자체의 프로세스와 맞지 않다거나 확장에 문제가 생기는 등의 문제들을 주로 꼽고있다. > 참고 이미지 ![](http://uiux.bstones.co.kr/docs_images/egovMD/capture1.jpg) ## 4. 결론 ### 특장점 장점 - 이미 많은 기능들을 제공하고 있다 - 수요가 많다. - 환경셋팅이 비교적 쉬우며, 예제가 많아 진입장벽이 낮다 (스프링 대비) 단점 - 꽤 많은 리소스를 잡아 먹는다 - 개발의 자율성이 떨어진다. - 버그가 많다 ### 결론 이미 많은 기능들이 구현되어있고, 프로젝트 속성에 따라 컴포넌트들을 사용할지 말지 선택적으로 사용하면 프로젝트 구성에는 문제가 없을것 같으나 기존의 회사 라이브러리와 구현 방식등에 차이점등이 명확한 만큼, `egovFramework`를 사용한다면 그에따른 선행학습이 **필수** 요소로 작용한다. 물론 `프레임워크`자체가 어느정도의 학습비용을 필요로 하지만, `egovFramework`는 조금더 많은 학습비용을 필요로 할 것으로 예상된다. 참고 : [전자정부 프레임워크 가이드 wiki](http://www.egovframe.go.kr/wiki/doku.php) <file_sep>/java/god_of_java/Vol.1/06. loop/README.md ## 6장 제가 조건을 좀 따져요 ### Loop - if - switch - for - while - for > 다른 언어들과 특별히 다른건 없어 보인다 Python 이나 Ruby 완 다르게 그냥 쓰던대로 쓰면 될것 같다. > 혹 문제가 생긴다면 구글링정도로.. > PHP 에서는 break 를 궂이 쓰지 않았는데 간단한 알고리즘 자체에서 구현에 문제가 없었던 건지 java와 다른점인지 정도만 > 짚고 넘어가면 될 것 같다. ```java public class ControlOfFlow{ // 중간 생략 public void switchStatatement(int numberOfWheel) { switch(numberOfWheel){ case 1: System.out.println("It is one foot bicycle"); //break; case 2: System.out.println("It is a motor cycle or bicycle"); //break; case 3: System.out.println("It is a Three whell car."); break; case 4: System.out.println("It is a Three whell car."); break; /* 이하 케이스 생략 */ default : System.out.println("It is ans expensive car"); break; } } } ``` > Result > 1~3번째 출력문 까지 출력 > break 문은 기타 언어와 사용법이 동일하다. > 다만 궂이 유의할점은 default 값은 마지막에 쓰길 권장하며 > 숫자비교시엔 되도록 적은 숫자부터 증가시켜 가는것이 좋다고 한다. > 또한 JDK7 (회사 로컬에 셋팅한 자바도 7버전대로 기억한다...톰캣도 7대...) 부터는 String 도 사용할 수 있다고 한다. ```java public void switchStatement2(int month) { switch(month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: System.out.println(month + " has 31 days." ); break; case 4: case 6: /* 이하 생략 각각 30일 , 28 || 29 그리고 기본값 코드 작성이다. */ } } public void whileLoop() { int loop = 0; while(loop<12) { loop++; switchStatement2(loop); if(loop == 6) break; } } ``` ```java public void whileLoop2() { int loop=0; do { loop++; switchStatement2(loop); } while(loop<12); // 세미콜론을 반드시 찍어줘야한다. } ``` > do~ while 문은 적어도 한번은 꼭 실행된다. > 위 조건문은 whileLoop 와 동일한 로직이다. <file_sep>/python/algorithm/max.py def max(a): n=len(a) r = a[0] for i in range(0,n): if r < a[i]: r = a[i] return r v=[17,92,18,33,58,7,33,42] print(max(v)) <file_sep>/php/06-1 . 자주 사용하는 함수 .md # 자주 사용하는 php 함수 ## 자료형 관련 - #### **var\_dump();** - var\_dump()는 파라키터로 주어진 값의 자료형과, 크기, 값을 출력합니다. - echo 기능이 들어있으므로 따로 출력을 위한 선언을 하지 않아도 됩니다. ## 문자열 관련 - #### **trim();** - trim()은 문자열 앞뒤의 공백을 제거합니다. <br /> - #### **nl2br();** - 문자열에 포함된 줄바꿈(\r , \n)문자를 < br />태그로 변환합니다. <br /> - #### **strlen($param);** - strlen()은 파라미터로 전달 받은 문자열의 길이 를 반환합니다. <br /> - #### **strcmp($param1 , $param2);** - strcmp($param1 , $param2)은 파라미터로 전달 받은 $param1 과 $param2의 값을 비교합니다. <br /> - #### **strcasecmp($str1,$str2);** - strcasecmp($str1,$str2)은 strcmp()와 기능은 같지만, 차이점으로 대소문자를 비교하지 않습니다. <br /> - #### **str_replace($param1 , $param2, 원본문자열);** - str\_replace($param1 , $param2, 원본문자열)은 원본문자열에서 $param1을 찾아 $param2로 바꾼뒤 결과를 반환합니다. <br /> - #### **substr($원본문자열 , $찾을위치 , $갯수);** - substr()은 $원본문자열에서 $찾을 위치의 인덱스로부터 $갯수만큼의 문자열을 잘라서 반환합니다. <br /> - #### **explode(토큰, 자를문장);** - 자를문장이 'abc:abcde:poiuytre'이고, 토큰이 : 일때, - 출력값을 배열의 형태로 array(abc , abcde , poiuytre);가 반환된다. ## arrray 관련 - #### **array\_push($배열 , $값);** - 배열의 끝에 값을 집어 넣을경우에 사용합니다. <br /> - #### **sort();** - 배열을 정렬할때 사용합니다. <br /> - #### **rsort();** - 역순으로 배열을 정렬할때 사용합니다. <br /> - #### **sizeof();** - 배열의 모든 원소나, 객체의 프로퍼티 수를 셉니다. - sizeof의 별칭으로 count가 있습니다. <file_sep>/java/god_of_java/Vol.2/01. 매번 만들기 귀찮은데 누가 만들어 놓은 거 쓸 수 없나요/README.md ## 1장. 매번 만들기 귀찮은데 누가 만들어 놓은 거 쓸 수 없나요? ### 미리 만들어 놓은 클래스들은 아주 많아요 밑바닥에서부터 자바 프로그램을 아무 것도 없는 상태에서 개발한다고 생각해보자.. 아주 간단한 프로그램을 작성하더라도 꽤 오랜 시간과 노력이 소요될 것이다. > 그래서 우리가 설치해서 사용중인 `JDK`에는 엄청나게 많은 클래스와 메소드들이 포함되어 있다. > 물론, `JDK`에 포함된 클래스들 외에도 많은 클래스들이 존재한다. 이런 많은 클래스를 사용할 때 참조하는 문서가 바로 `API`라는 것이다. > [자바 API 바로가기(JDK 7)](http://docs.oracle.com/javase/7/docs/api/) `java.lang`패키지의 `String`클래스를 살펴보자 [해당 링크 바로가기](http://docs.oracle.com/javase/7/docs/api/) ##### 1) 패키지와 클래스 / 인터페이스 이름 - 패키지와 클래스 이름이 다음과 같이 제공된다. ```java java.lang Class String ``` ##### 2) 클래스 상속 고나계 다이어그램(Class Inheritance Diagram) - 이 클래스가 어떤 클래스들의 상속을 받았는지에 대한 관계를 간단한 계단식을 보여준다. ```java java.lang.Object java.lang.String ``` > 이 관계를 보는 것은 아주~~~~~~~중요하다. 왜냐하면, 해당 클래스의 객체에서 사용할 수는 있지만, 지금 보고 있는 페이지에 메소드에 대한 상세 설명은 존재하지 않을 수도 있기 때문이다. > API 문서는 부모클래스에 선언되었지만, 자식 클래스에서 별도로 `오버라이딩`을 하지 않은 메소드는 자세한 설명이 제공되지 않는다. > 따라서, 사용 가능한 메소드가 있는데 그 클래스의 API에 없다면 부모 클래스들의 메소드들을 살펴봐야만 한다. ##### 3) 직속 자식 클래스(Direct Known Subclasses) - 현재 보고 있는 클래스를 확장한 클래스들의 목록이 나타난다. - 지금 보고있는 `String`클래스는 `final`클래스이기 때문에 더이상 자식을 갖지 못한다. - 참고를 위해 같은 패키지에 있는 `Throwable`클래스의 직속 자식 클래스 내용을 보자 ```java Direct Known Subclasses: Error, Exception ``` ##### 4) 알려진 모든 하위 인터페이스 목록(All Known Subinterfaces): 인터페이스에만 존재함 - 인터페이스를 상속받은 인터페이스 목록을 나타낸다. > `String`클래스는 인터페이스가 아니므로, `java.lang` 패키지의 `Runnable`이라는 인터페이스의 관련된 정보를 보자 ```java All Known Subinterfaces: RunnableFuture<V>, RunnableScheduledFuture<V> ``` ##### 5) 알려진 모든 구현한 클래스 목록(All Known Implementing Classes) : 인터페이스에만 존재함 - 해당 인터페이스를 구현한 클래스들의 목록이다. 방금 살펴본 `Runnable`이라는 인터페이스와 관련된 정보는 다음과 같다. ```java All Known Implementing Classes: AsyncBoxView.ChildState, ForkJoinWorkerThread, FutureTask, RenderableImageProducer, SwingWorker, Thread, TimerTask ``` > 어떤 인터페이스로 선언된 매개 변수를 메소드에 넘겨줘야 할 때, 여기에 구현된 클래스의 객체를 넘겨주면 된다. > 즉, `Runnable`인터페이스를 매개 변수로 사용하는 메소드가 있으면, 끝에서 두번째에 있는 `Thread`객체를 생성해서 넘겨주면 된다는 것이다. ##### 6) 구현한 모든 인터페이스 목록(All Implemented Interfaces) : 클래스에만 존재함 - 클래스에서 구현~implements~한 모든 인터페이스의 목록을 나열한다. ```java All Implemented Interfaces: Serializable, CharSequence, Comparable<String> ``` 여기에 명시되어 있는 모든 인터페이스의 메소드들은 해당 클래스에서 반드시 구현되어 있을 것이다. ##### 7) 클래스/인터페이스의 선언상태(Class/Interface Declaration) - 클래스의 선언 상태를 볼 수 있다. ```java public final class String extends Object implements Serializable, Comparable<String>, CharSequence ``` > 즉, 클래스가 어떤 접근 제어자를 사용했는지, `final`로 선언된 클래스인지 등을 확인할 수 있다. ##### 8) 클래스 / 인터페이스의 설명(Class / Interface Description) - 클래스에 대한 상세한 설명을 볼 수 있다. - 이 영역에서 제공되는 내용은 클래스의 용도, 클래스사용법, 사용 예 등이 자유롭게 기술되어 있다. ```java /* The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class. Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example: */ String str = "abc"; //is equivalent to: char data[] = {'a', 'b', 'c'}; String str = new String(data); //Here are some more examples of how strings can be used: System.out.println("abc"); String cde = "cde"; System.out.println("abc" + cde); String c = "abc".substring(2,3); String d = cde.substring(1, 2); /* The class String includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version specified by the Character class. 이하 생략 */ //Since: //JDK1.0 //See Also: Object.toString(), StringBuffer, StringBuilder, Charset, Serialized Form ``` > 그런데, 이 설명 부분에서 잊지 않고 봐야 하는 영역이 있다. > 바로 설명의 가장 아래에 있는 `Since`와 `Also`부분이다. - `Since`는 해당 클래스가 `JDK`에 추가된 버전이 명시된다. - `String`클래스는 자바가 처음 만들어지면서부터 생긴 클래스기 때문에 `JDK 1.0`으로 되어 있지만, - `JDK`버전이 올라가면서 많은 클래스들이 추가되었기 때문에 개발할 때에는 이 부분을 꼭 확인해 봐야한다. 예를 들어 `JDK 5`기반의 시스템을 만드는데 `JDK 6`나 `7`의 API문서를 보면서 개발하면, 안된다. > 현재 클래스가 만들어질 때 같이 만든 상수 필드나 메소드에는 `Since`가 없지만, 그 이후의 `JDK`에 포함된 > 상수 필드나 메소드에는 `Since`가 명시되어 있다. > 생소한 메소드가 있다면 , API 문서를 확인하여 언제부터 추가됬는지 확인하는 습관을 가지자 - `See Also`는 그 클래스와 관련되어 있는 모든 클래스나 인터페이스, 메소드 등의 링크가 제공된다. ##### 9) 내부 클래스 종합(Nested Class Summary) - 클래스 안에 `public`하게 선언되어 있는 클래스인 내부 클래스의 목록이 제공된다. - 내부 클래스는 해당 클래스에서 직접 호출하여 사용할 수 있기 때문에 쉽게 사용할 수 있다. > `String`클래스에는 내부 클래스가 없으니, `Thread`클래스의 내부 클래스를 살펴보자 ##### 10) 상수 필드 종합(Field Summary) - 클래스에는 public static으로 선언한 상수 필드가 존재할 수 있다. - 이 값은 바뀌지 않기 때문에 여러모로 많이 사용된다. > `String` 클래스를 살펴보자. ##### 11) 생성자 종합(Constructor Summary) - 클래스에 어떤 생성자들이 선언되어 있는지를 목록으로 제공한다. - 어떤 생성자가 있는지 한눈에 볼 수 있기 때문에 아주 유용하다. - 이 종합 목록에 있는 생성자에 대한 설명이 부족하면, 그 생성자에 걸려 있는 링크를 클릭하면 아래에 있는 생성자 상세 설명으로 이동한다. ##### 11) 메소드 종합(Method Summary) - 클래스에 선언되어 있는 모든 `public` 및 `protected` 메소드에 대한 종합 정보를 제공한다. - 이 내용이 앞으로 개발하면서 가장 많이 봐야 하는 부분이다. - 왜냐하면 어떤 메소드가 있는지 쉽게 확인할 수 있고, 각 메소드의 리턴 타입이 어떤 것이고, 매개변수로 어떤 것을 넘겨줘야 하는지를 알 수 있기 때문이다. > 표를 보면 가장 왼쪽 열에 있는 것은 해당 메소드에 선언되어 있는 `modifier`들이 나열된다. > 만약 메소드의 `modifier`가 `public` 뿐이라면 리턴 타입만 표시된다. > `String`에 나오는 내용들은 모두 리턴 타입뿐이다. > 그런데, 해당 메소드가 `static`메소드라면 `static`이 추가로 명시된다. `public`이 아니라 `protected`라고 선언되어 있는 메소드도 이 API에 표시된다. 왜그럴까? > `protected`는 상속을 받은 클래스에서만 사용할 수 있다. 다시말해서, 해당클래스를 상속받아 자식 클래스를 개발할 때 > 어떤 메소드가 있는지를 알아야 하는데, API에 `protected`메소드에 대한 정보가 없으면 `public`메소드만 `오버라이딩` 할 수 있을 것이다. > 그래서 API문서에는 `protected`로 선언된 메소드도 포함되어야만 한다. ##### 12) 부모 클래스로부터 상속받은 메소드(Methods ingerited from parent) - 여기에는 간단히 부모 클래스로부터 상속받은 메소드들이 나열된다. - 부모클래스가 여러개라면 각 클래스별로 목록을 별도로 제공한다. ```java Methods inherited from class java.lang.Object clone, finalize, getClass, notify, notifyAll, wait, wait, wait ``` ##### 13) 상수 필드 상세 설명(Field Detail) - 클래스에 선언된 상수 필드가 어떤 내용을 제공하는지에 대한 상세한 설명을 나열한다. - 여기에도 Since와 See Also가 제공되는 경우가 있다. ##### 14) 생성자 상세 설명(Constructor Detail) - 생성자를 어떻게 사용하고, 매개변수에 어떤 값들이 제공되어야 하는지, 어떤 리턴 값을 제공하는지, - 이 생성자에서 던지는(throws하는) 예외는 언제 발생하는지를 확인할 수 있다. - 마찬가지로 Since와 See Also가 제공되는 경우가 있다. ##### 15) 메소드 상세 설명(Method Detail) ### Deprecated 라고 표시되어 있는 것은 뭐야? - "디프리케이티드"라고 읽으며, 사전적의미는 "(강력히)반대하다" 라는 말이다. - 이 `Deprecated`는 생성자, 상수 필드, 메소드에 선언되어 있다. > 쉽게 말해서 필요해서 말했는데 나중에 쓰다보니 여러가지 문제를 야기시키거나, 혼동을 가져와서, 혹은 더이상 가치가 없을때 `Deprecated`로 처리되어 버린다. 그럼 왜 없애버리지 않고 `Deprecated`라고 표시하는 걸까? > 그 이유는 호환성~compatibility~때문이다. (버전업을 생각해보자) > 이 외에 여러 발생 가능한 문제들이 많기 때문에 `Deprecated`로 표시하는 것이다. 참고로 이클립스에서는 중간에 줄을그어 `Deprecated`된 메소드등을 표시해준다. 그외에 는 컴파일단에서 알려주거나 가이드를 해준다...참고하자 ### Header와 Footer <file_sep>/java/god_of_java/Vol.1/07. Array/Array.java public class Array { public static void main(String[] args) { Array sample = new Array(); // sample.init(); // sample.primitiveTypes(); // sample.referenceTypes(); // sample.otherInit(); // sample.twoDimensionArray(); // sample.printArrayLength(); if(args.length>0) { for(String arg:args) { System.out.println(arg); } } } public void init() { int[] lottoNumbers = new int[7]; lottoNumbers[0] = 5; lottoNumbers[1] = 12; lottoNumbers[2] = 23; lottoNumbers[3] = 25; lottoNumbers[4] = 38; lottoNumbers[5] = 41; lottoNumbers[6] = 2;a // lottoNumbers[7] = 9; } public void primitiveTypes() { byte[] byteArray = new byte[1]; short[] shortArray = new short[1]; int[] intArray = new int[1]; long[] longArray = new long[1]; float[] floatArray = new float[1]; double[] doubleArray = new double[1]; char[] charArray = new char[1]; boolean[] booleanArray = new boolean[1]; System.out.println("byteArray[0]=" + byteArray[0]); System.out.println("shortArray[0]=" + shortArray[0]); System.out.println("intArray[0]=" + intArray[0]); System.out.println("longArray[0]=" + longArray[0]); System.out.println("floatArray[0]=" + floatArray[0]); System.out.println("doubleArray[0]=" + doubleArray[0]); System.out.println("charArray[0]=[" + charArray[0] + "]"); System.out.println("booleanArray[0]=" + booleanArray[0]); System.out.println("byteArray=" + byteArray); System.out.println("shortArray=" + shortArray); System.out.println("intArray=" + intArray); System.out.println("longArray=" + longArray); System.out.println("floatArray=" + floatArray); System.out.println("doubleArray=" + doubleArray); System.out.println("charArray=" + charArray); System.out.println("booleanArray=" + booleanArray); } public void referenceTypes() { String[] strings = new String[2]; Array[] array = new Array[2]; System.out.println("strings[0]=" + strings[0]); System.out.println("array[0]=" + array[0]); // strings[0]="Please visit www.GodOfJava.com."; // array[0]=new Array(); // System.out.println("strings[0]="+strings[0]); // System.out.println("strings[1]="+strings[1]); // System.out.println("array[0]="+array[0]); // System.out.println("array[1]="+array[1]); } public void otherInit() { int[] lottoNumbers = { 5, 12, 23, 25, 38, 41, 2 }; String[] month = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; } public void twoDimensionArray() { int[][] twoDim; twoDim = new int[2][3]; twoDim[0][0] = 1; twoDim[0][1] = 2; twoDim[0][2] = 3; twoDim[1][0] = 4; twoDim[1][1] = 5; twoDim[1][2] = 6; } static String[] month = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; public void printArrayLength() { int monthLength = month.length; System.out.println("month.length=" + monthLength); int[][] twoDim = { { 1, 2, 3 }, { 4, 5, 6 } }; System.out.println("twoDim.length=" + twoDim.length); System.out.println("twoDim[0].length=" + twoDim[0].length); for (int loop1 = 0; loop1 < 2; loop1++) { for (int loop2 = 0; loop2 < 3; loop2++) { System.out.println("twoDim[" + loop1 + "][" + loop2 + "]=" + twoDim[loop1][loop2]); } } for (int loop1 = 0; loop1 < twoDim.length; loop1++) { for (int loop2 = 0; loop2 < twoDim[loop1].length; loop2++) { System.out.println("twoDim[" + loop1 + "][" + loop2 + "]=" + twoDim[loop1][loop2]); } } int twoDimLength = twoDim.length; for (int loop1 = 0; loop1 < twoDimLength; loop1++) { int twoDim1Length = twoDim[loop1].length; for (int loop2 = 0; loop2 < twoDim1Length; loop2++) { System.out.println("twoDim[" + loop1 + "][" + loop2 + "]=" + twoDim[loop1][loop2]); } } for (int[] tempArray : twoDim) { for (int temp : tempArray) { System.out.println(temp); } } int count1 = 0; for (int[] tempArray : twoDim) { int count2 = 0; for (int temp : tempArray) { System.out.println("twoDim[" + count1 + "][" + count2 + "]=" + temp); count2++; } count1++; } } } <file_sep>/guide/개발 라이브러리 가이드/CI/02 . config 설정.md <style>.blue {color:#2844de;font-size:18px;}.red {color:#dd4814;font-size:18px;}.ex {color:gray;}p.me{padding:10px 8px 10px;line-height:20px;border:1px solid black;}.center{text-align:center;}</style> ## 02 . config 설정 ───────────── 순서 ───────────── 1. autoload.php 2. config.php 3. constants.php 4. database.php 5. routes.php <br /> #### 1. autoload.php 설정 - autoload.php 파일은 라이브러리, 헬퍼, 모델을 `프로그램이 작동할때 자동으로 로드하는 기능`을 지원합니다. 만약 특정리소스가 전체 프로그램에서 작동해야한다면, 자동 로드 기능을 사용하시는 것이 편리합니다. - 다음의 리소스들이 자동으로 로드 가능합니다. - "<b>libraries</b>" 안의 코어클래스들 - "<b>helpers</b>" 폴더안의 헬퍼 클래스들 - "<b>config</b>" 폴더안에 사용자 설정파일들 - "<b>system/language</b>" 안의 언어 파일들 - "<b>models</b>" 폴더안의 모델들 <br /> - bstones 초기 설정 내용 ▼ ────────────────────────────────────────────────── <br /> ##### $autoload['libraries'] &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;<b class="red">$autoload['libraries']</b>에 <span class="blue">database, CI\_PageNavigation, session</span>을 추가한다. <br /> ##### $autoload['helpers'] &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;<b class="red">$autoload['helper']</b>에 <span class="blue">array, bs_html_helper, bs_message_helper</span>을 추가한다. <br /> ##### $autoload['model'] &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;<b class="red">$autoload['model']</b>에 <span class="blue">board_dao</span>을 추가한다. <br /> ────────────────────────────────────────────────────────────────── ``` ※ 추가하는 형태 $autoload['libraries'] = array('database','CI_PageNavigation','session'); ──▶ array(); 안에 클래스이름을 기입하면 된다. ``` #### 2. config.php 설정 - config.php 파일은 환경설정정보를 가져오거나 설정하는 방법을 제공합니다. <br /> - bstones 초기 설정 내용 ▼ ────────────────────────────────────────────────── <br /> ##### $config['base\_url'] &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;<b class="red">$config['base_url'] = </b><span class="blue">((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http");</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;<b class="red">$config['base_url'] .= </b><span class="blue"> "://" . $_SERVER['HTTP_HOST'];</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;<b class="red">$config['base_url'] .= </b><span class="blue"> str_replace(basename($_SERVER['SCRIPT_NAME']), "", $_SERVER['SCRIPT_NAME']);</span> <br /> ##### $config['uri\_protocol'] &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;<b class="red"> $config['uri\_protocol'] = </b><span class="blue"> 'AUTO';</span> <br /> ##### $config['encryption\_key'] &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;<b class="red"> $config['encryption_key'] = </b><span class="blue"> '0b1@)(N9s2$C^t8O*&#3%N7e4s56E!J*';</span> <br /> ##### $config['sess\_']&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;: 세션 관련 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;# pc에 저장되는 쿠키명 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;<b class="red"> $config['sess_cookie_name'] = </b><span class="blue"> '저장할쿠키이름';</span> <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;# 세션 만료 시간 (2 시간입니다(7200 초)), 무한대:0 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;<b class="red"> $config['sess_expiration'] = </b><span class="blue"> '7200';</span> <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;# TRUE일 경우 브라우저를 닫으면 세션이 종료됩니다. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;<b class="red"> $config['sess_expire_on_close'] = </b><span class="blue"> 'TRUE';</span> <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;# 쿠키저장시 암호화 여부 (TRUE로 하시기를 추천합니다) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;<b class="red"> $config['sess_encrypt_cookie'] = </b><span class="blue"> 'TRUE';</span> <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;# DB세션 사용 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;<b class="red"> $config['sess_use_database'] = </b><span class="blue"> 'FALSE';</span> <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;# DB세션을 이용할때 테이블명 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;<b class="red"> $config['sess_table_name'] = </b><span class="blue"> '';</span> <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;# 세션데이터를 읽을때 사용자의 IP주소를 일치시킬지 설정합니다 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;<b class="red"> $config['sess_match_ip'] = </b><span class="blue"> 'TRUE';</span> <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;# 세션 비교시 브라우저까지 매칭할지. 식별강화 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;<b class="red"> $config['sess_match_useragent'] = </b><span class="blue"> 'TRUE';</span> <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;# 세션 업데이트 주기. 5분에 한번씩 갱신합니다. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;<b class="red"> $config['sess_time_to_update'] = </b><span class="blue"> '600';</span> <br /> ─────────────────────────────────────────────────────────────────────────── <br /> #### 3. constants.php 설정 - constants.php 파일에다가 사용할 상수를 설정합니다. - define('상수명',값); <br /> ex. <p class="me" style="line-height:30px">URI가 `www.test.co.kr/`일 때, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b class="red">DOMAIN</b> 값은 <b class="blue">http://test.co.kr</b> 이고 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b class="red">SITE_URL</b>은 <b class="blue">/</b> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b class="red">index.php</b> 값은 <b class="blue">/</b> 이다. <b class="ex">[ → index.php를 없앴으므로. ]</b> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b class="red">ROOT_PATH</b>는 <b class="blue">프로젝트가 위치한 디렉토리 경로</b>를 기입하면 된다. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b class="red">UPLOAD_PATH</b>는 <b class="blue">프로젝트 내에서 uploads파일이 위치한 경로</b>를 기입하면 된다. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b class="red">UPLOAD_SITE_PATH</b>는 <b class="blue">URI에서 사용할 경로</b>를 입력하면 된다. </p> - bstones 초기 설정 내용 ▼ ────────────────────────────────────────────────── #####&nbsp;&nbsp;&nbsp;&nbsp;#### 경로 설정 #### &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;# 도메인 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;<b class="red"> define('DOMAIN', 'http://test.co.kr'); </b> <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;# SITE_URL &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;<b class="red"> define('SITE_URL', '/'); </b> <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;# index.php 포함 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;<b class="red"> define('SITE_URL_INDEX', '/'); </b> <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;# 실제 경로 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;<b class="red"> define('ROOT_PATH', 'C:/xampp/htdocs/프로젝트이름/'); </b> <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;# 업로드 실 경로 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;<b class="red"> define('UPLOAD_PATH', 'C:/xampp/htdocs/프로젝트이름/uploads/'); </b> <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;# 업로드 웹 경로 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;<b class="red"> define('UPLOAD_SITE_PATH', SITE_URL.'uploads/'); </b> <br /> #####&nbsp;&nbsp;&nbsp;&nbsp;#### 메일 발송 관련 #### &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;# 발신 이메일 주소 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;<b class="red"> define('FROM_MAIL', '<EMAIL>'); </b> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;# 보내는 사람 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;<b class="red"> define('FROM_NAME', 'admin'); </b> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;# 메일 제목 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;<b class="red"> define('분류명_SUBJECT', '제목'); </b> ─────────────────────────────────────────────────────────────────────────── <br /> #### 4. database.php 설정 - database.php 파일에 데이터베이스 연결 정보를 입력합니다. <br /> - bstones 초기 설정 내용 ▼ ────────────────────────────────────────────────── <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$db['default'] = array( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'dsn' => '', &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'<b class="red">hostname</b>' => '<b class="blue">localhost</b>', &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'<b class="red">username</b>' => '<b class="blue">root</b>', &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'<b class="red">password</b>' => '<b class="blue">1234</b>', &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'<b class="red">database</b>' => '<b class="blue">db_name</b>', &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'dbdriver' => 'mysqli', &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'dbprefix' => '', &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'pconnect' => FALSE, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'db_debug' => (ENVIRONMENT !== 'production'), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'cache_on' => FALSE, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'cachedir' => '', &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'char_set' => 'utf8', &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'dbcollat' => 'utf8_general_ci', &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'swap_pre' => '', &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'encrypt' => FALSE, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'compress' => FALSE, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'stricton' => FALSE, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'failover' => array(), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'save_queries' => TRUE ); ─────────────────────────────────────────────────────────────────────────── <br /> #### 5. routes.php 설정 - routes.php 파일에 컨트롤러의 기본 설정과 URI 라우팅 설정을 추가 할 수 있습니다. - URI 라우팅 설정 같은 경우 옵션이므로, 아래의 메뉴얼을 참고하여 설정하면 될것입니다. - URI 라우팅 설정 : http://codeigniter-kr.org/user_guide_2.1.0/general/routing.html <br /> - bstones 초기 설정 내용 ▼ ────────────────────────────────────────────────── <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;# 기본 컨트롤러를 설정하는 곳. 쉽게 말해 도메인 주소만 입력했을 시 실행할 기본 컨트롤러를 설정하는 곳입니다. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;<b class="red"> $route['default\_controller'] = </b><b class="blue"> 'index' </b> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;───▶ &nbsp;&nbsp;&nbsp; 도메인 주소만 입력한 경우 , controller에서 index.php파일을 찾아 실행합니다. <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;# 컨트롤러가 존재하지 않을시 보여줄 컨트롤러를 설정하는 곳 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;<b class="red"> $route['404\_override'] = </b><b class="blue"> 'index' </b> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;───▶ &nbsp;&nbsp;&nbsp; 컨트롤러가 존재하지 않을 경우 (주소가 잘못 입력된 경우), 컨트롤러에서 index.php파일을 찾아 실행합니다. <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;# 이 설정은 컨트롤러 그리고 메소드의 uri 문자열에 '-'(하이픈) 이 있을경우 '\_'(언더바) 로 바꾸어줍니다. 이 기능을 사용하기 위해서는 TRUE 로 설정해주면됩니다. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;<b class="red"> // $route['translate\_uri\_dashes'] = FALSE; </b> ───────────────────────────────────────────────────────────────────────────<file_sep>/php/11. $_SERVER 환경변수.md ## 11. php 슈퍼전역변수 **php의 공부**와 **유지보수** 하기에 필수적인 내용이다. 1. \$GLOBALS 2. \$\_SERVER 3. \$\_POST 4. \$\_GET 5. \$\_REQUEST 6. \$\_FILES 8. \$\_COOKIE 9. \$\_SESSION #### 11.01 \$GLOBALS \$GLOBALS는 자동전역 변수 이다. `$GLOBALS["변수이름"]`으로 선언하면 변수가 전역변수가 된다. ── 예제 ── ```php function test() { $foo = "local variable"; echo '$foo in global scope: ' . $GLOBALS["foo"] . "\n"; echo '$foo in current scope: ' . $foo . "\n"; } $foo = "Example content"; test(); ``` ──────── 실행 결과 ──────── ``` $foo in global scope: Example content $foo in current scope: local variable ``` 위의 코드를 본다면 , function밖에 있는 $foo변수를 사용하기 위해 $GLOBALS를 사용하여 전역변수로 만든 것이다. > 기본적으로, > PHP는 함수내부에서 선언한 변수는 함수내부에서만 사용할 수 있고 , 함수 외부에서 선언한 변수는 함수내부에서 사용할 수 없다. > > 그렇기 때문에 함수 외부에서 사용한 변수를 함수 내부에서 사용하려면 `$GLOBALS`를 사용하여 전역변수화한뒤 사용해야 한다. ```php ** ?? 지역변수 전역변수 ?? ** 지역변수 : 블록{ } 내부에 선언된 변수로, 블록 내에서만 사용할 수 있다. ex : function test(){} 내부의 $foo = "local variable" 변수 전역변수 : 전역에서 사용할 수 있다. ex : function test(){} 외부의 $foo = "Example content" 변수 ``` <br> #### 11.02 \$\_SERVER 환경변수 php에서 확인할 수 있는 환경변수 \$\_SERVER값이다. ```php $_SERVER['DOCUMENT_ROOT'] : 사이트 루트의 물리적 경로. ex) /home/ksprg/www $_SERVER['HTTP_ACCEPT_ENCODING'] : 인코딩 방식. ex) gzip, deflate $_SERVER['HTTP_ACCEPT_LANGUAGE'] : 언어. ex) ko $_SERVER['HTTP_USER_AGENT'] : 사이트 접속한 클라이언트(사용자) 프로그램 정보. ex) Mozilla/4.0(compatible; MSIE 7.0; Windows NT 5.1; Q312461; .NET CLR 1.0.3705 $_SERVER['REMOTE_ADDR'] : 사이트 접속한 클라이언트(사용자)의 IP. ex) 192.168.0.100 $_SERVER['HTTP_REFERER'] : 현재 페이지로 오기전의 페이지 주소값. <a> 또는 <form> 태그로 전송시 값이 넘어옴. ex) http://roadrunner.tistory.com/write.php $_SERVER['SCRIPT_FILENAME'] : 실행되고 있는 파일의 전체경로. ex) /home/ksprg/www/index.php $_SERVER['SERVER_NAME'] : 사이트 도메인 ex) roadrunner.tistory.com (virtual host에 지정한 도메인) $_SERVER['HTTP_HOST'] : 사이트 도메인 ex) roadrunner.tistory.com (접속할 때 사용한 도메인) $_SERVER['SERVER_PORT'] : 사이트 포트. ex) 80 $_SERVER['SERVER_SOFTWARE'] : 서버의 소프트웨어 환경 ex) Apache/1.3.23 (Unix) PHP/4.1.2 mod_fastcgi/2.2.10 mod_throttle/3.1.2 mod_ssl/2.8.6 $_SERVER['GATEWAY_INTERFACE'] : CGI 정보. ex) CGI/1.1 $_SERVER['SERVER_PROTOCOL'] : 사용된 서버 프로토콜. ex) HTTP/1.1 $_SERVER['REQUEST_URI'] : 현재페이지의 주소에서 도메인 제외. ex) /index.php?user=ksprg&name=hong $_SERVER['PHP_SELF'] : 현재페이지의 주소에서 도메인과 넘겨지는 값 제외. ex) /test/index.php 파일명만 가져올때 : basename($_SERVER['PHP_SELF']); $_SERVER['APPL_PHYSICAL_PATH'] : 현재페이지의 실제 파일 주소. ex) /home/ksprg/www/ $_SERVER['QUERY_STRING'] : GET 방식의 파일명 뒤에 붙어서 넘어오는 파라미터 값. ex) ?user=ksprg&name=hong ``` <br> #### 10.3 $PHP_SELF , $REQUEST_URI , $QUERY_STRING , $SERVER_NAME , $SERVER_ADMIN , $REMOTE_ADDR 현재 URL : www.servername.co.kr/html/test?id=aa&passwd=bb 라고 가정 $PHP_SELF(정말 많이 사용하는거.) : /html/test 값이 들어있음 $REQUEST_URI : /html/test?id=aa&passwd=bb 값이 들어있음. 인증후에 넘어갈때, 정확치 않는 복수개의 변수값들이 딸려올때, form 으루 넘긴 값에서 hidden 일때 저장된다. `post로 넘긴 값은 안 나타남`. `get`으로 넘겨야 모든 변수들이 나타남 $QUERY_STRING : 넘어온 변수들만 저장 id=aa&passwd=bb 이렇게 $SERVER_NAME : www.servername.co.kr 이 들어있다 $SERVER_ADMIN : admin_id@userhost.co.kr 이 들어있음 $REMOTE_ADDR : 현재의 클라이언트의 ip가 들어 있음. ex : 211.111.xxx.xxx $HTTP_COOKIE : 현재의 쿠키정보저장 ex : email=bellheat; name=aaaa 가끔 씀. 현재의 쿠키 파악해서 strchr등으로 찾아서 원하는 쿠키만을 삭제,추가등.. 많이 씀. $HTTP_COOKIE_VARS["쿠키변수이름"] : 쿠키변수의 값을 저장. 쿠키변수들이 어떤것이 저장 되어있는지 확실히 아는경우 사용 $HTTP_USER_AGENT : 클라이언트 정보저장 $REQUEST_METHOD : 넘어온 변수들의 방식이 GET인지 POST인지 저장 <br> #### 10.5 \$\_POST , \$\_GET , \$\_REQUEST $_POST : post방식으로 전달된 값이 담겨있다. ex : $_POST['name'] $_GET : get 방식으로 전달된 값이 담겨있다. ex : $_GET['name'] $_REQUEST : cookie, post, get의 정보를 담을수 있다. 단, 예를들어 cookie와 post의 이름이 같은 경우 cookie의 정보만 담겨있게된다. ex : $_REQUEST['name'] <br> #### 10.6 \$\_FILES post방식 업로드. 업로드한 파일의 처리 제어에 사용한다. ``` PHP는 넷스케이프 컴포저와 W3C의 Amaya 클라이언트가 사용하는 PUT 방식 파일 업로드도 지원합니다. 자세한 내용은 PUT 방식 지원을 참고하십시오. ``` <br> ##### 파일 업로드 준비 파일 업로드 화면은 다음과 같은 특수한 form으로 만들어진다. ── 파일 업로드 폼 ── ```xml <form enctype="multipart/form-data" action="_URL_" method="post"> <input type="hidden" name="MAX_FILE_SIZE" value="30000" /> 이 파일을 전송합니다: <input name="userfile" type="file" /> <input type="submit" value="파일 전송" /> </form> ``` 위 예제의 "_URL_"을 변경하여 PHP파일을 지시하도록 해야 합니다. MAX_FILE_NAME 히든 필드는 파일 입력 필드 앞에 위치해야 하며, 최대 파일 크기(바이트로 지시)를 값으로 가집니다. 또한, 파일 업로드 폼은 enctype="multipart/form-data"을 가지고 있어야 하며, 그렇지 않으면 파일 업로드는 작동하지 않습니다. <font color=red><b> * 주의</b></font> ``` MAX_FILE_SIZE는 PHP가 확인하기도 하지만, 브라우저에 대한 권고입니다. 이 값을 변경하는건 매우 간단하기에, 크기가 큰 파일을 막기 위해서는 이 기능에 의존해서는 안됩니다. 대신, 최대 크기에 관한 PHP설정은 속일 수 없습니다. 그러나 MAX_FILE_SIZE폼 변수는 사용자가 파일이 너무 크다는 것을 파악하기 위해서 실제 전송을 하는 동안 기다릴 필요를 없애줍니다. ``` 해당 페이지에서는 파일 업로드 이름을 userfile로 표현했습니다. ```php $_FILES['userfile']['name'] : 클라이언트 머신에 존재하는 파일의 원래 이름. $_FILES['userfile']['type'] : 브라우저가 이 정보를 제공할 경우에, 파일의 mime 형식. 예를 들면 "image/gif". $_FILES['userfile']['size'] : 업로드된 파일의 바이트로 표현한 크기. $_FILES['userfile']['tmp_name'] : 서버에 저장된 업로드된 파일의 임시 파일 이름. $_FILES['userfile']['error'] : 파일 업로드에 관련한 에러 코드. ['error']는 PHP 4.2.0에서 추가되었습니다. ``` <br> ##### 업로드 후 업로드된 파일을 받는 PHP 스크립트는 업로드된 파일로 무엇을 할 지 결정하는 로직을 포함하고 있어야 합니다. 예를 들면, $_FILES['userfile']['size'] 변수는 너무 작거나 큰 파일을 처리하는데 이용할 수 있습니다. $_FILES['userfile']['type'] 변수는 형식 기준에 맞지 않는 파일을 처리하는데 이용할 수 있습니다. PHP 4.2.0부터, $_FILES['userfile']['error']를 이용하여 에러 코드에 따라서 처리하게 할 수 있습니다. 어떠한 로직이건 간에, 임시 디렉토리로부터 파일을 지우거나 다른 곳으로 이동해야 합니다. 폼에서 어떠한 파일도 선택하지 않으면, PHP는 $_FILES['userfile']['size']를 0으로, $_FILES['userfile']['tmp_name']을 none으로 반환합니다. >** 요청이 끝날 때, 이동하거나 이름을 변경하지 않은 임시 디렉토리의 파일은 삭제됩니다. ** <br> ##### 에러 메세지 설명 PHP 4.2.0부터, PHP는 파일 배열에 적절한 에러 코드를 반환합니다. 에러 코드는 PHP로 파일을 업로드 했을때 만들어지는 파일 배열의 ['error'] 세그먼트에서 확인할 수 있습니다. 예를 들면, $_FILES['userfile']['error']에서 확인할 수 있을겁니다. ###### UPLOAD_ERR_OK > 값: 0; > 오류 없이 파일 업로드가 성공했습니다. ###### UPLOAD_ERR_INI_SIZE > 값: 1; > 업로드한 파일이 php.ini upload_max_filesize 지시어보다 큽니다. ###### UPLOAD_ERR_FORM_SIZE > 값: 2; > 업로드한 파일이 HTML 폼에서 지정한 MAX_FILE_SIZE 지시어보다 큽니다. ###### UPLOAD_ERR_PARTIAL > 값: 3; > 파일이 일부분만 전송되었습니다. ###### UPLOAD_ERR_NO_FILE > 값: 4; > 파일이 전송되지 않았습니다. 참고: 이들은 PHP 4.3.0에서 PHP 상수가 되었습니다. <br> #### 10.7 \$\_COOKIE 쿠키에 저장된 값을 사용할 수 있게 해줌 ex : 쿠키에 name='Hannes'를 저장해 놓은 뒤 , 사용한다. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;echo 'Hello ' . htmlspecialchars(**$_COOKIE["name"]**) ; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;==> Hello Hannes > htmlspecialchars : 문자열에서 특정한 특수 문자를 HTML 엔티티로 변환한다. 이함수를 사용하면 악성 사용자로 부터 XSS 공격을 방지 할 수 있다. > ex ) > $entity= "<b>b 요소가 삭제 되어 출력화면에 나타난다.</b>"; > echo htmlspecialchars($entity); > > 결과 ) > <b>b 요소가 삭제 되어 출력화면에 나타난다.</b> <br> #### 10.8 \$\_SESSION ##### 세션의 초기화 세션을 사용하려면 우선적으로 session_start() 함수를 사용하여 세션을 초기화 하여야 한다. `bool session_start();` session_start() 함수는 세션을 생성하고 현재의 세션 아이디를 활성화시킨다. 리턴값은 항상 TRUE 이다.. ##### 세션의 등록 $_SESSION["변수명"]을 사용한다. ------- 세션의 등록 예 (session1.php)---------------- <? session_start(); echo("세션이 시작되었습니다."."<br>"); $_SESSION['color'] = 'blue'; $_SESSION['animal'] = 'dog'; $_SESSION['time'] = time(); echo"<a href='session2.php'>session2.php로 이동</a>"; ?> ------------------------------------------------------ 위에 a href 태그를 누르면 session2.php 로 이동하는데 그 이동하는 session2.php 는 아래와 같은 코드 로 작성해서 확인해보자 ------- 세션의 사용 예 (session2.php)---------------- <? session_start(); echo "세션이 시작되었습니다."."<br>"; echo $_SESSION['color']; echo "<br>"; echo $_SESSION['animal']; echo "<br>"; echo date('Y-m-d(H:i:s)', $_SESSION['time']); ?> ------------------------------------------------------ <file_sep>/guide/server/Zeus&Webtob/jeus.MD # JEUS ---------------- ##### 1.개요 버전은 <span style="color : red">`6.0`</span> 윈도우 설치 기준으로 작성하였습니다. --------------- ##### 2.설치 [technet.tmaxsoft.com](http://technet.tmaxsoft.com) 티맥스 사이트에서 다운로드를 진행합니다. 설치받은 파일을 실행하여 인스톨을 진행합니다. - <span style="color : red">설치경로</span> - <span style="color : red">jdk 경로</span> - <span style="color : red"> 관리자 비밀번호</span> 해당 정보를 입력하고 나면 설치가완료됩니다. ---------------- ##### 3.관리자 ``` 계정 : administrator 비밀번호 : 설치시 입력했던 비밀번호 ``` URL : [localhost:9744/webadmin](http://localhost:9744/webadmin) 웹에서 접근가능하며 명령 프롬프트 창에서 jeusadmin 을 입력하여도 접근이 가능합니다. ---------------- ##### 4.실행 명령 프롬프트를 열고 jeus를 입력하면 서버가 실행됩니다. 서버를 실행하면 기본적으로 관리자페이지에 접근이 가능합니다. 아래 사항은 제우스 컨테이너를 실행시키는 방법입니다. 둘중 한가지 방법을 이용하여 컨테이너를 실행시킵니다. - 웹 관리자에 접속하여서<span style="color : red"> 엔진 컨테이너</span> 항목으로 접근하여 내 컴퓨터이름으로 생성된 컨테이너를 실행합니다. - 명령프롬프트 창으로 jeusadmin [내컴퓨터 이름]로 접근하여 <span style="color : red">boot</span>를 입력합니다. 컨테이너가 실행되면 [localhost:8088](localhost:8088)으로 접속하여 jeus를 사용하실수 있습니다. ------------------------------ ##### 5.index.jsp ```css <%=1+1%> ``` index.jsp파일을 아래 경로에 복사한후 jsp작동유무를 확인합니다. ###### C:\TmaxSoft\JEUS6.0\webhome\HKKIM-PC_container1\examples\welcome_war_\_\__ ---------------- ##### 6.이클립스 연동 참고 URL [http://godwings.blog.me/110183985551](http://godwings.blog.me/110183985551) <file_sep>/php/09.1 파일.md ## 파일 ** << 목록 >> ** 1. 파일의 제어 - 파일 복사 - 파일 삭제 - 읽고 쓰기 - 파일을 다루는 과정에서 발생할 수 있는 문제들 2. 디렉토리 제어 - 현재 디렉토리와 디렉토리의 변경 - 디렉토리의 탐색 - 디렉토리의 생성 3. 파일 업로드 --------------- ##### 파일의 제어 ###### 파일 복사 ```php << /file/a.php >> <?php $file = 'readme.txt'; $newfile = 'example.txt.bak'; if(!copy($file, $newfile)) { // copy(원본_파일명,원본파일을_복사한_파일명) echo "failed to copy $file...<br>"; } ?> ``` 위의 코드를 실행한 다음에 디렉토리를 열어보면 파일이 생긴것을 확인할 수 있다. <br> ###### 파일 삭제 ```php << /file/b.php >> <?php unlink('example.txt.bak'); // unlink('제거할_파일명') ?> ``` 위의 코드를 실행한 다음에 디렉토리를 열어보면 파일이 없어진것을 확인할 수 있다. <br> ###### 읽고 쓰기 - file_get_contents(파일명) : 텍스트로 이루어진 파일을 읽어서 문자열을 리턴한다. ```php << c.php >> <?php $file = './readme.txt'; echo file_get_contents($file); ?> ``` - file_put_contents(파일명 , 저장할내용) : 문자열을 파일에 저장한다. ```php << d.php >> <?php $file = './writeme.txt'; file_put_contents($file, 'coding everybody'); ?> ``` - 네트워크를 통해서 데이터 읽어오기 ```php << d.php >> <?php $homepage = file_get_contents('http://www.naver.com'); echo $homepage; ?> ``` file_get_contents()의 매개변수에 사이트주소를 문자열로 전달하면 해당 사이트를 읽어올 수 있다. <br> ###### 권한 * 파일을 읽고 쓸 때 권한의 문제로 오류가 발생할 수 있다. * 다음의 코드는 특정 파일이 `읽을 수 있는 상태인지`를 확인한다. ```php <?php $filename = 'readme.txt'; if(is_readable($filename)){ echo 'The file is readable'; } else { echo 'The file is not readable'; } ?> ``` * 다음의 코드는 특정 파일이 `쓰기가 가능한 상태인지`를 확인한다. ```php <?php $filename = 'writeme.txt'; if(is_writeable($filename)){ echo 'The file is writeable'; } else { echo 'The file is not writeable'; } ?> ``` * 다음의 코드는 특정 `파일이 존재하는지 `확인한다. ```php <?php $filename = 'readme.txt'; if(file_exists($filename)){ echo 'The file is writeable'; } else { echo 'The file is not writeable'; } ?> ``` <file_sep>/게시판만들기/c-cgi-mysql 게시판 만들기/cgi-bin/test/mysqltest.c #include<stdio.h> #include<stdlib.h> #include "/usr/include/mysql/mysql.h" /* gcc -o mysqltest mysqltest.c -I /usr/include/mysql -L /usr/local/lib/mysql -l mysqlclient*/ void main() { MYSQL *conn; MYSQL_RES *res; MYSQL_ROW row; char *server = "dev-smc.com:10022"; char *user = "root"; char *pwd = "<PASSWORD>"; char *database = "main"; conn = mysql_init(NULL); if(!mysql_real_connect(conn, server, user, pwd, database, 0, NULL, 0)){ fprintf(stderr, "%s\n", mysql_error(conn)); exit(1); } if(mysql_query(conn, "show tables")){ fprintf(stderr, "%s\n", mysql_error(conn)); exit(1); } res = mysql_use_result(conn); printf("MySQL의 mysql 데이터베이스 리스트\n"); while((row = mysql_fetch_row(res)) != NULL){ printf("%s\n", row[0]); } mysql_free_result(res); mysql_close(conn); }<file_sep>/php/09.2 파일-디렉토리 제어.md ## 파일 - 디렉토리 제어 ** << 목록 >> ** 1. 디렉토리 제어 - 현재 디렉토리와 디렉토리의 변경 - 디렉토리의 탐색 - 디렉토리의 생성 2. 파일 업로드 --------------- ##### 디렉토리 제어 ###### 현재 디렉토리와 디렉토리의 변경 getcwd()는 현재 디렉토리를 통해서 현재 디렉토리를 알 수 있고, chdir('위치')을 이용해서 디렉토리를 변경할 수 있다. ```php <?php echo getcwd().'<br />'; chdir('../'); echo getcwd().'<br />'; ?> ``` <br> ###### 디렉토리의 탐색 scandir은 디렉토리를 탐색하는 기능이다. **첫번째 인자**는 탐색할 디렉토리의 경로이고, **두번째 인자**는 정렬 방법이다. 아래 예제는 **현재 디렉토리를 탐색하는 방법**과 **탐색된 결과의 정렬 방법을 바꾸는 법**에 대한 예제다. ```php <?php $dir = './'; $file1 = scandir($dir); $file2 = scandir($dir,1); print_r($file1); print_r($file2); ?> ``` <br> ###### 디렉토리의 생성 mkdir은 디렉토리를 생성하는 내장함수다. **첫번째 인자**로 디렉토리의 이름, **두번째 인자**로 디렉토리의 권한을 지정할 수 있다. **세번째 인자**의 값으로 true를 지정하면 첫번째 인자로 주어진 경로가 여러개의 디렉토리로 이루어져 있을 때 해당 디렉토리를 한번에 생성하는 기능을 제공한다. `mkdir("디렉토리이름",디렉토리권한,true);` ```php <?php mkdir("1/2/3/4",0700,true); ?> ``` <file_sep>/java/diskstaion_java_lec/01/Hello.java public class Hello { public static void main(String[] args) { System.out.println("Hello World!"); System.out.print("Hello Java"); System.out.print("The End \n Bye"); } } /* 1. 소스작성 -> Hello.java : 원시코드 (클래스 명과 파일명을 동일하게 작성 ) 2. 컴파일 -> javac 클래스명(Hello) */ /* 자바의 특징 1. 플랫폼 독림성 : JVM(자바가상머신)이 해당 플랫폼마다 제공되어져, 이를 설치하면 어떤 운영체제에서 작성된 자바 파일이든지 동일한 실행을 제공한다. 2.객체 지향언어 : 재사용성, 유연성, 프로그램 생산성 향상 3.멀티 스레드 지원: Thread 는 Process보다 작은 단위로 동시 다발적으로 작업 수행이 가능 4.자동 메모리 관리 - Garbage Collector(쓰레기 수집기) 5.동적인 성능 확장 제공 : Applet 자바 프로그램 종류 1. Application : 독립적인 실행 프로그램 main() 메소드를 가짐 --> Hello.java 콘솔 어플리케이션 윈도우 어플리케이션 - GUI 환경을 가짐 2. Applet : 비독립적 프로그램 웹문서(html)에 포함되어 실행되는 프로그램 main()메소드는 필요 없다 웹브라우저가 가지고 있는 JVM에 의해 실행된다. 동적인 성능 */<file_sep>/javascript/inside_javascript/chapter05 실행 컨텍스트와 클로저/5.js /* *************************************** 5-1 예제 ******************************************* */ console.log("This is global context"); function ExContext1() { console.log("This is ExContext1"); }; function ExContext2() { ExContext1(); console.log("This is ExContext2"); }; ExContext2(); /* *************************************** 5-2 예제 ******************************************* */ function execute(param1, param2) { var a = 1, b = 2; function func() { return a+b; } return param1+param2+func(); } execute(3, 4); /* *************************************** 5-4 예제 ******************************************* */ var var1 = 1; var var2 = 2; function func() { var var1 = 10; var var2 = 20; console.log(var1); // 10 console.log(var2); // 20 } func(); console.log(var1); // 1 console.log(var2); // 2 /* *************************************** 5-5 예제 ******************************************* */ var value = "value1"; function printFunc(func) { var value = "value2"; function printValue() { return value; } console.log(printValue()); } printFunc(); /* *************************************** 5-7 예제 ******************************************* */ function outerFunc(){ var x=10; var innerFunc = function(){console.log(x);} return innerFunc; } var inner = outerFunc(); inner(); //10 /* *************************************** 5-9 예제 ******************************************* */ function HelloFunc(func) { this.greeting = "hello"; } HelloFunc.prototype.call = function(func) { func ? func(this.greeting) : this.func(this.greeting); } var userFunc = function(greeting) { console.log(greeting); } var objHello = new HelloFunc(); objHello.func = userFunc; objHello.call(); /* *************************************** 5-10 예제 ******************************************* */ function HelloFunc(func) { this.greeting = "hello"; } HelloFunc.prototype.call = function(func) { func ? func(this.greeting) : this.func(this.greeting); } var userFunc = function(greeting) { console.log(greeting); } var objHello = new HelloFunc(); objHello.func = userFunc; objHello.call(); function saySomething(obj, methodName, name) { return (function(greeting) { return obj[methodName](greeting, name); }); } function newObj(obj, name) { obj.func = saySomething(this, "who", (name || "everyone")); return obj; } newObj.prototype.who = function(greeting, name) { console.log(greeting + " " + (name || "everyone") ); } var obj1 = new newObj(objHello, "zzoon"); obj1.call(); /* *************************************** 5-11 예제 ******************************************* */ var buffAr = [ 'I am ', '', '. I live in ', '', '. I\'am ', '', ' years old.', ]; function getCompletedStr(name, city, age){ buffAr[1] = name; buffAr[3] = city; buffAr[5] = age; return buffAr.join(''); } var str = getCompletedStr('zzoon', 'seoul', 16); console.log(str); /* *************************************** 5-12 예제 ******************************************* */ var getCompletedStr = (function(){ var buffAr = [ 'I am ', '', '. I live in ', '', '. I\'am ', '', ' years old.', ]; return (function(name, city, age) { buffAr[1] = name; buffAr[3] = city; buffAr[5] = age; return buffAr.join(''); }); })(); var str = getCompletedStr('zzoon', 'seoul', 16); console.log(str); /* *************************************** 5-13 예제 ******************************************* */ function callLater(obj, a, b) { return (function(){ obj["sum"] = a + b; console.log(obj["sum"]); }); } var sumObj = { sum : 0 } var func = callLater(sumObj, 1, 2); setTimeout(func, 500); /* *************************************** 5-14 예제 ******************************************* */ function outerFunc(argNum){ var num = argNum; return function(x){ num += x; console.log('num: '+num); } } var exam=outerFunc(40); exam(5); exam(-10); /* *************************************** 5-15 예제 ******************************************* */ function func(){ var x = 1; return { func1 : function(){ console.log(++x); }, func2 : function(){ console.log(-x); } }; }; var exam = func(); exam.func1(); exam.func2(); /* *************************************** 5-16 예제 ******************************************* */ function countSeconds(howMany) { for (var i = 1; i <= howMany; i++) { setTimeout(function () { console.log(i); }, i * 1000); } }; countSeconds(3); <file_sep>/java/god_of_java/Vol.1/10. 자바는 상속이라는 것이 있어요/Parent2.java public class Parent2{ public Parent2(){ } public Parent2(String name){ } public void printName(){ System.out.println("printName() - Parent"); } }<file_sep>/java/god_of_java/Vol.2/02. String/UseStringMethods.java public class UseStringMethods { public static void main(String[] args) { UseStringMethods usm=new UseStringMethods(); String text="The String class represents character strings."; String fstr="string"; char c='s'; String fstr2="ss"; //usm.printWords(text); //usm.findString(text, fstr); //usm.findAnyCaseString(text, fstr); //usm.countChar(text, c); usm.printContainWords(text, fstr2); } public void printWords(String str){ String str2[]=str.split(" "); for(String tmp:str2){ System.out.println(tmp); } } public void findString(String str, String findStr){ System.out.println("string is appeared at "+str.indexOf(findStr)); } public void findAnyCaseString(String str, String findStr){ String str2 = str.toLowerCase(); System.out.println("string is appeared at "+str2.indexOf(findStr)); } public void countChar(String str,char c){ int charCount=0; char[] strArray=str.toCharArray(); for(char tmp:strArray){ if(tmp=='s'){ charCount++; } } System.out.println("char 's' count is "+charCount); } public void printContainWords(String str, String findStr){ String[] strArray=str.split(" "); for(String tmp:strArray ){ if(tmp.contains(findStr)){ System.out.print(tmp+" contains ss"); } } } } <file_sep>/java/god_of_java/Vol.1/01. 자바란/README.md 1. java의 메소드 기본 구현방식 ```java 접근제어자 리턴타입 메소드이름(매개변수){ } ``` 2. 메소드는 단독으로 존재 할 수 없고 항상 클래스 안에 포함되어야 한다. 3. 하나의 클래스 안에는 여러개의 메소드가 존재할 수 있다. 4. void 라는 리턴타입은 돌려주는 값이 없다는것을 의미한다.(동영상 강의의 '선물'을 생각해보자) 5. 클래스는 상태(state)와 행동(behavior)이 있어야만 한다. -> 행동은 메소드를 의미하며 상태는 그 클래스의 특성을 결정짓은 것을 말한다. -> 그러면 상태는 어떻게 정할까? 6. 클래스의 상태는 - 클래스 안에, - 메소드 밖에 정의한다. 7. 클래스에 상태와 행동이 꼭 있어야 하는건 아니다. ```java public class DoorLockManager{ // 변수는 클래스의 상태(state)에 해당한다. String currentPassword; public boolean checkPassword(String password) { } public void setPassword(String password) { } public void resetPassword() { } } ``` > 정수 num1과 num2를 더하는 add()라는 메소드를 작성해보자. ```java public class Calurator { int num1 = 10; int num2 = 20; public void sum(int num1, int num2) { System.out.println(num1+num2); } } ``` > 정리 1. 클래스가 뭔가요? -> 자바의 가장작은 단위로 상태와 행동이 있어야 한다 => 클래스는 각각의 객체들을 나타내는 청사진과 같다. 즉 하나의 객체를 나타내기 위한 자바에서 가장 작은 단위로 볼 수 있으며, 상태와 행동을 갖고 있는 것을 의미한다. 2. 메소드가 뭔가요? -> 단독으로 존재할수 없고 클래스에 포함되어야 한다 클래스의 행동에 해당한다. => 메소드는 클래스의 행동을 제공하는 역할을 수행한다. 3. 메소드의 매개변수는 어디에 적어주나요? ->메소드의 선언 후 소괄호 안 =>메소드의 매개변수는 메소드 선언시 사용하는 소괄호 안에 타입과 변수명 순으로 선언한다. 두개 이상의 매개변수가 있을 경우에는 콤마로 구분한다. 4. 메소드 이름앞에 꼭 적어줘야 하는 것은 뭐죠? -> 접근제어자 혹은 리턴타입 => 리턴 타입 5. 클래스가 갖고 있어야 한다고 한 두가지가 뭐죠? -> 상태와 행동 6. 메소드에서 결과를 돌려주려면 어떤 예약어를 사용해야 하나요? -> return > 어떤 값을 받아서 계산을 하고 결과를 리턴하는 것이 바로 메소드이다. > 단 매개변수가 없거나 리턴값이 없는 메소드도 가능하다. > > 즉 클래스라는 집안에 여러개의 메소드라는 기계가 들어있다고 생각 <file_sep>/게시판만들기/c-cgi-mysql 게시판 만들기/cgi-bin/bak_160329/list.c #include "common.h" // gcc -o list.cgi list.c cgic.c -I/usr/include/mysql -L/usr/local/lib/mysql -lmysqlclient // gcc -o mysqltest mysqltest.c -I /usr/include/mysql -L /usr/local/lib/mysql -lmysqlclient int cgiMain(void) { /* 헤더 속성 최상단에 위치 - 헤더위에 print 문등이 있으면 500 error 발생 */ printf("%s%c%c\n","Content-Type:text/html;charset=utf-8",13,10); // 페이징 관련 변수 int page, limit; int page_num = 1; int list = 10; int block_page_num_list = 5; int block, block_start_page, block_end_page, total_page, total_block; int total_count = 0; int query_stat; // form 데이터 cgiFormString("title", title, MAX_LEN); cgiFormString("name", name, MAX_LEN); cgiFormString("content", content, MAX_LEN); cgiFormInteger("page", &page, 1); cgiFormString("search", search, MAX_LEN); cgiFormString("search_type", search_type, MAX_LEN); // DB연결 및 연결실패시 에러 console 출력 함수 mysqlDbConn(); // 검색값이 있을경우 if( strcheck(search_type) ){ mysqlDbSelect(search_type, search); } // 검색값이 없을경우 else{ mysqlDbSelect(search_type, search); } /* * 페이징 시작 */ res = mysql_store_result(connection); // 쿼리 문 실행 후 결과값을 가져온다. 쿼리 결과의 모든 ROW들를 한번에 얻어 온다 total_count = mysql_num_rows(res); // 최종 쿼리 row 갯수 if(&page == NULL){ page_num = 1; }else{ page_num = page; } block = ceil((float)page_num/block_page_num_list); if(block < 1){ block = 1; } block_start_page = ( (block - 1) * block_page_num_list )+1; block_end_page = (block_start_page + block_page_num_list) -1; total_page = ceil( (float)total_count/list ); total_block = ceil( (float)total_page/block_page_num_list ); if( block_end_page > total_page ){ block_end_page = total_page; } limit = (page -1)*list; // Limit 적용한 최종 쿼리(페이징 데이터용) if( strcheck(search_type) ){ mysqlDbSelectLimit( search_type, search, limit, list ); sprintf(search_query, "&search_type=%s&search=%s", search_type, search); } else{ mysqlDbSelectLimit( search_type, search, limit, list ); sprintf(search_query, ""); } /* * 페이징 끝 */ final_res = mysql_store_result(connection); // 최종 출력되는 쿼리 ( mysql 의 limit 가 반영된 쿼리 ) /* // 페이징 변수 확인 printf("page : %d - 1,2,3 등의 실제 페이지 번호 <br>", page); printf("page_num : %d - 페이지번호를 페이징에서 사용하기위해 구분한 변수 <br>", page_num); printf("block_page_num_list : %d - 한블록에 노출될<br>", block_page_num_list); printf("block : %d <br>", block); printf("block_start_page : %d <br>", block_start_page); printf("block_end_page : %d <br>", block_end_page); printf("total_count : %d <br>", total_count); printf("total_page : %d <br>", total_page); printf("limit : %d <br>", limit); printf("list : %d <br>", list); */ printf("<!DOCTYPE html>\n\n"); printf("<HTML lang=\"ko\">\n\n"); printf("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n\n"); printf("<HEAD> \n\n"); printf(" <TITLE>CGI - board</TITLE>\n\n"); //printf(" <link href=\"https://maxcdn.bootstrapcdn.com/bootswatch/3.3.6/paper/bootstrap.min.css\" rel=\"stylesheet\" > \n"); printf(" <link href=\"https://maxcdn.bootstrapcdn.com/bootswatch/3.3.6/slate/bootstrap.min.css\" rel=\"stylesheet\" > \n"); printf(" <script src=\"https://code.jquery.com/jquery-1.12.1.min.js\"></script> \n\n"); printf(" <script > \n"); printf(" function goWrite(){ \n"); printf(" location.href='write.cgi'; \n"); printf(" }; \n"); printf(" $(function(){ \n"); printf(" var form = document.search_frm; \n"); printf(" form.submit \n"); printf(" }); \n"); printf(" </script> \n"); printf("<HEAD>\n\n"); printf("<BODY>\n"); printf("<div class='container' style='margin-bottom: 20px;'>\n"); printf(" <div class='row' >\n"); printf(" <h2 class='pull-left '>CGI - board</h2>\n"); printf(" <form class='form-inline pull-right' style='margin-top:30px;' name='search_frm' id='search_frm' > \n"); printf(" <div class='form-group '> \n"); printf(" <select class='form-control' name='search_type' id='search_type'>"); printf(" <option value=''>선택</option>"); printf(" <option value='title'>제목</option>"); printf(" <option value='name'>작성자</option>"); printf(" </select> \n"); printf(" <input type='text' name='search' class='form-control' id='search' value='%s'> \n", search); printf(" </div> \n"); printf(" <button class='btn btn-default' >검색</button> \n"); printf(" </form> \n"); printf(" <table width='600' class='table table-bordered'>\n"); printf(" <tr>"); printf(" <th class='col-xs-1 active' style='text-align:center' >번호</th>"); printf(" <th class='col-xs-10 active'>제목</th>"); printf(" <th class='col-xs-1 active'>작성자</th>"); printf(" </tr>\n"); // 데이터 뿌리기 while( (row = mysql_fetch_row(final_res)) != NULL ){ listData(final_res); } printf(" </table> \n"); printf("<nav style='text-align:center; height:24px' > \n"); printf(" <ul class='pagination' > \n"); // 페이징 pagingData(page_num, list, block, block_start_page, block_end_page, total_block, total_page); printf(" </ul> \n"); printf("</nav> \n"); printf(" <button class='btn btn-default pull-right' onclick='goWrite();' >글쓰기</button> \n"); printf(" </div>\n"); printf("</div>\n"); printf("</body>\n\n</html>"); mysql_free_result(final_res); // mysql_store_result() 함수에 의해 할당된 메모리를 해제한다 - 최종 출력되는 쿼리 해제 mysql_free_result(res); // 페이징 데이터를 위한 쿼리 해제 ( limit 가 없는 쿼리 ) mysql_close(connection); // mysql 접속해제 } <file_sep>/javascript/inside_javascript/chapter03 데이터 타입과 연산자/README.md ## 3. 자바스크립트 데이터 타입과 연산자 #### 자바스크립트의 데이터 타입은 다음과 같이 나뉜다 - 기본타입 1) 숫자 2) 문자열 3) 불린값 4) undefined 5) null - 참조타입 1) 객체 - 배열 - 함수 - 정규표현식 ```javascript // 숫자 타입 var intNum = 10; var floatNum = 0.1; // 문자열 타입 var singleQuoteStr = 'single quote strign'; var doubleQuoteStr = "double quote string"; var singleChar = 'a'; // 불린 타입 var boolVar = true; // undefined 타입 var emptyVar; // null 타입 var nullVar = null; console.log( typeof inNum, typeof floatNum, typeof singleQuoteStr, typeof doubleQuoteStr, typeof boolVar, typeof nullVar, typeof emptyVar ); ``` > 결과값 `number number string string boolean obejct nullVar emptyVar` 1. 숫자 - 하나의 숫자형만 존재한다. - 모든 숫자를 64비트 부동 소수점 형태로 저장하기 때문이다. - 정수형이 따로 없고, 모든 숫자를 실수로 처리하므로 나눗셈 연산을 할 때는 주의해야 한다. > 예) 다음 계산을 C언어에서 할경우 5/2 는 소수부분을 버린 2가 출력된다 반면 `js`에서는 2.5가 출력 ```javascript var num = 5/2; console.log(num); //출력값 2.5 console.log(Math.floor(num)); //출력값 2 ``` 2. 문자열 - 문자열은 작은따옴표나 큰 따옴표로 생성한다. - `java`의 char 타입과 같이 문자 하나만을 별도로 나타내는 데이터 타입은 존재하지 않는다. - 문자 배열처럼 인덱스를 이용해서 접근할 수 있다. - 한번생성된 문자열은 읽기만 가능하지 수정은 불가능하다. 3. null과 undefined - 두 타입 모두 '값이 비어있음'을 나타낸다. - 자바스크립트 환경 내에서 기본적으로 값이 할당되지 않는 변수는 `undefined`타입이며, 변수자체의 값 또한 `undefined`이다. > **undefined는 타입이자, 값을 나타낸다** - null 타입 변수의 경우는 개발자가 명시적으로 값이 비어있음을 나타내는 데 사용한다. - null타입 변수인지를 확인할 때 typeof 연산자를 사용하면 안되고, 일치연산자(==)를 사용해서 변수의 값을 직접 확인해야 한다. --- ##### 자바스크립트 참조 타입(객체 타입) - 기본타입을 제외한 모든 값은 객체다. 따라서 배열, 함수, 정규표현식 등도 모두 결국 자바스크립트 객체로 표현된다. - 객체는 단순히 '이름(key):값(value)' 형태의 프로퍼티들을 저장하는 컨테이너 - 컴퓨터 과학 분야에서 `해시`라는 자료구조와 상당히 유사하다. - 기본타입은 하나의 값만을 가지는 데 비해, 참조타입인 객체는 여러 개의 프로퍼티들을 포함할 수 있으며, 이러한 객체의 프로퍼티는 기본 타입의 값을 포함하거나, 다른 객체를 가리 킬 수도 있다 - 객체의 프로퍼티는 기본 타입의 값을 포함하거나, 다른 객체를 가리킬 수도 있다. - 객체의 프로퍼티는 함수로 포함할 수 있으며, 자바스크립트에서는 이러한 프로퍼티를 **메서드**라고 부른다. ##### 객체생성 - 자바는 클래스르를 정의하고, 클래스의 인스턴스를 생성하는 과정에서 객체가 만들어지지만, 자바스크립트에서는 클래스라는 개념이 없고, 객체 리터럴이나 생성자 함수 등 별도의 생성방식이 존재한다. - 객체를 생성하는 방법은 크게 세가지가 있다. 1. 기본제공 Object()객체 생성자 함수를 이용하는 방법 2. 객체 리터럴을 이용하는 방법 3. 생성자 함수를 이용하는 방법 1) Object() 생성자 함수 이용방법 ```javascript // Object()를 이용해서 foo 빈 객체 생성 var foo = new Object(); // foo 객체 프로퍼티 생성 foo.name = 'foo'; foo.age = 30; foo.gender = 'male'; console.log(typeof foo); //출력값 object console.log(foo); //출력값 { name:'foo', age:30, gender:'male'} ``` 2) 객체 리터럴 방식 이용 - 객체를 생성하는 표기법을 의미한다. - 중괄호{}를 이용해서 객체를 생성한다. {}안에 아무것도 적지 않은 경우는 빈객체가 생성 - 중괄호{}안에 "프로퍼티 이름:프로퍼티값" 형태로 표기하면, 해당 프로퍼티가 추가된 객체를 생성 - 프로퍼티 이름은 문자열이나 숫자가 올 수 있고 프로퍼티값은 어떤 표현식이든 가능하다. - 이 값이 함수일 경우 이러한 프로퍼티를 메서드라고 부른다. ```javascript //객체 리터럴 방식으로 foo 객체 생성 var foo = { name:'foo', age:30, gender:'male' }; console.log(typeof foo); //출력값 object console.log(foo); //출력값 { name:'foo', age:30, gender:'male'} ``` 3) 생성자 함수 이용 - `js`에서는 함수를 통해서도 객체를 생성할 수 있다. - 이 내용은 4장 참조(다음장) --- ##### 객체 프로퍼티 읽기/쓰기/갱신 - 객체는 새로운 값을 가진 프로퍼티를 생성하고, 생성된 프로퍼티에 접근해서 해당 값을 읽거나 또는 원하는 값으로 프로퍼티의 값을 갱신할 수 있다. 객체의 프로퍼티에 접근하는 방법은 다음과 같이 두가지이다. - 대괄호[] 표기법 - 마침표 . 표기법 ```javascript // 객체 리터럴 방식을 통한 foo 객체 생성 var foo = { name : 'foo', major : 'computer science' }; // 객체 프로퍼티 읽기 console.log(foo.name); // foo console.log(foo['name']); // foo console.log(foo.nickname); // undefined // 객체 프로퍼티 갱신 foo.major = 'electronics engineering'; console.log(foo.major); //electronics engineering console.log(foo['major']); //electronics engineering // 객체 프로퍼티 동적 생성 /* 객체의 프로퍼티에 값을 할당할 때, 프로퍼티가 이미 있을경우는 값이 갱신되고, 없을경우는 프로퍼티가 동적으로 생성된 후 값이 할당된다. */ foo.age = 30; console.log(foo.age); // 30 // 대괄호 표기법만을 사용해야 할 경우 /* 접근하려는 프로퍼티가 표현식이거나 예약어일 경우 대괄호를 이용해서 접근해야 한다. 아래 full-name에서 "-"는 연산자이므로 */ foo['full-name'] = 'foo bar'; console.log(foo['full-name']); // foo bar console.log(foo.full-name); // NaN console.log(foo.full); // undefined console.log(name); // undefined ``` > Nan(Not a Number)값 > 수치 연산을 해서 정상적인 값을 얻지 못할 때 출력되는 값 > 가령 `1-'hello'` 라는 연산의 결과는 NaN이다 ##### for in 문과 객체 프로퍼티 출력 > `for in` 문을 사용하면 객체에 포함된 모든 프로퍼티에 대해 루프를 수행할 수 있다 ```javascript // 객체 리터럴을 통한 foo 객체 생성 var foo = { name: 'foo', age: 30, major: 'computer science' }; // for in문을 이용한 객체 프로퍼티 출력 var prop; for (prop in foo) { console.log(prop, foo[prop]); } ``` --- ##### 객체 프로퍼티 삭제 > 객체의 프로퍼티를 delete 연산자를 이용해 즉시 삭제할 수 있다. > 주의점은 객체의 프로퍼티를 삭제할 뿐, 객체 자체를 삭제하지는 못한다는 점이다. ##### 참조타입의 특성 - 기본타입을 제외한 모든값은 객체로, 배열이나 함수 또한 객체로 취급된다. 또한 이런 타입을 참조타입이라 부른다 (java와 크게 다르지 않은 형태) - 이것은 객체의 모든 연산이 실제 값이 아닌 참조값으로 처리되기 때문이다. ```javasciprt // 객체를 리터럴 방식으로 생성 //여기서 objA 변수는 객체 자체를 저장하고 있는 것이 아니라 생성된 객체를 가리키는 참조값을 저장하고 있다. var objA = { val : 40 }; // objB에도 objA와 같은 객체의 참조값이 저장된다. var objB = objA; console.log(objA.val); // 40 console.log(objB.val); // 40 objB.val = 50; console.log(objA.val); // 50 console.log(objB.val); ``` > objA 객체는 참조 변수 objA가 가리키고 있는 객체 동등연산자(==)를 사용하여 두 객체를 비교할 때도 객체의 프로퍼티값이 아닌 참조값을 비교한다는것에 주의 ```javascript var a = 100; var b = 100; var objA = { value: 100 }; var objB = { value: 100 }; var objC = objB; console.log(a == b); // true console.log(objA == objB); // false console.log(objB == objC); // true ``` > objA와 objB는 같은형태의 프로퍼티값을 가지고 있지만 동등연산자 로 출력해보면 false가 출력된다 > 이는 기본타입의 경우는 값 자체를 비교해서 일치 여부를 판단하지만, 객체와 같은 참조 타입의 경우는 > 참조값이 같아야 true가 되기 때문이다. ##### 참조에 의한 함수 호출 방식 > 기본 타입과 참조 타입의 경우는 함수 호출 방식도 다르다. > 기본 타입의 경우는 값에 의한 호출(call byy value)방식으로 동작한다. > 즉, 함수를 호출할 때 인자로 기본 타입의 값을 넘길 경우, 호출된 함수의 매개변수로 **복사된 값**이 전달된다. > 때문에 함수내부에서 매개변수를 이용해 값을 변경해도, 실제로 호출된 변수의 값이 변경되지는 않는다 이에반해 > 참조 타입의 경우 함수를 호출할 때 참조에 의한 호출(call by reference)방식으로 동작한다. > 즉, 함수 호출시 객체를 전달할 경우, 객체의 프로퍼티값이 함수의 매개변수로 복사되지 않고, 인자로 넘긴 객체의 참조값이 그대로 함수 내부로 전달된다. > 때문에 함수 내부에서 참조값을 이용해서 인자로 넘긴 실제 객체의 값을 변경할 수 있는것이다. ```javascript var a = 100; var objA = { value: 100 }; function changeArg(num, obj) { num = 200; obj.value = 200; console.log(num); console.log(obj); } changeArg(a, objA); console.log(a); console.log(objA); ``` 결과값 > 200 > {value:200} > 100 > {value:200} ##### 프로토타입 > 자바크스립트의 **모든 객체는 자신의 부모 역할을 하는 객체와 연결되어 있다** 이것은 마치 객체지향의 상속 개념과 같이 부모 객체의 프로퍼티를 마치 자신의 것처럼 쓸 수 있는 것 같은 특징이 있다. > 자바스크립트에서는 이러한 부모 객체를 **프로토타입 객체(짧게는 프로토타입)** 이라 부른다 ```javascript var foo = { name: 'foo', age: 30 }; console.log(foo.toString()); console.dir(foo); ``` > 모든 객체의 프로토타입은 자바스크립트의 룰에 따라 객체를 생성할 때 결정된다. (자세한 내용은 4.5장참조) > 객체 리터럴 방식으로 생성된 객체의 경우 `Object.prototype`객체가 프로토 타입 객체가 된다는 것만 기억하자 > 객체를 생성할 때 결정된 프로토타입 객체는 임의의 다른 객체로 변경하는 것도 가능하다. > 즉, 부모 객체를 동적으로 바꿀 수도 있는 것이다. > 자바스크립트에서는 이러한 특징을 활용해서 객체 상속 등의 기능을 구현한다.(자세한 사항은 6장 참조) ##### 배열 - 배열은 자바스크립트 객체의 특별한 형태다. - 즉, C나 자바의 배열과 같은 기능을 하는 객체지만, 이들과는 다르게 굳이 크기를 지정하지 않아도 되며, - 어떤 위치에 어느 타입의 데이터를 저장하더라도 에러가 발생하지 않는다. #####배열리터럴 > **배열리터럴**은 자바스크립트에서 새로운 배열을 만드는 데 사용하는 표기법이다. > 객체 리터럴이 {} 중괄호 표기법이었다면, 배열 리터럴은 []대괄호를 사용한다. ```javascript // 배열 리터럴을 통한 5개 원소를 가진 배열 생성 var colorArr = ['orange', 'yellow', 'blue', 'green', 'red']; console.log(colorArr[0]); // orange console.log(colorArr[1]); // yellow console.log(colorArr[4]); // red ``` > 당연히 위와같이 인덱스로 접근가능하다~ ##### 배열의 요소생성 - 객체가 동적으로 프로퍼티를 추가할 수 있듯이, 배열도 동적으로 배열 원소를 추가할 수 있디. - 값을 순차적으로 넣을 필요 없이 아무 인덱스 위치에나 동적으로 추가할 수 있다. ```javascript // 빈 배열 var emptyArr = []; console.log(emptyArr[0]); // undefined // 배열 요소 동적 생성 emptyArr[0] = 100; emptyArr[3] = 'eight' emptyArr[7] = true; console.log(emptyArr); // [100, undefined × 2, "eight", undefined × 3, true] console.log(emptyArr.length); // 8 ``` > 출력값을 확인해보면 배열의 크기를 현재 인덱스중 가장 큰 값을 기준으로 정함을 알 수 있다. > 또한 값이 할당되지 않는 인덱스요소는 `undefined`값을 기본으로 가진다. ##### 배열의 length 프로퍼티 > `length`프로퍼티는 배열의 원소 개수를 나타내지만, 실제로 배열에 존재하는 원소 개수와 일치하는 것은 아니다. > 하지만 실제 메모리는 length 크기처럼 할당되지는 않는다 `ex) arr[100]` 에 값이 3개밖에 없을경우 > `undefined` 부분은 실제로 메모리가 할당되지 않는다는 말이다. ```javascript var arr = [0, 1, 2]; console.log(arr.length); // 3 arr.length = 5; console.log(arr); // [0, 1, 2] arr.length = 2; console.log(arr); // [0, 1] console.log(arr[2]); // undefined ``` > 위소스를 보면 명시적으로 배열의 `length`값을 변경 가능하고 또한 생성된 인덱스보다 작을경우 그에 해당하는 값이 삭제되는걸 알 수 있다. ##### 배열 표준 메서드와 length 프로퍼티 - `js`는 배열에서 사용 가능한 다양한 표준 메서드를 제공한다. - 이러한 배열 메소드는 `length 프로퍼티`를 기반으로 동작하고 있다. - 예를 들면 `push()`메소드 (인수로 넘어온 항목을 배열의 끝에 추가하는 표준 배열 메소드다.) ##### 배열과 객체 > `js`에서는 배열 역시 객체다. 하지만 배열은 일반객체와는 약간 차이가 있다. - 객체는 length 프로퍼티가 존재하지 않는다. - 객체는 배열이 아니므로 `push()`와 같은 **표준 배열 메소드**를 사용할 수 없다 - 객체 리터럴 방식으로 생성한 객체의 경우 `Object.prototype` 객체가 프로토타입이고 - 배열의 경우 `Array.prototype` 객체가 부모객체인 프로토타입이 된다. > 배열과객체의 프로토타입 순서도는 아래와 같다 ##### Obejct.prototype <- Array.prototype <- 배열 > 즉 배열에서는 Object.prototype의 표준메소드들도 사용할 수 있다는 뜻 ```javascript var emptyArray = []; // 배열 리터럴을 통한 빈 배열 생성 var emptyObj = {}; // 객체 리터럴을 통한 빈 객체 생성 console.dir(emptyArray.__proto__); // 배열의 프로토타입(Array.prototype) 출력 console.dir(emptyObj.__proto__); // 객체의 프로토타입(Object.prototype) 출력 ``` > 크롬브라우져 개발자도구로 확인해보자 ```javascript // 배열 생성 var arr = ['zero', 'one', 'two']; console.log(arr.length); // 3 // 프로퍼티 동적 추가 arr.color = 'blue'; arr.name = 'number_array'; console.log(arr.length); // 3 // 배열 원소 추가 arr[3] = 'red'; console.log(arr.length); // 4 // 배열 객체 출력 console.dir(arr); ``` > 배열의 length 프로퍼티는 배열 원소의 가장 큰 인덱스가 변했을 경우만 변경된다. > 아래는 위 코드의 출력 결과다. > 보기와 같이 배열도 객체처럼 "key:value" 형태가 가능함을 알수있고 `length` 로 알수 있는 값은 인덱스값만을 뽑아낼수 있다는걸 알 수 있다. ```javascript 0: "zero" 1: "one" 2: "two" 3: "red" color: "blue" length: 4 name: "number_array" ``` ##### 배열의 프로퍼티 열거 - 배열역시 객체 처럼 `for in`문으로 프로퍼티를 열거할 수 있지만 불필요한 프로퍼티가 출력될 수 있으므로 되도록 `for` 문을 사용하는 것이 좋다. ```javascript // 배열 생성 var arr = ['zero', 'one', 'two']; // 프로퍼티 동적 추가 arr.color = 'blue'; arr.name = 'number_array'; // 배열 원소 추가 arr[3] = 'red'; for (var prop in arr) { console.log(prop, arr[prop]); } for (var i=0; i<arr.length; i++) { console.log(i, arr[i]); } ``` > 아래는 결과 값이다. 보기와 같이 `for in`문으로 돌릴경우 color와 name 프로퍼티까지 출력된걸 알 수 있다. ``` 0 zero 1 one 2 two 3 red color blue name number_array ---------------------- 0 "zero" 1 "one" 2 "two" 3 "red" ``` ##### 배열요소삭제 - 배열도 객체이므로, 배열오소나 프로퍼티를 삭제하는 데 delecte 연산자를 사용할 수 있다. ```javascript var arr = ['zero', 'one', 'two', 'three']; delete arr[2]; console.log(arr); // ["zero", "one", undefined × 1 , "three"] console.log(arr.length); // 4 ``` > 주의할점은 위와 같이 arr[2] 배열의 요소를 삭제할 경우 undefined가 할당되지만 lengh값은 변하지 않는 것을 확인할 수 있다. > 즉, delete 연산자는 해당 요소의 값을 undefined로 설정할 뿐 원소 자체를 삭제하지는 않는다. > 때문에 보통 배열에서 요소들을 완전히 삭제할 경우 자바스크립트에서는 `splice()`배열 메소드를 사용한다. ```javascript splice(start,deleteCount,item...) ``` - start - 배열에서 시작 위치 - deleteCount - start에서 지정한 시작 위치에서 삭제할 요소의 수 - item - 삭제할 위치에 추가할 요소 > 아래는 사용예제다 ```javascript var arr = ['zero', 'one', 'two', 'three']; arr.splice(2, 1); console.log(arr); // ["zero", "one", "three"] console.log(arr.length); // 3 ``` ##### Array()생성자 함수 - 배열은 일반적으로 배열 리터럴로 생성하지만, 배열 리터럴도 결국 자바스크립트 기본 제공 `Array() 생성자함수`로 배열을 생성하는 과정을 단순화시킨 것이다. - 생성자 함수로 배열과 같은 객체를 생성할 때는 반드시 new 연산자를 같이 써야 한다는 것을 기억하자. > Array() 생성자 함수 호출시 인자 개수에 따라 동작이 다르므로 아래 코드를 참고하자 ```javascript var foo = new Array(3); console.log(foo); // [undefined, undefined, undefined] console.log(foo.length); // 3 var bar = new Array(1, 2, 3); console.log(bar); // [1, 2, 3] console.log(bar.length); // 3 ``` ##### 유사 배열 객체 - `length`프로퍼티를 가진 객체를 `유사 배열 객체(array-like object)`라고 부른다. - 아래 예제에서 객체 obj는 length 프로퍼티가 있으므로 유사 배열 객체다. - 유사배열 객체의 가장 큰 특징은 객체임에도 불구하고, 자바스크립트의 표준 배열 메소드를 사용하는 게 가능하다는 것이다. ```javascript var arr = ['bar']; var obj = { name : 'foo', length : 1 }; arr.push('baz'); console.log(arr); // ['bar', 'baz'] obj.push('baz'); // Uncaught TypeError: Object #<Object> has no method 'push' ``` > 위 코드를 살펴보면, 배열 arr은 push()표준 배열 메소드를 활용해서 원소를 추가하는 것이 가능한 반면에, > 유사 배열 객체 obj는 당연히 배열이 아니므로 바로 push()메소드를 호출할 경우 에러가 발생한다. 하지만 유사배열객체의 경우 추후 배울 `apply()`메소드를 사용하면 객체지만 표준 배열 베소드를 활용하는 것이 가능하다. 이 부분에 대한 더욱 자세한 내용은 **4.4.2.4 call과 apply메소드를 이용한 명시적인 this바인딩**에서 살펴볼 것이니 지금은 '유사 배열 객체도 배열 메소드를 사용하는 것이 가능하다'정도만 숙지하도록 하자. > 참고로 `arguments 객체`나 `jQuery 객체`가 바로 유사 배열 객체 형태로 되어있다 ```javascript var arr = ['bar']; var obj = { name : 'foo', length : 1}; arr.push('baz'); console.log(arr); // [‘bar’, ‘baz’] Array.prototype.push.apply(obj, ['baz']); console.log(obj); // { '1': 'baz', name: 'foo', length: 2 } ``` #### 연산자 - `+`연산자는 두 연산자가 모두 숫자일 경우에만 더하기 연산이 수행되고, 나머지는 문자열 연결 연산이 이뤄진다. ##### typeonf 연산자 - `typeof` 연산자는 피연산자의 타입을 문자열 형태로 리턴한다. - 여기서 `null` 과 배열이 `object`라는점. 함수는 `function`이라는 점에 유의해야 한다. ##### 동등(==)연산자와 일치(===)연산자 - 자바스크립트에서는 두 값이 동일한지를 확인하는 데, 두 연산자를 모두 사용할 수 있다. - 두 연산자의 차이는 `==`연산자는 비교하려는 피연산자의 타입이 다를 경우에 타입 변환을 거친 다음 비교한다. - `===`연산자는 피연산자의 타입이 다를 경우에 타입을 변경하지 않고 비교한다. ```javascript console.log(1 == '1'); // true console.log(1 === '1'); // false ``` ##### !! 연산자 - `!!`의 역할은 피연산자를 불린 값으로 변화하는 것이다. ```javascript console.log(!!0); // false console.log(!!1); // true console.log(!!'string'); // true console.log(!!''); console.log(!!true); console.log(!!false); console.log(!!null); console.log(!!undefined); // false console.log(!!{}); // true console.log(!![1,2,3]); // true ``` <file_sep>/javascript/Ninja_javascript/2 Test & Debuging/README.md ##2. 테스팅과 디버깅 갖추기 - 자바스크립트 디버깅 도구 - 테스트 생성 기법 - 테스트 스위트 작성 방법 - 비동기 작업을 테스트 하는 방법 ### 2.1 코드 디버깅 자바스크립트 코드 디버그 도구들 - FireBug - IE Developer Tools - Opera Dragonfly - WebKit Developer Tools 자바스크립트 디버깅에는 `로깅`과 `중단점(breakpoint)`라는 두 가지 중요한 방법이 있다. 로깅은 흔이 하는 브라우저내에서 지원하는 콘솔창을 생각하면 되고, 중단점은 말그대로 개발자도구에서 javascript debug시 찍는 breakpoint로 생각하면 된다. ### 2.1.1 로깅 ```javascript function log() { try { console.log.apply(console, arguments); //#1 } catch(e) { //#2 try { opera.postError.apply(opera, arguments); //#3 } catch(e){ alert(Array.prototype.join.call( arguments, " ")); //#4 } } } ``` ### 2.1.2 BreakPoint 코드의 특정한 위치에서 스크립트의 실행을 중지시키고, 브라우저를 멈춘다라는 로깅보다 좀더 명확한 장점을 가지고 있다. 이는 실행이 중지된 시점에서, 모든 상태를 좀 더 여유롭게 조사할 수 있게 해준다. 중지된 상태에서 조사할 수 있는 상태는 중지한 위치에서 접근할 수 있는 모든 변수들과 콘텍스트, 유효범위를 포함한다. <file_sep>/Front-End/gulp/README.md ## Gulp ### Gulp 기본 템플릿 > 아래 링크를 클릭해 기본 템플릿 파일을 `Clone` 합니다. [Gulp 프로젝트](http://ds.bstones.co.kr:9000/bstones/CodingConvention/code/master/Gulp-project#Gulp-project) --- ### Node.js & NPM에 의존하는 프로젝트 > 프로젝트는 Node.js 환경에서 작동합니다. Node.js가 설치되어 있지 않다면 아래 링크로 이동하여 설치 파일을 내려 받습니다. [Node.js 다운로드](http://nodejs.org/download/) --- ### NPM 모듈 설치 > 내려 받은 ZIP 파일 압축을 푼 후, Git Bash에서 압축을 푼 디렉토리로 <code>cd</code> 명령으로 이동합니다. 그리고 NPM 설치 명령을 실행하여 <strong>프로젝트의 의존 개발모듈(devDependencies)</strong>을 내려 받습니다. `의존개발모듈` 은 `package.json` 을 참조하여 자동 설치됩니다. ```bash $ npm install ``` --- #### Gulp 프로젝트 명령어 기본 Gulp 프로젝트는 아래 명령어를 지원합니다. * `gulp` 또는 `gulp default` - 기본 업무로 clean > styles > scripts > watch 순으로 실행됩니다. * `gulp watch` - 파일의 변경 내용을 지속적으로 관찰하여 관련 업무를 수행합니다. * `gulp clean` - 생성된 파일을 제거합니다. * `gulp styles` - CSS 문법 검사, 병합, 압축 과정을 수행하는 업무입니다. * `gulp scripts` - Javascript 문법 검사, 병합, 압축 과정을 수행하는 업무입니다. --- #### 프로젝트 의존 개발 모듈 목록 > 책에서 다룬 실습 예제는 아래 NPM 모듈에 의존합니다. 버전 앞에 붙는 기호(^)는 "해당 버전에 호환"되는 집합을 의미합니다. 예를 들어 "^1.1.1"은 1.1.0-0 버전보다 크고 2.0.0-0 버전 보다 작다는 의미로 해석됩니다. [참고 URL: 시멘틱 버전 관리(Semantic Versioning)](http://semver.org/lang/ko/) * __del__ - 버전 ^1.1.0 * __gulp__ - 버전 ^3.8.10 * __gulp-concat__ - 버전 ^2.4.2 * __gulp-concat-css__ - 버전 ^1.1.1 * __gulp-csslint__ - 버전 ^0.1.5 * __gulp-if__ - 버전 ^1.2.5 * __gulp-jshint__ - 버전 ^1.9.0 * __gulp-rename__ - 버전 ^1.2.0 * __gulp-uglify__ - 버전 ^1.0.2 * __gulp-uglifycss__ - 버전 ^1.0.4 * __jshint-stylish__ - 버전 ^1.0.0 <file_sep>/java/god_of_java/Vol.2/08. 그 다음으로 많이 쓰는 애들은 자바 유틸/README.md ## 8장. 그 다음으로 많이 쓰는 애들은 자바 유틸 ### java.lang 다음으로 많이 사용되는 java.util 패키지 java.util 패키지의 유용한 클래스 목록 - Date 와 Calendar - Collections - Arrays - StringTokenizer - Properties - Random - Formatter ### 날짜를 처리하기 위한 Date와 Calendar JDK 1.0 버전에서는 날짜를 처리하기 위해서 Date클래스를 사용했다. 하지만 JDK1.1버전 부터는 Calendar 클래스를 사용하여 날짜 처리 작업을 하도록 변경되었다. 그런고로, Date 클래스에는 deprecated된 메소드들이 존재한다. ##### Date클래스 > Data 클래스에는 두개의 생성자만 사용가능하다 (나머지는 deprecated) - Date() : 객체가 생성된 시간을 갖는 Date 객체 생성 - Date(long date) : 매개 변수로 넘어온 long 타입 시간을 갖는 Date 객체 생성 여기서 long값으로 나타내는 시간은 UTC 시간으로 `System.currentTimeMillis()`메소드 호출시 리턴되는 시간과 동일하다. > 생성자와 마찬가지로 Date클래스의 메소드들은 deprecated 된 것들이 매우 많다. > 사용가능한 메소드들 중에서 쓸 만한 것은 getTime() 메소드와 setTime()메소드다 ```java import java.util.Date; public class DateCalendarSample { public static void main(String[] args) { DateCalendarSample sample=new DateCalendarSample(); sample.checkDate(); } public void checkDate(){ Date date=new Date(); System.out.println(date); long time=date.getTime(); System.out.println(time); date.setTime(0); System.out.println(date); } } ``` > 출력결과 ```java Wed Nov 18 15:56:27 KST 2015 1447829787901 Thu Jan 01 09:00:00 KST 1970 ``` > 지정한 날짜사이의 시간등을 계산하는 것은 쉽지 않다(Date로했을시) 그래서 제공되는 것이 Calendar 클래스다 ##### Calendar 클래스 > Calendar 클래스의 선언 ```java public abstract class Calendar extends Object implements Serializable, Cloneable, Comparable<Calendar> ``` > `abstract` 클래스인데다가, `Calendar` 클래스는 생성자들이 `protected`로 선언되어 있어 얼핏보기엔 이 클래스를 확장하여 구현하지 않으면, > 생성자로 객체를 만들어낼 수 없어 보인다. > 그렇다고 객체를 생성할수 없는 것은 아니다. > 왜냐하면 Calendar클래스는 `getInstance()`라는 메소드가 존재하기 때문이다. `getInstance()`의 생성자는 아래처럼 네개가 존재한다. - getInstance() - getInstance(Locale aLocale) - getInstance(TimeZone zone) - getInstance(TimeZone zone, Locale aLocale) Locale 클래스는 지역에 대한 정보를 담는다. 자바를 설치할 때 OS에 있는 지역 정보를 확인하여 JVM의 설정에 저장된다. Timezone 클래스는 시간대를 나타내고 처리하기 위해 사용된다. 우리나라는 GMT기준으로 `+9` 시간이기 때문에 앞서 Date 클래스 예제에서도 `+09:00`으로 표시되는걸 확인했었다. TimeZone 클래스도 마찬가지로 abstract 클래스이므로 이 클래스를 편하게 사용하려면 같은 패키지에 선언된 `SimpleTimeZone`클래스를 사용하면 된다. 또한, getInstance() 메소드외에 `GregorianCalendar` 라는 클래스도 있다. ```java public void makeCalendarObject(){ Calendar cal=Calendar.getInstance(); Calendar greCal=new GregorianCalendar(); } ``` > 이 중에서 편한방법을 사용하면 되는데, 일반적으로는 greCal 객체처럼 사용하는것을 권장한다. 그러면 Calendar 클래스는 어떻게 사용하면 될까? Calendar 클래스를 제대로 사용하기 위해서는 API문서에 있는 상수들을 눈여겨 봐야만 한다. 예제를 통해 확인해보자 ```java public void useCalendar(){ // Calendar 클래스의 객체를 Calendar 클래스에 선언된 getInstance()메소드로 생성했다. Calendar cal=Calendar.getInstance(); // Calendar 클래스의 객체를 GregorianCalendar 클래스의 생성자를 사용하여 만들었다. Calendar greCal=new GregorianCalendar(); System.out.println(cal); System.out.println(greCal); int year=greCal.get(Calendar.YEAR); int month=greCal.get(Calendar.MONTH); //자바의 캘린더에서 월은 1월부터 시작하지 않고, 0부터 시작한다. int date=greCal.get(Calendar.DAY_OF_MONTH); System.out.println(year+"/"+month+"/"+date); // getDisplayName()메소드를 호출하면 문자열로 표시 가능한 값이 리턴된다(월 요일등...) String monthKorea=greCal.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.KOREA); String monthUS=greCal.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.US); System.out.println(monthKorea); System.out.println(monthUS); } ``` > 출력결과 ```java java.util.GregorianCalendar[time=1447830799240,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Seoul",offset=32400000,dstSavings=0,useDaylight=false,transitions=22,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2015,MONTH=10,WEEK_OF_YEAR=47,WEEK_OF_MONTH=3,DAY_OF_MONTH=18,DAY_OF_YEAR=322,DAY_OF_WEEK=4,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=4,HOUR_OF_DAY=16,MINUTE=13,SECOND=19,MILLISECOND=240,ZONE_OFFSET=32400000,DST_OFFSET=0] java.util.GregorianCalendar[time=1447830799240,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Seoul",offset=32400000,dstSavings=0,useDaylight=false,transitions=22,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2015,MONTH=10,WEEK_OF_YEAR=47,WEEK_OF_MONTH=3,DAY_OF_MONTH=18,DAY_OF_YEAR=322,DAY_OF_WEEK=4,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=4,HOUR_OF_DAY=16,MINUTE=13,SECOND=19,MILLISECOND=240,ZONE_OFFSET=32400000,DST_OFFSET=0] 2015/10/18 11월 Nov ``` > 첫번째 출력결과를 보면, Calendar의 getInstance() 메소드를 호출하면 Calendar 클래스의 객체가 리턴되는 것이 아니라 > GregorianCalendar 객체가 리턴되는 것을 볼 수 있다. > 여기서 중요한점은 현재 코드의 작성시점은 `2015/11/18`일인데 출력결과는 `2015/10/18`로 나온것이다. > `Nov`의 경우는 `Calendar.SHORT`로 지정했기 때문이며 `LONG`으로 지정한다면 `December`처럼 전체이름이 나온다. ##### 추가적으로 add()메소드와 roll()메소드를 알아보자 ```java public void addAndRoll(Calendar calendar, int amount) { calendar.add(Calendar.DATE, amount); printCalendar(calendar); calendar.add(Calendar.DATE, -amount); printCalendar(calendar); calendar.roll(Calendar.DATE, amount); printCalendar(calendar); } public void printCalendar(Calendar calendar) { int year = calendar.get(Calendar.YEAR); String month = calendar.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.KOREA); int date = calendar.get(Calendar.DATE); System.out.println(year + "/" + month + "/" + date); } ``` > roll()메소드는 상위값을 변경하지 않는다. 그러므로 날짜만 10일을 더하고 월은 바꾸지 않는다. ### 컬렉션 객체들의 도우미 Collections 앞서 배운 Collection 관련 클래스들을 위한 Collections라는 도우미 클래스가 있다. 이 클래스에 있는 메소드들은 모두 static 메소드다. (즉 객체를 생성할 필요가 없다.) 매우 많은 메소드들이 제공되고 있지만 그중에서 눈여겨 봐야 하는 것은 바로 `synchronize`로 시작하는 메소드들이다. > 기본적으로 대부분의 Collection 클래스들은 쓰레드에 안전하게 구현되어 있지 않다. > 따라서, 쓰레드에 안전하지 않은 Collection 클래스의 객체를 생성할 때에는 `synchronize`로 시작하는 메소드를 사용하면 > 쓰레드에 안전한 클래스가 된다. > 예를 들어 ArrayList는 다음과 같이 객체를 생성해주면 쓰레드에 안전한 클래스가 된다. ```java List list = Collections.synchronizedList(new ArrayList(...)); ``` 그렇다고, 무조건 쓰레드에 안전하게 작성하려고 이렇게 변경해버리면 성능에 좋지 않다. 딸사ㅓ, 곡 필요할 때에만 사용할 것을 권장한다. ### 배열을 쉽게 처리해주는 Arrays Arrays 클래스도 Collections 클래스처럼 도우미 클래스이며, 배열을 쉽게 처리할 수 있도록 도움을 주는 클래스다. 이 중에서 가장 많이 사용되는 sort()메소드와 fill() 메소드만 예제를 통해서 알아보자 ```java import java.util.Arrays; public class ArraySample { public static void main(String[] args) { ArraySample sample=new ArraySample(); sample.checkSort(); } public void checkSort(){ int[] values=new int[]{1,5,3,2,4,7,6,10,8,9}; Arrays.sort(values); String stringValues=Arrays.toString(values); System.out.println(stringValues); } } ``` > 이렇게 숫자들이 순서 없이 나열되어 있을 때 어렵게 구현하고 계산할 필요 없이 static으로 선언되어 있는 `Arrays`클래스의 > `sort()`메소드를 호출하면, 해당 배열의 값이 순서대로 나열된다. > 추가로 `Arrays.toString()`메소드를 호출하면, 자동으로 배열의 각 항목이 순서대로 나열되어 있는 문자열을 받을 수 있다. > 이 메소드를 안쓴다면 for나 while등으로 루프돌려서 값을 봐야했을 것이다. 이번에는 특정 값으로 데이터를 채우는 `fill()`메소드를 살펴보자. ```java public void checkFill(){ int[] emptyArray=new int[10]; Arrays.fill(emptyArray, 1); Arrays.fill(emptyArray,0,5,9); String stringValues=Arrays.toString(emptyArray); System.out.println(stringValues); } ``` > fill()메소드는 두 가지를 제공한다. > - 모든 위치에 있는 값들을 하나의 값으로 변경하는 것과 > - 특정 범위의 값들을 하나의 값으로 변경하는 것이 있다. > 출력결과는 각각 아래와 같다 ```java [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] [9, 9, 9, 9, 9, 1, 1, 1, 1, 1] ``` ### 임의의 값을 생성하기 위한 Random 난수를 생성한느 Random 클래스는 두개의 생성자가 있다. - Random() - Random(Long long) 이중 매개변수로 long을 받는 생성자는 씨드~seed~값을 지정하는 것이다. 씨드값을 지정하게 되면, 해당 Random에서 만들어 낸 값들은 임의의 숫자가 나오긴 하지만, 그 결과는 항상 동일하게 된다. ```java import java.util.Random; public class RandomSample { public static void main(String[] args) { RandomSample sample=new RandomSample(); int randomCount=10; sample.generateRandomNumbers(randomCount); } public void generateRandomNumbers(int randomCount){ Random random=new Random(); for (int loop = 0; loop < randomCount; loop++) { System.out.print(random.nextInt(100)+","); } } } ``` ### 문자열을 자르기 위한 StringTokenizer "This is a basic java book" 이 문자열을 단어 단위로 분리하려고 하면 어떻게 해야 할까? > 여러가지 방법이 있지만 일반적인 방법은 `StringTokenizer`를 사용하는 것이다. > 이 클래스는 어떤 문자열이 일정한 기호(구분자)로 분리되어 있을 때 적합한 클래스다. 다만 String클래스의 Split()메소드보다 이 클래스를 사용하는 것은 권장하지 않는다. 허나 사용된 코드를 볼 수도 있으니 알아는 두자. ```java import java.util.StringTokenizer; public class StringTokenizerSample { public static void main(String[] args) { StringTokenizerSample sample = new StringTokenizerSample(); String data = "This is a basic java book"; sample.parseString(data); } public void parseString(String data) { StringTokenizer st = new StringTokenizer(data); // StringTokenizer st=new StringTokenizer(data,"a"); while (st.hasMoreElements()) { String tempData = st.nextToken(); System.out.println("[" + tempData + "]"); } } public void parseStringWithSplit(String data) { String[] splitString = data.split("\\s"); for (String tempData : splitString) { System.out.println("[" + tempData + "]"); } } } ``` > 그럼 더 나은 방법이라고했던 String클래스의 split()메소드를 살펴보자 ```java public void parseStringWithSplit(String data) { String[] splitString = data.split("\\s"); for (String tempData : splitString) { System.out.println("[" + tempData + "]"); } } ``` ### java.math 패키지의 BigDecimal java.util에 선언되어있진 않고, java.math에 선언되어있다. - 특히 돈 계산과 같은 프로그램을 작성할때 사용된다 ```java import java.math.BigDecimal; public class BigDecimalSample { public static void main(String[] args) { BigDecimalSample sample = new BigDecimalSample(); //sample.normalDoubleCalc(); sample.bigDecimalCalc(); } public void normalDoubleCalc() { double value = 1.0; for (int loop = 0; loop < 10; loop++) { value += 0.1; System.out.println(value); } } public void bigDecimalCalc() { BigDecimal value = new BigDecimal("1.0"); BigDecimal value2 = new BigDecimal(1.0); BigDecimal addValue = new BigDecimal("0.1"); BigDecimal addValue2 = new BigDecimal(0.1); for (int loop = 0; loop < 10; loop++) { value = value.add(addValue); System.out.println(value.toString()); } for(int loop=0;loop<10;loop++) { value2 = value2.add(addValue2); System.out.println("value2="+value2); } } } ``` > 주의 할점은 문자열을 매개변수로 넘겨줘야 한다. ( 그렇지 않으면 0.1이 아닌 근사치로 계산되기때문에..) --- ### 정리해 봅시다 1. `Date`, `Calendar` 클래스가 대표적인 날짜와 시간을 처리하는 클래스이다. 하지만, `Date 클래스`는 Deprecated된 메소드들이 많아서, `Calendar클래스`를 사용할 것을 권장한다. 그리고, `Calendar클래스`는 abstract 클래스이기 때문에 보통 `GregorianCalendar 클래스`를 사용한다. 2. Date 클래스의 Deprecated되지 않은 생성자는 Date()와 Date(long date) 두개 뿐이다. 3. getTime() 메소드는 long 형태로 관리되는 시간을 처리하므로, getTime(0)은 1970년 1월 1일 00시를 의미한다. 한국은 GMT + 9 이기 때문에 09시로 출력될 수 있다. 4. Calendar 클래스는 new를 사용하여 객체를 생성하지 않고, getInstance() 메소드를 사용하여 객체를 생성한다. 5. Calendar 클래스에서 1월은 0이고, 12월은 11을 사용한다. 6. Collection 클래스들의 내용을 쉽게 처리하기 위해서 Collections 클래스가 존재한다. 7. Collections 클래스의 synchronized로 시작하는 메소드들은 Thread에 안전하지 않은 Collection들을 쉽게 안전하게 바꿀 수 있도록 해준다. 8. Arrays 클래스도 Collections 클래스처럼 배열과 관련된 객체들을 쉽게 처리할 수 있도록 만들어졌다. 9. 자바의 Random 클래스는 임의의 수를 생성하기 위해서 사용한다. 10. StringTokenizer 클래스의 hasMoreElements() 메소드는 생성된 데이터가 더 존재하는지를 확인하기 위한 메소드로, boolean 타입의 결과를 리턴한다. 11. StringTokenizer 클래스의 nextToken() 메소드는 생성된 데이터에서 다음 데이터를 꺼낼 때 사용한다. 12. String클래스의 split() 메소드의 기능은 StringTokenizer와 비슷한 역할을 수행한다. 13. Properties 클래스의 load() 메소드는 저장되어 있는 Properties 파일의 내용을 읽어 Properties 객체에 담아준다. 14. 숫자의 정확한 계산을 위한 BigDecimal 클래스는 java.math 패키지에 선언되어 있다. 15. BigDecimal 클래스에서 값을 더할 때에는 add() 메소드를, 뺄 때에는 subtract() 메소드를, 곱하기는 multiply(), 나누기는 subtract() 메소드를 각각 사용한다. <file_sep>/java/god_of_java/Vol.1/05. 계산/README.md ## 계산을 하고 싶어요 ### 1.연산자라는게 뭐지? - PHP와 달리 명시해줘야될 부분이 있나? - jsp로 게시판 페이징 구현시 ceil이 원하는대로 써지지않아 애먹었던 기억을 떠올려보자 ```java public class Operators { //중간생략 public void multiplicative() { int intValue1=5; int intValue2=10; int result=intValue1 * intValue2; System.out.println(result); // 아래 계산내용은 0.5가아닌 0으로 출력... 왜? result= intvalue1/intValue2; // 아래 (float)처럼 명시해줘야 원하는 값인 0.5가 출력된다. float result2=(float)intValue1/intValue2; System.out.println(result2); } } ``` > 자바는 계산하는 두 값이 정수형이더라도, 결과가 소수형이면 알아서 소수형으로 결과가 나오지 않는다 > 그래서 float으로 변환한 것이다. 더 자세한 사항은 이장의 마지막절의 형변환을 참조 == != 등의 등가비교연산자의 경우 같은 종류끼리 사용가능하다. - char == int - double == int - boolean == boolean 연산자 | 사용가능한 타입 ------ | ------ ==, != | 모든 기본 자료형과 참조 자료형 -> 즉 모든 타입 >,<,>=,<= | boolean을 제외한 기본자료형 그 외 연산자들은 그냥 생략...필요하면 책찾아보자 ###2.? : 연산자( 삼항연산자 )... ```java public class Operators { //중간 생략 public boolean doBlindDate(int point) { boolean doBlindDateFlag = false; doBlindDateFlag = (point>=80) ? true : false; System.out.println(point+" : " + doBlindDateFlag); return doBlindDateFlag; } } ``` > 위 삼항연잔자를 표기해보면 아래와 같다 `변수 = (boolean조건식) ? true일때값 : false일때값;` ###3. 캐스팅 - 형 변환은 **casting**이라고 한다. - 자바의 형변환은 기본자료형과 참조 자료형 모두 괄호로 묶어주면 된다. - 단 불린값의 경우는 형변환이 되지 않는다...당연하게도 - 기본자료형 -> 참조자료형, 혹은 그반대의 경우는 형변환이 불가능하다. <file_sep>/javascript/inside_javascript/chapter04 함수와 프로토타입 체이닝/README.md ## 4. 함수와 프로토타입 체이닝 > 자바스크립트에서 가장 중요한 개념 1순위는 단연 `함수`다. (`C`의 포인터...) 살펴볼 주요 내용 - 함수 생성 - 함수 객체 - 다양한 함수 형태 - 함수 호출과 this - 프로토타입과 프로토타입 체이닝 ### 4.1 함수 정의 > 자바스크립트에서 함수를 생성하는 방법은 3가지가 있다. > 각각의 방식에 따라 함수 동작이 미묘하게 차이가 난다. - 함수 선언문(function statement) - 함수 표현식(function expression) - Function() 생성자 함수 #### 4.1.1 함수 리터럴 - 자바스크립트에서는 함수도 일반 객체처럼 값으로 취급된다. - 때문에, 함수리터럴을 이용해 함수를 생성할 수 있다. - 함수 선언문이나 함수 표현식 방법 모두 이런 함수 리터럴 방식으로 함수를 생성한다. ```javascript function 함수명(x,y){ return x+y; } ``` function 키워드 - 자바스크립트 함수 리터럴은 function 키워드로 시작한다. 함수명 - 함수 몸체의 내부 코드에서 자신을 재귀적으로 호출하거나 또는 자바스크립트 디버거가 해당 함수를 구분하는 식별자로 사용 - 함수명은 선택사항이다. (함수명이 없는 함수를 익명 함수라 한다.) 매개변수리스트 - 매개변수 타입을 기술하지 않는다. #### 4.1.2 함수 선언문 방식으로 함수 생성하기 - 함수 선언문 방식으로 정의된 함수의 경우는 **반드시 함수명이 정의되어 있어야 한다.** ```javascript //add() 함수선언문 function add(x,y){ return x+y; } console.log(add(3,4)); // 출력값 7 ``` #### 4.1.3 함수 표현식 방식으로 함수 생성하기 - 자바스크립트에서는 함수도 하나의 값처럼 취급된다(이러한 특징이 있으므로 자바스크립트의 함수는 일급객체라고 한다.) - 따라서, 함수도 숫자나 문자열처럼 변수에 할당하는 것이 가능하다. > 이런 방식으로 함수 리터럴로 하나의 함수를 만들고, > 여기서 생성된 함수를 변수에 할당하여 함수를 생성하는 것을 **함수표현식**이라한다. 함수표현식은 함수 선언문 문법과 거의 유사하지만 유일한 차이점은 ###### **함수 이름이 선택사항이며, 보통 사용하지 않는다는 것이다.** ```javascript // add() 함수 표현식 var add = function(x,y){ return x+y; } var plus = add; console.log(add(3,4)); // 출력값 7 console.log(plus(3,4)); // 출력값 11 ``` > `add`변수는 함수 리터럴로 생성한 함수를 참조하는 변수이지, **함수이름**이 아니라는것에 주의 하자 > `add`와 같이 함수가 할당된 변수를 **함수변수**라 한다. > `add`는 함수의 참조값을 가지므로 또 다른 변수 `plus`에도 그 값을 그대로 할당할 수가 있다. > 이것이 바로 **익명 함수를 이용한 함수표현식(익명 함수 표현식)**이다. > 참고로 함수 이름이 포함된 함수 표현식을 **기명 함수 표현식**이라 한다. ```javascript var add = function sum(x, y) { return x + y; }; console.log(add(3,4)); // 7 console.log(sum(3,4)); // Uncaught ReferenceError: sum is not defined 에러 발생 ``` > 위 코드를 보면 `sum()`함수를 정의하고, 이 함수를 `add`함수 변수에 할당했다. > 주의할점은 `add()`함수 호출은 결과값이 성공적으로 리턴되는 반면, > `sum()`함수 호출의 경우 에러가 발생한다는 점이다. > 이것은 **함수 표현식에서 사용된 함수 이름이 외부 코드에서 접근 불가능하기 때문이다.** 실제로 함수 표현식에서 사용된 함수 이름은 정의된 함수 내부에서 해당 함수를 재귀적으로 호출하거나, 디버거 등에서 함수를 구분할 때 사용된다. 따라서 함수 이름으로 사용된 `sum`으로 함수 외부에서 해당 함수를 호출할때 `sum()`함수가 정의되어 있지 않다는 에러가 발생한다. > `함수 표현식`에서는 함수 이름이 선택사항이지만, 이러한 함수 이름을 이용하면 함수 코드 내부에서 함수이름으로 함수의 재귀적인 호출 처리가 가능하다. 무슨말인지 당최 설명만 보고는 알수가 없으니 아래 예제 코드를 통해 살펴보자 ```javascript var factorialVar = function factorial(n) { if(n <= 1) { return 1; } return n * factorial(n-1); }; console.log(factorialVar(3)); // 6 console.log(factorial(3)); // Uncaught ReferenceError: factorial is not defined 에러 발생 ``` 위 코드는 함수 표현식 방식으로 팩토리얽밧을 재귀적으로 구현한 함수다.......- - 함수 외부에서는 함수 변수 `factorialVar`로 함수를 호출했으며, 함수 내부에서 이뤄지는 재귀 호출은 `factorial()`함수 이름으로 처리한다는 것을 알 수 있다. - 함수명 `factorial()`으로 함수 외부에서 해당 함수를 호출하지 못해 에러가 발생한다. function statement와 function expression에서의 세미콜론 **일반적으로 자바스크립트 코드를 작성할 때 함수 선언문 방식으로 선언된 함수의 경우는 함수 끝에 세미콜론(;)을 붙이지 않지만, 함수 표현식 방식의 경우는 세미콜론(;)을 붙이는 것을 권장한다.** 자바스크립트는 `C`와 같이 세미콜론 사용을 강제하지는 않는다(인터프리터가 자동으로 세미콜론을 삽입함) > **결론은 함수표현식 방식에서는 세미콜론을 반드시 사용하자** (자세한 사항은 p.77 참조) #### 4.1.4 Function()생성자 함수를 통한 함수 생성하기 - 자바스크립트의 함수도 `Functioin()`이라는 기본 내장 생성자 함수로부터 생성된 `객체`라고 볼 수 있다. - 앞에서 살펴본 함수선언문이아 함수 표현식 방식도 `Function()`생성자 함수가 아닌 함수 리터럴 방식으로 함수를 생성하지만, - 결국엔 이 또한 내부적으로는 `Function()`생성자 함수로 함수가 생성된다고 볼 수 있다. ```javascript var add = new Function('x', 'y', 'return x + y'); console.log(add(3, 4)); // 7 ``` > 이와 같은 방식은 실제로 많이 사용하지 않으므로 상식선에서만 알아두자.. #### 4.1.5 함수 호이스팅 처음 언급했던 함수의 3가지 생성방법에 대해 동작방식이 약간씩 다르다고 했었는데, 그중의 한가ㅏ 바로 `함수 호이스팅(Function Hoistion)` 이다. > 더글러스 크락포드의 저서 [더글라스 크락포드의 자바스크립트 핵심 가이드]에서 함수표현식만을 사용할 것을 권하고 있다. > 그 이유 중의 하나가 바로 함수 호이스팅 때문이다. ```javascript console.log(add(2,3)); // 5 // 함수 선언문 형태로 add() 함수 정의 function add(x, y) { return x + y; } console.log(add(3, 4)); // 7 ``` > 위 코드를 첫번째 줄을 보면 `add()`함수가 정의되지 않았음에도 정상적으로 호출된것을 알 수 있다. 이것은 함수가 자신이 위치한 코드에 상관없이 **함수 선언문 형태로 정의한 함수의 유효범위는 코드의 맨 처음부터 시작한다**는 것을 확인할 수 있다. 이것을 **함수 호이스팅**이라고 부른다. 더클라스크락포드는 이러한 함수 호이스팅은 함수를 사용하기 전에 반드시 선언해야 한다는 규칙을 무시하므로, 코드의 구조를 엉성하게 만들 수도 있다고 지적하며, 함수 표현식 사용을 권장하고 있다. 혹시 모르니 아래 `함수 표현식` 방식으로 인한 함수 호이스팅 코드를 실행해보자 ```javascript add(2,3); // uncaught type error // 함수 표현식 형태로 add() 함수 정의 var add = function (x, y) { return x + y; }; add(3, 4); ``` --- ### 4.2) 함수 객체 : 함수도 객체다 #### 4.2.1 자바스크립트에서는 함수도 객체다 - 자바스크립트에서는 `함수도 객체`다. 즉 함수의 기본 기능인 코드 실행뿐만 아니라, 함수 자체가 일반 객체처럼 프로퍼티들을 가질수 있다는 것이다. 예제를 통해 살펴보자 ```javascript // 함수 선언 방식으로 add()함수 정의 function add(x, y) { return x+y; } // add() 함수 객체에 result, status 프로퍼티 추가 add.result = add(3, 2); add.status = 'OK'; console.log(add.result); // 5 console.log(add.status); // 'OK' ``` > `add()`함수를 생성할 때 함수 코드는 함수 객체의 `[[Code]]` 내부 프로퍼티`에 자동으로 저장된다. > 즉 아래와 같다. `[[Code]]` --------> return x+y; `result` --------> 5; `status` --------> 'OK'; #### 4.2.2 자바스크립트에서 함수는 값으로 취급된다. > **함수도 일반 객체처럼 취급될 수 있다**는 말은 다음과 같은 동작이 가능하다는 뜻이다. - 리터럴에 의해 생성 - 변수나 배열의 요소, 객체의 프로퍼티 등에 할당 가능 - 함수의 인자로 전달 가능 - 함수의 리턴값으로 리턴가능 - 동적으로 프로퍼티를 생성 및 할당 가능 > 이와 같은 특징이 있으므로 자바스크립트에서는 함수를 `일급~FirstClass~ 객체`라고 부른다. 여기서 `일급객체`라는 말은 컴퓨터 프로그래밍 언어 분야에서 쓰이는 용어로서, 앞에서 나열한 기능이 모두 가능한 객체를 일급 객체라고 부른다. ##### 4.2.2.1 변수나 프로퍼티의 값으로 할당 함수는 숫자나 문자열처럼 변수나 프로퍼티의 값으로 할당될 수 있다. 예제를 통해 살펴보자 ```javascript // 변수에 함수 할당 var foo = 100; var bar = function () { return 100; }; console.log(bar()); // 100 // 프로퍼티에 함수 할당 var obj = {}; obj.baz = function () {return 200; } console.log(obj.baz()); // 200 ``` ##### 4.2.2.2 함수 인자로 전달 함수는 다른 함수의 인자로도 전달이 가능하다. 다음 예제를 살펴보자. `foo()`함수 표현식 방법으로 생성한 함수로서, 인자로 받은 func 함수를 내부에서 함수 호출 연산자()를 붙여 호출하는 기능을 한다. ```javascript // 함수 표현식으로 foo() 함수 생성 var foo = function(func) { func(); // 인자로 받은 func() 함수 호출 }; // foo() 함수 실행 foo(function() { console.log('Function can be used as the argument.'); }); // 출력결과 Function can be used as the argument. ``` > `foo()`함수를 호출할 때, 함수 리터럴 방식으로 생성한 `익명함수`를 func인자로 넘겼다. > 따라서 `foo()`함수 내부에서는 func 매개변수로 인자에 넘겨진 `함수`를 호출할 수 있다. > 출력결과를 보면 알 수 있듯이 인자로 넘긴 익명 함수가 `foo()`함수 내부에서 제대로 호출된 것을 알 수 있다. ##### 4.2.2.3 리턴값으로 활용 함수는 다른함수의 리턴값으로도 활용할 수 있다. 다음 에제에서 `foo()`함수는 `console.log()`를 이용해 출력하는 간단한 익명 함수를 리턴하는 역할을 한다. 이것이 가능한 이유 또한 함수 자체가 값으로 취급되기 때문이다. ```javascript // 함수를 리턴하는 foo() 함수 정의 var foo = function() { return function () { console.log('this function is the return value.') }; }; // foo() 함수가 호출되면, 리턴값으로 전달되는 함수가 bar변수에 저장된다. var bar = foo(); //()함수 호출 연산자를 이용해 bar()로 리턴된 함수를 실행하는 것이 가능하다. bar(); ``` #### 4.2.3 함수 객체의 기본 프로퍼티 계속 강조하듯이 자바스크립트에서는 함수 역시 객체다(그만큼 중요한 내용이므로 반복숙달 하자) 이것은 함수 역시 일반적인 객체의 기능에 추가로 호출됐을 때 정의된 코드를 실행하는 기능을 가지고 있다는 것이다. 또한, 일반객체와는 다르게 추가로 **함수 객체만의 표준프로퍼티**가 정의되어 있다. 실제 함수가 어떤 객체 형태로 되어있는지름 코드를 통해 직접 확인해보자. ```javascript function add(x, y) { return x + y; } console.dir(add); ``` 위 코드를 브라우저 개발자도로 살펴보면 아래와 같다. ```console function add(x,y) arguments: null caller: null length: 2 name: "add" prototype: add __proto__: () apply: apply() arguments: (...) get arguments: ThrowTypeError() set arguments: ThrowTypeError() bind: bind() call: call() caller: (...) get caller: ThrowTypeError() set caller: ThrowTypeError() constructor: Function() length: 0 name: "" toString: toString() __proto__: Object <function scope> ``` 1) `length`와 `prototype 프로퍼티` > A5 스크립트 명세서에는 모든 함수가 `length`와 `prototype 프로퍼티`를 가져야 한다고 기술하고 있다. 위 `add()`함수 역시 `length`와 `prototype 프로퍼티`를 가지고 있는 것을 확인할 수 있다. > length나 prototype 이외의`name`, `aller` `guments` `_proto__` 프로퍼티는 ECMA 표준이 아니다. 2) `name` > `name`프로퍼티는 함수의 이름을 나타내며, 익명 함수라면 이 값은 빈 문자열이 된다. 3) `caller` > `caller 프로퍼티`는 자신을 호출한 함수를 나타낸다. 이 예제에서는 `add()`함수를 호출하지 않았으므로, `null`값이 나왔다. 4) `arguments` > `arguments 프로퍼티`는 함수를 호출할 때 전달된 인자값을 나타내는데, 현재는 `add()`함수가 호출된 상태가 아니므로 `null`값이 출력됬다. 5)` __proto__` > **3.4 프로토타입** 에서 모든 자바스크립트 객체는 자신의 프로토타입을 가리키는 **[[Prototype]]라는 내부 프로퍼티**를 가진다고 설명했다. > 즉 `[[Prototype]]`과 `__proto__`는 같은 개념이라고 생각하면 된다. add()함수 역시 자바스크립트 객체이므로 `__proto__`프로퍼티를 가지고 있고 이를통해 자신의 부모 역할을 하는 프로토타입 객체를 가리킨다. > ECMA 표준에서는 `add()`와 같이 함수 객체의 부모 역할을 하는 프로토타입 객체를 `Function.prototype 객체`라고 명명하고 있으며, 이것 역시 **함수 객체**라고 정의하고 있다. ##### 4.2.3.1 length 프로퍼티 함수 객체의 length 프로퍼티는 앞서 설명했듯이 ECMAScript에서 정한 모든 함수가 가져야 하는 표준 프로퍼티로서, 함수가 정상적으로 실행될 때 기대되는 인자의 개수를 나타낸다. ```javascript function func0() { } function func1(x) { return x; } function func2(x, y) { return x + y; } function func3(x, y, z) { return x + y + z; } console.log('func0.length - ' + func0.length); // func0.length - 0 console.log('func1.length - ' + func1.length); // func1.length - 1 console.log('func2.length - ' + func2.length); // func2.length - 2 console.log('func3.length - ' + func3.length); // func3.length - 3 ``` > 출력값은 살펴보면 함수 객체의 length 프로퍼티는 함수를 작성할 때 정의한 인자 개수를 나타내고 있음을 알 수 있다. ##### 4.2.3.2 prototype 프로퍼티 - 모든 함수는 객체로서 `prototype 프로퍼티`를 가지고 있다. 여기서 주의할 것은 함수 객체의 `prototype 프로퍼티`는 앞서 설명한 모든 객체의 부모를 나타내는 `내부프로퍼티`인 `[[Prototype]]`과 혼동하지 말아야 한다는 것이다. - prototype 프로퍼티는 함수가 생성될 때 만들어지며, constructor 프로퍼티 하나만 있는 객체를 가리킨다. - prototype 프로퍼티가 가리키는 프로토타입 객체의 유일한 constructor 프로퍼티는 자신과 열결된 함수를 가리킨다. - 즉 `js`에서는 함수를 생성할 때, 함수 자신과 연결된 프로토타입 객체를 동시에 생성하며, 이 둘은 각각 prototype과 constructor라는 프로퍼티로 서로를 참조하게 된다. > 다음 예제를 통해 함수의 프로토타입 객체를 좀 더 살펴보자. ```javascript // myFunction 함수 정의 function myFunction() { return true; } console.dir(myFunction.prototype); console.dir(myFunction.prototype.constructor); ``` 1) 우선 `myFunction()`라는 함수를 생성했다. 함수가 생성됨과 동시에 `myFunction()` 함수의 prototype프로퍼티에는 이 함수와 연결된 프로토타입 객체가 생성된다. 2) `myFunction.prototype`은 `myFunction()`함수의 프로토타입 객체를 의미한다. 3) `myFunction.prototype.constructor`의 값을 출력함으로써 프로토타입 객체와 매핑된 함수를 알아볼 수 있다. 결과값을 보면 myFunction() 함수를 가리키고 있다. --- ### 4.3 함수의 다양한 형태 #### 4.3.1 콜백함수 - 자바스크립트 함수표현식에서 **함수이름**은 꼭 붙이지 않아도 되는 선택사항이다. - 즉, 함수의 이름을 지정하지 않아도 함수가 정의되며 이러한 함수가 익명함수다. - 이러한 익명 함수의 대표적인 용도가 바로 `콜백함수`이다. 콜백함수는 코드를 통해 명시적으로 호출하는 함수가 아니라, 개발자는 단지 함수를 등록하기만 하고, 어떤 이벤트가 발생했거나 특정 시점에 도달했을때 시스템에서 호출되는 함수를 말한다. 또한, 특정 함수의 인자로 넘겨서, 코드 내부에서 호출되는 함수 또한 콜백 함수가 될 수있다. 대표적인 콜백함수의 사용 예가 자바스크립트에서의 이벤트 핸들러 처리이다. > 다음 코드는 웹페이지가 로드됬을때 경고창을 띄워 주는 간단한 예제다. > `window.onload`는 이벤트 헨들러로서, 웹 페이지의 로딩이 끝나는 시점에 `load`이벤트가 발생하면 실행된다. > 예제에서는 `window.onload`이벤트 핸들러를 익명 함수로 연결했다. 따라서 익명 함수가 콜백 함수로 등록된 것이다. ```javascript <!DOCTYPE html> <html> <body> <script> // 페이지 로드시 호출될 콜백 함수 window.onload = function() { alert('This is the callback function.'); }; </script> </body> </html> ``` #### 4.3.2 즉시실행함수 - 함수를 정의함과 동시에 바로 실행되는 함수를 `즉시 실행 함수`라고 한다. - 이 함수도 익명함수를 응용한 형태이다. ```javascript (function (name) { console.log('This is the immediate function --> ' + name); })('foo'); ``` > `즉시실행함수`를 만드는 방법은 간단하다. - 우선 함수 리터럴을 `()`로 둘러싼다. 이때 함수 이름이 있든 없든 상관없다. - 그런 다음 함수가 바로 호출될 수 있게 `()`괄호 쌍을 추가한다. - 이때 괄호 안에 값을 추가해 `즉시 실행 함수`의 인자로 넘길 수가 있다. (예제의 경우는 `('foo')`로 즉시 실행함수를 호출했으며, 이때 'foo'를 인자로 넘겼다 - 이렇게 함수가 선언되자마자 실행되게 만든 즉시 실행함수의 경우, 같은 함수를 다시 호출할 수 없다. - 따라서 즉시실행함수의 이러한 특징을 이용한다면 **최초 한 번의 실행만을 필요로 하는 초기화 코드부분**등에 사용할 수있다. > 즉시 실행 함수의 또 다른 용도를 알아보자. 그것은 바로 `jQuery`와 같은 자바스크립트 라이브러리나 프레임워크 소스들에서 사용된다. `jQuery`최신 소스코드를 살펴보면 소스의 시작 부분과 끝 부분이 다음 에제와 같이 즉시 실행 함수 형태로 구성되어 있음을 확인할 수 있다. 즉 `jQeury`소스 코드 전체가 즉시 실행 함수고 감싸져 있다. ```javascript (function(window, undefined){ ......생략 })(window); ``` > 이렇게 `jQuery`에서 즉시 실행 함수를 사용하는 이유는 자바스크립트의 변수 유효범위 특성때문이다. > 자바스크립트에서는 **함수유효범위**를 지원한다. > 자바스크립트는변수를 선언할 경우 프로그램 전체에서 접근할 수 있는 전역 유효범위를 가지게 된다. > 그러나 함수 내부에서 정의된 매개변수와 변수들은 함수 코드 내부에서만 유효할 뿐 함수 밖에서는 유효하지 않다. > 이것은 달리 ㅁ라하면 함수 외부의 코드에서 함수 내부의 변수를 엑세스하는 게 불가능 하다는 것이다. 이에 대한 자세한 내용은 5장 참고 > 따라서 라이브러리 코드를 이렇게 즉시 실행 함수 내부에 정의해두게 되면, 라이브러리 내의 변수들은 함수 외부에서 접근할 수 없다. > 따라서 이렇게 즉시실행함수 내에 라이브러리 코드를 추가하면 전역 네임스페이스를 더럽히지 않으므로, 이후 다른 자바스크립트 라이브러리들이 동시에 로드가 되더라도 라이브러리 간 변수 이름 충돌 같은 문제를 방지할 수 있다. #### 4.3.3 내부함수 자바스크립트에서는 함수 코드 내부에서도 다시 함수 정의가 가능하다. 이렇게 함수 내부에 정의된 함수를 **내부 함수**라고 부른다. 내부 함수는 자바스크립트의 기능을 보다 강력하게 해주는 클로저를 생성하거나 부모 함수 코드에서 외부에서의 접근을 막고 독립적인 헬퍼 함수를 구현하는 용도 등으로 사용한다. ```javascript // parent() 함수 정의 function parent() { var a = 100; var b = 200; // child() 내부 함수 정의 function child() { var b = 300; console.log(a); console.log(b); } child(); } parent(); child(); ``` > 출력결과 ```javascript 100 300 Uncaught ReferenceError: chiled is not defined ``` > 내부 함수는 자신을 둘러썬 외부 함수의 변수에 접근가능하다. 이게 가능한 이유는 자바스크립트의 `스코프체이닝`때문이다. > 관련된 자세한 내용은 5장에서 다룬다.(다음장) > 마지막줄에 `parent()`함수 외부에서 `child()`함수 호출을 시도하지만, 함수가 정의되어 있지 않다는 에러가 발생한다. > 이것은 자바스크립트의 함수 스코핑 때문이다. > 즉, 함수 내부에 선언된 변수는 함수 외부에서 접근이 불가능하다. > 이 규칙은 내부 함수도 그대로 적용된다. > > 하지만 함수 외부에서도 특정함수 스코프 안에 선언된 내부 함수를 호출할 수 있다. > 가령, 부모 함수에서 내부 함수를 외부로 리턴하면, 부모 함수 밖에서도 내부 함수를 호출하는 것이 가능하다. > 아래 예제는 parent()함수를 호출하고, 이 결과로 반환된 inner()함수를 호출하는 간단한 예제이다. ```javascript function parent() { var a = 100; // child() 내부 함수 var child = function () { console.log(a); } // child() 함수 반환 return child; } var inner = parent(); inner(); ``` > 1) 내부 함수를 함수 표현식 형식으로 정의하고, child 함수 변수에 저장했다. 그리고 parent()함수의 리턴값으로 > 내부 함수의 참조값을 가진 child 함수 변수를 리턴했다. > 2) parent()함수가 호출되면, inner변수에 child함수 변수 값이 리턴된다. child함수 변수는 내부 함수의 참조값이 있으므로, 결국 inner 변수도 child()내부 함수를 참조했다. > 3) 때문에 inner변수에 함수 호출 연산자 `()`를 붙여 함수 호출 구문을 만들면, > parent()함수 스코프 밖에서도 내부 함수 child()가 호출된다. > 호출하는 내부 함수에는 a 변수가 정의되어 있지 않아, 스코프 체이닝으로 부모 함수에 a 변수가 정의되어 있는지 확인하게 되고, a가 정의되어 있으면 그 값이 출력된다. 이와 같이 실행이 끝난 parent()와 같은 부모 함수 스코프의 변수를 참조하는 inner()와 같은 함수를 `클로저`라고 한다. #### 4.3.4 함수를 리턴하는 함수 - 자바스크립트에서는 함수도 일급 객체이므로 일반 값처럼 함수 자체를 리턴할 수도 있다. - 이러한 특징은 다양한 활용이 가능해진다. - 함수를 호출함과 동시에 다른함수로 바꾸거나, - 자기 자신을 재정의하는 함수를 구현할 수 있다. - 이러한 함수 유형 또한 자바스크립트의 언어적인 유연성을 보여주는 좋은 활용예다. > 다음 에제는 함수를 리턴하는 self 라는 함수를 정의했다 ```javascript // self() 함수 var self = function () { console.log('a'); return function () { console.log('b'); } } self = self(); // a self(); // b ``` 1. 처음 self()함수가 호출됐을 때는 `a`가 출력된다. 그리고 다시 self 함수 변수에 self()함수 호출 리턴값으로 내보낸 함수가 저장된다. 2. 두번째로 self()함수가 호출됐을 때는 `b`가 출력된다. 즉, 1번에서 self()함수 호출 후에, self 함수 변수가 가리키는 함수가 원래 함수에서 리턴 받은 새로운 함수가 변경됐기 때문이다. ### 4.4 함수 호출과 this > 함수의 기본적인 기능은 당연히 함수를 호출하여 코드를 실행하는 것이다. > 하지만 자바스크립트 언어 자체가 `C/C++`같은 엄격한 문법 체크를 하지 않는 자유로운 특성의 언어이므로 함수 호출 또한 다른 언어와는 달리 자유롭다. #### 4.4.1 arguments 객체 > `C`와 같은 엄격한 언어와 달리, 자바스크립트에서는 함수를 호출할 때 함수 형식에 맞춰 인자를 넘기지 않더라도 에러가 발생하지 않는다. > 백문이 불여일견 코드를 보자 ```javascript function func(arg1, arg2) { console.log(arg1, arg2); } func(); // undefined undefined func(1); // 1 undefined func(1,2); // 1 2 func(1,2,3); // 1 2 ``` 위 예제를 보면 알 수 있듯이 정의된 함수의 인자보다 적게 함수를 호출했을 경우에는 `undefined`값이 할당 되고 이와 반대로 정의된 인자 개수보다 많게 함수를 호출했을 경우는 에러는 발생하지 않고, 초과된 인수는 무시된다. > 자바스크립트의 이러한 특성 때문에 함수 코드를 작성할 때, 런타임 시에 호출된 인자의 개수를 확인하고 > 이에 따라 동작을 다르게 해줘야 할 경우가 있다. > 이를 가능케 하는 게 바로 `arguments 객체`다 > 자바스크립트에서는 함수를 호출할 때 인수들과 함께 암묵적으로 arguments객체가 함수 내부로 전달되기 때문이다. 여기서 `arguments 객체`는 함수를 호출할 때 넘긴 인자들이 배열 형태로 저장된 객체를 의미한다. 특이한 점은 이 객체는 실제 배열이 아닌 **유사 배열 객체**라는 점이다. > 유사배열 객체는 이전장에서 살펴봤으니 arguments 객체를 살펴보자 ```javascript // add() 함수 function add(a, b) { // arguments 객체 출력 console.dir(arguments); return a+b; } console.log(add(1)); // NaN console.log(add(1,2)); // 3 console.log(add(1,2,3)); // 3 ``` > 아래는 개발자도구를 통해 살펴본 값이다. ``` Arguments[1] 0: 1 // 호출 시에 넘긴 인자를 배열 형태로 저장 callee: add(a, b) length: 1 //호출 시에 넘긴 인자 개수 Symbol(Symbol.iterator): values() __proto__: Object NaN Arguments[2] 0: 1 // 호출 시에 넘긴 인자를 배열 형태로 저장 1: 2 callee: add(a, b) length: 2 //호출 시에 넘긴 인자 개수 Symbol(Symbol.iterator): values() __proto__: Object 3 Arguments[3] 0: 1 // 호출 시에 넘긴 인자를 배열 형태로 저장 1: 2 2: 3 callee: add(a, b) length: 3 //호출 시에 넘긴 인자 개수 Symbol(Symbol.iterator): values() __proto__: Object 3 ``` - arguments는 객체이지 배열이 아니다. 즉, length 프로퍼티가 있으므로 배열과 유사하게 동작하지만, 배열은 아니므로 - 배열 메소드를 사용할 경우 에러가 발생한다는 것에 주의해야 한다. - 물론 유사배열객체에서 배열 메소드를 사용하는 방법이 있다. > arguments 객체는 매개변수 개수가 정확하게 정해지지 않은 함수를 구현하거나, 전달된 인자의 개수에 따라 서로 다른 처리를 해줘야 하는 함수를 개발하는 데 유용하게 사용할 수 있다. ```javascript function sum(){ var result = 0; for(var i=0; i<arguments.length; i++){ result += arguments[i]; } return result; } console.log(sum(1,2,3)); // 출력값 6 console.log(sum(1,2,3,4,5,6,7,8,9)); // 출력값 45 ``` #### 4.4.2 호출 패턴과 this 바인딩 자바스크립트에서 함수를 호출할 때 기존 매개변수로 전달되는 인자값에 더해, `arguments 객체` 및 `this 인자`가 함수 내부로 암묵적으로 전달된다. 여기서 특히 `this 인자`는 고급 자바스크립트 개발자로 거듭나려면 확실히 이해해야 하는 핵심 개념이다. `this`가 이해하기 어려운 이유는 자바스크립트의 여러 가지 ==**함수가 호출되는 방식(호출패턴)**==에 따라 this가 다른 ==**객체를 참조**==하기 ==**(this 바인딩)**==때문이다. 따라서 이번 절에서는 함수 호출 패턴과 해당 패턴에 따라 this가 어떤 객체에 바인딩이 되는지에 대해서 알아보자. ##### 4.4.2.1 객체의 메소드 호출할 때 this 바인딩 객체의 프로퍼티가 함수일 경우, 이 함수를 메소드라고 부른다. 이러한 메소드를 호출할 때, 메소드 내부 코드에서 사용된 this는 **++해당 메소드를 호출한 객체로 바인딩++**된다. ```javascript // myObject 객체 생성 var myObject = { name: 'foo', sayName: function () { console.log(this.name); } }; // ohterObject 객체 생성 var otherObject = { name: 'bar' }; // otherObject.sayName() 메서드 otherObject.sayName = myObject.sayName; // sayName() 메서드 호출 myObject.sayName(); otherObject.sayName(); ``` > 출력 결과 ``` foo bar ``` ##### 4.4.2.2 함수를 호출할 때 this 바인딩 자바스크립트에서는 함수를 호출하면, 해당 함수 내부 코드에서 사용된 ==**this 는 전역 객체에 바인딩**==된다. 브라우저에서 자바스크립트를 실행하는 경우 전역 객체는 ==**window 객체**==가 된다. 자바스크립트의 모든 전역 변수는 실제로는 이러한 전역 객체의 프로퍼티들이다. ```javascript var foo = "I'm foo"; // 전역 변수 선언 console.log(foo); // I’m foo console.log(window.foo); // I’m foo ``` > 위 코드를 보면 알 수 있듯이 전역 변수는 전역 객체(window)의 프로퍼티로도 접근할 수가 있다. > 이제 함수를 호출할 때 this바인딩이 어떻게 되는지를 다음 예제 코드를 살펴보자. ```javascript var test = 'This is test'; console.log(window.test); // sayFoo() 함수 var sayFoo = function () { console.log(this.test); // sayFoo() 함수 호출 시 this는 전역 객체에 바인딩된다. }; sayFoo(); // this.test 출력 ``` > 출력결과 ``` This is test This is test ``` > 자바스크립트의 전역 변수는 전역 객체(window)의 프로퍼티로 접근 가능하다..는점을 상기 하지만 이러한 함수 호출에서의 this바인딩 특성은 ==**내부함수를 호출했을 경우**==에도 그대로 적용되므로, 내부 함수에서 this를 이용할 때는 주의해야 한다. ```javascript // 전역 변수 value 정의 var value = 100; // myObject 객체 생성 var myObject = { value: 1, func1: function () { this.value += 1; console.log('func1() called. this.value : ' + this.value); // func2() 내부 함수 func2 = function () { this.value += 1; console.log('func2() called. this.value : ' + this.value); // func3() 내부 함수 func3 = function () { this.value += 1; console.log('func3() called. this.value : ' + this.value); } func3();// func3() 내부 함수 호출 } func2(); // func2() 내부 함수 호출 } }; myObject.func1(); // func1() 메서드 호출 ``` > 출력결과 ``` func1() called. this.value : 2 func2() called. this.value : 101 func3() called. this.value : 102 ``` 자바스크립트에서는 내부 함수 호출패턴을 정의해 놓지 않기 때문에 이와같은 결과가 나왔다. > 이렇게 내부 함수가 this를 참조하는 자바스크립트의 한계를 극복하려면 ==**부모함수(위 에제의 func1()메소드)의 this**==를 내부함수가 접근 가능한 ==**다른 변수에 저장**==하는 방법이 사용된다. > 관례상 this의 값을 저장하는 변수의 이름을 `that`이라고 짓는다. ```javascript // 내부 함수 this 바인딩 var value = 100; var myObject = { value: 1, func1: function () { var that = this; this.value += 1; console.log('func1() called. this.value : ' + this.value); func2 = function () { that.value += 1; console.log('func2() called. this.value : ' + that.value); func3 = function () { that.value += 1; console.log('func3() called. this.value : ' + that.value); } func3(); } func2(); } }; myObject.func1(); // func1 메서드 호출 ``` > 자바스크립트에서는 이와 같은 this바인딩의 한계를 극복하려고, this 바인딩을 명시적으로 할 수 있도록 `call`과 `apply` 메소드를 제공하는데, 이는 다다음 절에서 알아보자. > 또한 jQuery, underscore.js 등과 같은 자바스크립트 라이브러리들의 경우 bind라는 이름의 메소드를 통해, > 사용자가 원하는 객체를 this에 바인딩할 수 있는 기능을 제공하고 있다. ##### 4.4.2.3 생성자 함수를 호출할 때 this 바인딩 3장에서 살펴봤듯이 자바스크립트 객체를 생성하는 방법은 크게 객체 리터럴 방식이나 생성자 함수를 이용하는 두가지 방법이 있다. > 자바와 같은 객체지향 언어에서의 생성자 함수의 형식과는 다르게 그 형식이 정해져 있는 것이 아니라, 기존 함수에 new연산자를 붙여서 호출하면 해당 함수는 생성자 함수로 동작한다. > 이는 반대로 생각하면 일반 함수에 new를 붙여 호출하면 원치 않는 생성자 함수처럼 동작할 수 있다는 뜻이다. > 따라서 대부분의 자바스크립트 스타일 가이드에서는 특정 함수가 생성자 함수로 정의되어 있음을 알리려고 > ++**함수 이름의 첫 문자를 대문자로 쓰기**++를 권하고 있다. 생성자 함수를 호출할 때, 생성자 함수 코드 내부에서 `this`는 바로 이전에 알아본 `메소드`와 `함수 호출방식`에서의 this바인딩과는 또 다르게 동작한다. > 그전에 생성자 함수가 동작하는 방식을 먼저 알아보자 new 연산자로 자바스크립트 함수를 생성자로 호출하면, 다음과 같은 순서로 동작한다. 1. 빈객체 생성 및 this 바인딩 - 생성자 함수 코드가 실행되기 전 **빈 객체**가 생성된다. - 바로 이 객체가 생성자 함수가 새로 생성하는 객체이며, 이 객체는 this로 바인딩된다. 따라서 이후 생성자 함수의 코드 내부에서 사용된 this는 이 빈객체를 가리킨다. - 하지만 여기서 생성된 객체는 엄밀히 말하면 **빈 객체는 아니다** - 앞서 살펴본것처럼 `js`의 모든 객체는 자신의 부모인 프로토타입 객체와 연결되어 있으며, 이를 통해 부모 객체의 프로퍼티나 메소드를 마치 자신의 것처럼 사용할 수가 있기 때문이다. - 이렇게 생성자 함수가 생성한 객체는 자신을 생성한 **생성자 함수의 prototype 프로퍼티**가 가리키는 객체를 **자신의 프로토타입 객체**로 설정한다. 2. this를 통한 프로퍼티 생성 - 이후에는 함수 코드 내부에서 this를 사용해서, 앞에서 생성된 빈 객체에 동적으로 프로퍼티나 메소드를 생성할 수 있다. 3. 생성된 객체 리턴 - 리턴문이 동작하는 방식은 경우에 따라 다르므로 주의해야 한다. - 가장 일반적인 경우로 리턴문이 없을 경우, **this로 바인딩된 새로 생성한 객체가 리턴**된다. - 이것은 명시적으로 this를 리턴해도 결과는 같다 - 하지만 리턴값이 새로 생성한 객체(this)가 아닌 다른 객체를 반환하는 경우는 생성자 함수를 호출했다고 하더라도 this가 아닌 해당 객체가 리턴된다. ```javascript // Person 생성자 함수 var Person = function (name) { this.name = name; }; // foo 객체 생성 var foo = new Person('foo'); console.log(foo.name); // foo ``` > #### 객체 리터럴 방식과 생성자 함수를 통한 객체 생성 방식의 차이 각각 두가지의 차이점은 뭘까? > 예제를 통해 살펴보자 ```javascript //객체 리터럴 방식으로 foo 객체 생성 var foo = { name: 'foo', age: 35, gender: 'man' }; console.dir(foo); //생성자 함수 function Person(name, age, gender, position) { this.name = name; this.age = age; this.gender = gender; } // Person 생성자 함수를 이용해 bar 객체, baz 객체 생성 var bar = new Person('bar', 33, 'woman'); console.dir(bar); var baz = new Person('baz', 25, 'woman'); console.dir(baz); ``` > `foo`객체와 같이 객체리터럴 방식으로 생성된 객체는 같은 형태의 객체를 재생성할 수 없다. > `Person()`생성자 함수를 사용해서 객체를 생성하면, 생성자 함수를 호출할 때 다른 인자를 넘김으로써 같은 형태의 서로다른 객체 bar와 bax를 생성할 수 있다. 개발자 도구의 console.dir 값도 확인해 보자 > #### 생성자 함수를 new를 붙이지 않고 호출할 경우 `js`에서는 일반함수와 생성자 함수가 별도의 차이가 없다. new를 붙여서 함수를 호출하면 생성자 함수로 동작하는 것이다. 때문에 객체 생성을 목적으로 작성한 생성자 함수를 new 없이 호출하거나 일반함수를 new를 붙여서 호출할 경우 코드에서 오류가 발생할 수 있다. > 그이유는 this 바인딩 방식이 각각 다르기 때문이다. - 일반 함수 호출은 this가 window 전역객체에 바인딩 - 생성자 함수 호출의 경우 this는 새로 생성되는 빈 객체에 바인딩 ```javascript //생성자 함수 function Person(name, age, gender, position) { this.name = name; this.age = age; this.gender = gender; } var qux = Person('qux', 20, 'man'); console.log(qux); // undefined console.log(window.name); // qux console.log(window.age); // 20 console.log(window.gender); // man ``` > 위와 같이 `js`에서는 일반 함수와 생성자 함수의 구분이 별도로 없으므로, 일반적으로 생성자 함수로 사용할 함수는 > 첫 글자를 대문자로 표기하는 네이밍 규칙을 권장한다. > 그러나 이러한 규칙을 사용하더라도 결국 new를 사용해서 호출하지 않을 경우 에러가 발생하므로 > 더글라스 크락포드와 같은 전문가들은 객체를 생성하는 **다음과 같은 별도의 코드 패턴**을 사용하기도 한다. ```javascript // 앞에서 설명한 위험성을 피하려고 널리 사용되는 패턴이 있다. function A(arg){ if(!(this instanceof A)) return new A(arg); this.value = arg ? arg :0; } var a = new A(100); var b = A(10); console.log(a.value); //출력값 100 console.log(b.value); //출력값 10 console.log(global.value); //출력값 undefined ``` > `함수 A`에서는 `A`가 호출될 때, this가 `A`의 인스턴스인지를 확인하는 분기문이 추가되었다. > rhis가 `A`의 인스턴스가 아니라면, `new`로 호출된 것이 아님을 의미하고, 이경우 `new`로 A를 호출하여 반환하게 하였다. > 이렇게 하면 `var b = A(10);`과 같이 사용자가 사용했다고 하더라도, `전역 객체`에 접근하지않고, `새 인스턴스`가 생성되어 b에 반환될 것이다. > 이와 같이 하면, 특정 함수 이름과 상관없이 이 패턴을 공통으로 사용하는 모듈을 작성할 수 있는 장점이 있다. ##### 4.4.2.4 call과 apply메소드를 이용한 명시적인 this바인딩 자바스크립트에서 함수호출이 발생할 때마다 각각의 상황에 따라 `this`가 정해진 객체에 자동으로 바인딩 된다는것을 확인했다 자바스크립트에서는 이러한 내부적인 `this`바인딩 이외에도 `this`를 특정객체에 **명시적으로 바인딩**시키는 방법도 제공한다. > 이를 가능하게 하는 것이 바로 **함수 객체의 기본프로퍼티**에서 간단히 설명한 `apply()`나 `call()`메소드다. > 다음과 같은 형식으로 `apply()` 메소드를 호출하는 것이 가능하다 ```javascript function.apply(thisArg, argArray) ``` - 첫번째 인자 thisArg는 apply()메소드를 호출한 함수 내부에서 사용한 this에 바인딩할 객체를 가리킨다. - 두번째 인자 argArray 인자는 함수를 호출할 때 넘길 인자들의 배열을 가리킨다. > 두번째 인자인 argArray 배열을 자신을 호출한 함수의 인자로 사용하되, 이 함수 내부에서 사용된 this는 첫 번째 인자인 > thisArg객체로 바인딩해서 함수를 호출하는 기능을 하는 것이다. ```javascript // 생성자 함수 function Person(name, age, gender) { this.name = name; this.age = age; this.gender = gender; } // foo 빈 객체 생성 /* foo는 객체 리터럴 방식으로 생성한 빈 객체다. */ var foo = {}; // apply() 메서드 호출 /* apply()메소드를 사용해서, Person()함수를 호출한 코드다. 이 코드는 결국 Person('foo',30,'man') 함수를 호출하면서, this를 foo 객체에 명시적으로 바인딩하는 것을 의미한다. */ Person.apply(foo, ['foo', 30, 'man']); console.dir(foo); ``` > 출력결과 ``` Object age: 30 gender: "man" name: "foo" __proto__: Object ``` 출력결과를 보면 foo 객체에 제대로 프로퍼티가 생성되어 있음을 확인할 수 있다. call()메서드의 경우로 살펴보면 아래와 같다 ```javascript Person.call(foo,'foo',30,'man'); ``` 이런 apply()나 call()메소드는 this를 원하는 값으로 명시적으로 매핑해서 특정함수나 메서드를 호출할 수 있다는 장점이 있다. > 이들의 대표적인 용도가 바로 arguments객체에서 설명한 arguments 객체와 같은 유사배열객체에서 배열 메서드를 사용하는 경우다 자세한 사항은 p.117 ~ 118 참조 #### 4.4.3 함수 리턴 - 자바스크립트 함수는 항상 리턴값을 반환한다. - 특히 return 문을 사용하지 않았더라도 다음의 규칙으로 항상 리턴값을 전달하게 된다. 규칙1) 일반 함수나 메소드는 리턴값을 지정하지 않을 경우, undefined 값이 리턴된다. 규칙2) 생성자 함수에서 리턴값을 지정하지 않을 경우 생성된 객체가 리턴된다. ### 4.5 프로토타입 체이닝 #### 4.5.1 프로토타입의 두 가지 의미 - 자바스크립트는 자바같은 객체지향 프로그래밍 언어와는 다른 ++**프로토타입 기반의 객체지향 프로그래밍**++을 지원한다. - 자바스크립트의 동작 과정을 제대로 이해하려면 프로토타입의 개념도 잘 이해하고 있어야 한다. **프로토타입**과 **프로토타입 체이닝**의 기본개념을 알아보자 - 자바스크립트에는 `Java`와 같은 `클래스`개념이 없다. - 대신에 객체리터럴이나 생성자함수로 객체를 생성한다. - 이렇게 생성된 객체의 부모객체가 바로 '프로토타입'객체다. > 함수객체의 `prototype 프로퍼티`와 객체의 숨은 프로퍼티인 `[[Prototype]]`을 구분하는것이 초급 개발자와 고급 개발자의 차이라할만큼 중요하다 이 둘의 차이점을 알려면 **자바스크립트의 객체 생성 규칙**을 알아야 한다. > 자바스크립트에서 모든 객체는 자신을 생성한 생성자 함수의 prototype 프로퍼티가 가리키는 **프로토타입 객체**를 자신의 부모객체로 설정하는 [[Prototype]]링크로 연결한다. ```javascript // Person 생성자 함수 function Person(name) { this.name = name; } // foo 객체 생성 var foo = new Person('foo'); console.dir(Person); console.dir(foo); ``` #### 4.5.2 객체 리터럴 방식으로 생성된 객체의 프로토타입 체이닝 - 자바스크립트에서 객체는 자기 자신의 프로퍼티뿐만이 아니라, 자신의 부모 역할을 하는 프로토타입 객체의 프로퍼티 또한 마치 자신의 것처럼 접근하는게 가능하다. > 이것을 가능하게 하는게 바로 `프로토타입 체이닝`이다 ```javascript var myObject = { name: 'foo', sayName: function () { console.log('My Name is ' + this.name); } }; myObject.sayName(); console.log(myObject.hasOwnProperty('name')); console.log(myObject.hasOwnProperty('nickName')); myObject.sayNickName(); ``` > sayNickName() 메소드는 myObject 객체의 메소드가 아니므로 당연히 에러가 나지만 > hasOwnProperty()메소드는 에러가 안난다? 이를 이해하려면 객체 리터럴 방식으로 생성한 객체와 프로토타입 체이닝의 개념을 살펴봐야 한다. > 우선 객체리터럴로 생성한 객체는 `Object()`라는 내장 생성자 함수로 생성된 것이다. > Object()생성자 함수도 함수 객체이므로 prototype이라는 프로퍼티 속성이 있다. > 따라서 앞서 설명한 자바스크립트의 규칙으로 생성한 객체 리터럴 형태의 `myObject`는 `Object()`함수의 prototype 프로퍼티가 가리키는 Object.prototype 객체를 자신의 프로토타입 객체로 연결한다. 프로토타입 체이닝의 개념은 자바스크립트에서 특정객체의 프로퍼티나 메소드에 접근하려고 할 때, 해당 객체에 접근하려는 프로퍼티 또는 메소드가 없다면!!! > `[[Prototype]]링크`를 따라 자신의 부모 역할을 하는 프로토타입 객체의 프로퍼티를 차례대로 검색하는 것을 프로토타입 체이닝이라고 말한다. 위의 예제를 치면 `hasOwnProperty()`는 `myObejct`객체에 없으므로 [[Prototype]]링크를 따라 그것의 부모 역할을 하는 Object.prototype 프로토타입 객체 내에 `hasOwnProperty()` 메소드가 있는지 검색하는 것이다. 이 메소드는 자바스크립트 표준 API로 Object.prototype 객체에 포함되어 있으므로 에러가 나지 않았던 것이다. ##### 4.5.3 생성자 함수로 생성된 객체의 프로토타입 체이닝 생성자 함수로 객체를 생성하는 경우는 객체리터럴 방식과 얀간 다른 프로토타입 체이닝이 이뤄진다. 다만 다음의 그 기본원칙은 잘 지키고 있다 > 자바스크립트에서 모든 객체는 자신을 생성한 생성자 함수의 prototype 프로퍼티가 가리키는 객체를 자신의 프로토타입 객체(부모객체)로 취급한다. ```javascript // Person 생성자 함수 function Person(name, age, hobby) { this.name = name; this.age = age; this.hobby = hobby; } // foo 객체 생성 var foo = new Person('foo', 30, 'tennis'); // 프로토타입 체이닝 console.log(foo.hasOwnProperty('name')); // true // Person.prototype 객체 출력 console.dir(Person.prototype); ``` #### 4.5.4 프로토타입 체이닝의 종점 자바스크립트에서 Object.prototype 객체는 **프로토타입 체이닝**의 종점이다. 이것을 달리 해석하면, 객체리터럴방식이나 생성자함수 방식에 상관없이 모든 자바스크립트 객체는 프로토타입 체이닝으로 Object.prototype 객체가 가진 프로퍼티와 메서드에 접근하고, 서로 공유가 가능하다는 것을 알 수 있다. > 때문에 자바스크립트 표준 빌트인 객체인 `Object.prototype`에는 `hasOwnProperty()`나 `isPrototypeOf()`등과 같이 > 모든 객체가 호출 가능한 표준 메서드들이 정의되어 있다. #### 4.5.5 기본 데이터 타입 확장 - `Object.prototype`에 정의된 메소드들은 자바스크립트의 모든 객체의 표준 메소드라고 볼 수 있다. 이와 같은 방식으로 자바스크립트의 숫자, 문자, 배열 등에서 사용되는 표준 메소드들의 경우, 이들의 프로토타입인 `Number.prototype`, `String.prototype`, `Array.prototype`등에 정의되어 있다. 자바스크립트는 Object.prototype, String.prototype 등과 같이 표준 빌트인 프로토타입 객체에도 사용자가 직접 정의한 메소드들을 추가하는 것을 허용한다. 가령 아래 예제 처럼 String.prototype 객체에 testMethod() 메소드를 추가하면 이 메소드는 일반 문자열 표준 메소드처럼, 모든 문자열에서 접근 가능하다 ```javascript String.prototype.testMethod = function () { console.log('This is the String.prototype.testMethod()'); }; var str = "this is test"; str.testMethod(); console.dir(String.prototype); ``` #### 4.5.6 프로토타입도 자바스크립트 객체다 함수가 생성될 때, 자신의 prototype 프로퍼티에 연결되는 프로토타입 객체는 디폴트로 constructor 프로퍼티만을 가진 객체다. 당연히 프로토타입 객체 역시 자바스크립트 객체 이므로 일반 객체처럼 동적으로 프로퍼티를 추가/삭제하는 것이 가능하다. ```javascript // Person() 생성자 함수 function Person(name) { this.name = name; } // foo 객체 생성 var foo = new Person('foo'); /foo.sayHello(); // 프로토타입 객체에 sayHello() 메서드 정의 Person.prototype.sayHello = function () { console.log('Hello'); } foo.sayHello(); // Hello ``` #### 4.5.7 프로토타입 메소드와 this 바인딩 프로토타입 객체는 메소드를 가질 수 있다. 만약 프로토타입 메소드 내부에서 this를 사용한다면 이는 어디에 바인딩 될까? > 4.4.2.1 객체의 메소드를 호출할 때 this 바인딩에서 설명한 this 바인딩 규칙을 그대로 적용하면 된다. > 결국, 메소드 호출 패턴에서의 this는 그 메소드를 호출한 객체에 바인딩된다는 것을 기억하다. ```javascript function Person(name){ this.name=name; } Person.prototype.getName=function(){ return this.name; } var foo = new Person('foo'); console.log(foo.getName()); Person.prototype.name='person'; console.log(Person.prototype.getName()); ``` #### 4.5.6 디폴트 프로토 타입은 다른 객체로 변경이 가능하다 디폴트 프로토타입 객체는 함수가 생성될 때 같이 생성되며, 함수의 prototype 프로퍼티에 연결된다. 자바스크립트에서는 이렇게 함수를 생성할 때 해당 함수와 연결되는 디폴트 포로토타입 객체르르 다른 일반 객체로 변경하는 것이 가능하다. 이러한 특징을 이용해서 객체지향의 상속을 구현한다. > 여기서 주의할 점! 생성자 함수의 프로토타입 객체가 변경되면, 변경된 시점 이후에 생성된 객체들은 변경된 프로토타입 객체로 [[Prototype]]링크를 연결한다는 것이다. 이에 반해 생성자 함수의 프로토타입이 변경되기 이전에 생성된 객체들은 기존 프로토타입 객체로의 [[Prototype]] 링크를 그대로 유지한다. ```javascript // Person() 생성자 함수 function Person(name) { this.name = name; } console.log(Person.prototype.constructor); // foo 객체 생성 var foo = new Person('foo'); console.log(foo.country); // 디폴트 프로토타입 객체 변경 Person.prototype = { country: 'korea' }; console.log(Person.prototype.constructor); // bar 객체 생성 var bar = new Person('bar'); console.log(foo.country); console.log(bar.country); console.log(foo.constructor); console.log(bar.constructor); // 출력 결과 /* function Person(name) { this.name = name; } undefined function Object() { [native code] } undefined korea function Person(name) { this.name = name; } function Object() { [native code] } */ ``` #### 4.5.9 객체의 프로퍼티 읽기나 메소드를 실행할 때만 프로토타입 체이닝이 동작한다. 객체의 특정 프로퍼티를 읽으려고 할때, 프로퍼티가 해당 객체에 없는 경우 프로토타입 체이닝이 발생한다. 반대로 객체에 있는 특정 프로퍼티에 값을 쓰려고 한다면 이때는 프로토타입 체이닝이 일어나지 않는다. <file_sep>/java/god_of_java/Vol.1/04. 정보를 어디에 넣고 싶은데/PrimitiveTypes.java public class PrimitiveTypes { public void checkByte() { byte byteMin = -128l byte byteMax = 127; System.out.println("byteMin="byteMin); System.out.println("byteMax="byteMax); byteMin--; byteMax++; System.out.println("byteMin--="byteMin); System.out.println("byteMax++="byteMax); } public static void main(String[] args) { PrimitiveTypes types=new PrimitiveTypes(); types.checkByte(); } public void checkOtherTypes() { short shortMax=32767; int intMax=2147483647; long longMax=9223372036854775807l; // 맨 마지막은 소문자L 이다. long 타입을 명시하기 위해 사용 } } <file_sep>/guide/server/Zeus&Webtob/webtob.MD # WEBTOB ---------------- ##### 1. 개요 WEBTOB 가이드입니다. 버전은 4.1 윈도우를 기준으로 작성하였습니다. 또한 사전에 JEUS가 설치되어 있어야만 합니다. --------------- ##### 2. 설치 [technet.tmaxsoft.com](http://technet.tmaxsoft.com) 제우스 및 웹투비를 설치합니다. ---------------- ##### 3. 라이센스 발급 서버를 실행시키기 위한 진행 과정중 라이센스 발급을 진행하여야 합니다. 다운로드 페이지에 보면 데모라이센스 발급이 있습니다. 데모라이센스 발급절차에 각 상세내용을 입력하게 되는데 여기서 HostName은 자신의 컴퓨터명을 입력합니다. hostname - 자신의 컴퓨터 명 (모를시엔 시작-실행-cmd-hostname 을 입력 하면 알려줍니다.) 라이센스를 발급받은 후엔 라이센스 폴더에 발급받은 파일을 복사합니다. ---------------- ##### 4. http.m 컴파일 http.m 파일은 conf폴더에 있습니다. 아래 명령어로 컴파일을 진행합니다. ###### cmd-wscfl -i http.m 컴파일을 하는데 권한이슈로 인해 액세스가 거부될수 있으니 명령프롬프트를 관리자 모드로 실행시킵니다. ---------------- ##### 5. 실행 명령프롬프트 창에 wsboot를 입력하여 서버를 실행합니다. 서버가 실행되면 [localhost:8080](http://localhost:8080) 을 입력해서 확인 할 수 있습니다. 로컬경로를 http.m에 기재되어 있는 DOCROOT 와 같습니다. ###### C:/TmaxSoft/WebtoB4.1/docs <file_sep>/게시판만들기/c-cgi-mysql 게시판 만들기/cgi-bin/test/array_test.c #include <stdio.h> int main(void){ char arr[4][17] = {"Korea", "Brazil", "Germany", "papua new Guinea"}; char *ct[] = {"Korea", "Brazil", "Germany", "papua new Guinea"}; printf("na[2] : %s \n", arr[2]); printf("na[2][3] : %c \n", arr[2][3]); printf("ct[2] : %s \n", ct[2]); printf("ct[2][3] : %c \n", ct[2][3]); return 0; }<file_sep>/java/god_of_java/Vol.2/05. 자바랭 다음으로 많이 쓰는 애들은 컬렉션-Part1(List)/ManageHeight.java import java.util.ArrayList; public class ManageHeight { public static void main(String[] args) { ManageHeight sample=new ManageHeight(); sample.setData(); for (int loop=1;loop<6 ;loop++ ) { //sample.printHeight(loop); sample.printAverage(loop); } } ArrayList<ArrayList<Integer>> gradeHeights = new ArrayList<ArrayList<Integer>>(); public void setData(){ ArrayList<Integer> list1=new ArrayList<Integer>(); list1.add(170); list1.add(180); list1.add(173); list1.add(175); list1.add(177); ArrayList<Integer> list2=new ArrayList<Integer>(); list2.add(160); list2.add(165); list2.add(167); list2.add(186); ArrayList<Integer> list3=new ArrayList<Integer>(); list3.add(158); list3.add(177); list3.add(187); list3.add(176); ArrayList<Integer> list4=new ArrayList<Integer>(); list4.add(173); list4.add(182); list4.add(181); ArrayList<Integer> list5=new ArrayList<Integer>(); list5.add(170); list5.add(180); list5.add(165); list5.add(177); list5.add(172); gradeHeights.add(list1); gradeHeights.add(list2); gradeHeights.add(list3); gradeHeights.add(list4); gradeHeights.add(list5); } public void printHeight(int classNo){ ArrayList<Integer> classHeight = gradeHeights.get(classNo -1); System.out.println("classNo = "+classNo); for(int tempArr: classHeight){ System.out.println(tempArr); } System.out.println(); } public void printAverage(int classNo){ ArrayList<Integer> classAverage = gradeHeights.get(classNo -1); System.out.println("Class No. : "+classNo); double sum=0; for(int tempArr:classAverage){ sum += tempArr; } int count = classAverage.size(); System.out.println("Height average : "+sum/count); } } <file_sep>/php/10. 형변환.md ## 10. 형변환 #### 10.01 PHP의 자료형 PHP는 현재 버전 기준으로 다음의 자료형을 가지고 있다. - Stirng - Integer - Float [ floating point numbers - also called double ] - Boolean - Array - Object - NULL - Resource ── 자료형 테스트 코드 ── ```php $a = "apple juice"; var_dump($a); $b = 10; var_dump($b); $c = 3.141592; var_dump($c); $d = true; var_dump($d); $e = array(); var_dump($e); $f = new BlogExample(); var_dump($f); $g = NULL; var_dump($g); $h = mysql_connect('localhost','test','test'); var_dump($h); $i = mysql_query('show databases'); var_dump($i); ``` ───────────────────실행결과──────────────────── string(11) "apple juice" int(10) float(3.141592) bool(true) array(0) { } object(BlogExample)#1 (0){ } NULL resource(3) of type (mysql link) resource(4) of type (mysql result) #### 10.02 PHP 자동 자료형 변환 (Type Juggling) - PHP를 배우면서, 잘 모르면 쉽고, 알면 정말 어려운 것이 Type Juggling 이다. - 자동자료형변환은 아래와 같이 다양한 단어로 부를수 있다. `Type Juggling = 자동 자료형변환 = Auto Typecasting = Implicit Typecasting` 변수 정의(memory allocation), 변수에 값 할당(assign), 변수 연산(operation)을 하기 위해서는 DataType 정의가 필수적이다. PHP는 안될 것 같은 연산들도 Type Juggling을 해서 되게 만드는 것이 꽤나 있다. 이러한 동작은 Javascript에서도 동일하게 동작한다. 이 어려운 동작을 다른 언어에서도 채용하는 추세라서 알아두는 것이 좋을 것이다. 이것저것 해보고 경험을 통해 Type Juggling을 체득하여야 한다. C언어에도 폭 넓지는 않지만 이미 Type Juggling이 있긴 하다. ```java int i=1; while(1){ if(i>120) break; i++; } ``` if및 while구문에서 괄호 안에는 boolean값이 나와야 한다. 1은 boolean값이 아니기 때문에 자동형변환이 일어난다. 1은 true로 변환되고, 2도 true로 변환되고 0은 false로 변환된다. 즉, 0이외의 값은 true이다. 이에 대하여 엄청난 Type Juggling을 하는 PHP는 while(1), while(true),while('hello'),while(object 변수),while(resource 변수) 모두 동일한 동작을 한다. 다른 예제를 살펴보자 이번엔 boolean이 아니라 integer로 변환할 것이다. ```php $_GET['countdown'] = '10'; $my_countdown = $_GET['countdown']; for($i = $my_countdown; $i>=0; $i--){ var_dump($i); echo $i."gogo!\n\n"; } ``` ─────────────────실행결과──────────────────── ``` string(2) "10" 10 gogo! int(9) 9 gogo! int(8) 8 gogo! int(7) 7 gogo! int(6) 6 gogo! int(5) 5 gogo! int(4) 4 gogo! int(3) 3 gogo! int(2) 2 gogo! int(1) 1 gogo! int(0) 0 gogo! ``` 먼저 $my_countdown에는 string형 10이 저장되어 있다. $i에 $my_countdown을 할당했으니 , $i에도 string형 10이 저장되어 있다. $i>=0 구문을 만나면 비교 연산자 이기 때문에, '10'>=0 이 된다. string이 integer로 변환되고 integer형 10으로 바뀐후 비교를 한다. 변환 연산을 위해서 임시로 변한 것일 뿐 해당 값에는 변화가 없다. 즉 intval('10')>=0이 실행된 것이다. echo문을 만나면 $i가 string 10인 경우를 제외하고는 echo strval($i)." gogo!"가 실행된 것이다. 구문을 실행한 후 $i-구문을 만나면 이때에는 int형으로 변환된 9가 저장된다. 즉 $i = intval('10)-1이 실행 된 것이다. ```php $_GET['dollar'] = '150달러'; $my_dollar = $_GET['dollar']; $my_won = $my_dollar * 1100; echo 'KRW : ' . $my_won . 'WON'; ``` ───────────────실행결과─────────────── ``` KRW : 165000 WON ``` 위의 예제는 $my_won = intval($my_dollar)*1100;이라는 구문으로 변환되어 실행되어 버린다. `intval('150 달러')는 integer형 150과 같다.` ##### ** 참고 ** : 형변환 ```php - 값을 정수형으로 변환 - intval(값) - (int)$변수명 - 값을 문자열로 변환 - strvar(값) - (string)$변수명 - object로 형변환 - (object)$변수명 - array로 형변환 - (array)$변수명 - NULL로 형변환 - (unset)$변수명 ``` <file_sep>/Front-End/gulp/src/js/libs/DOMHelper/nextEl.js /* domhelper-nextEl.js */ function nextEl(el) { if (!el.nextElementSibling) { el = el.nextElementSibling; } else { do { el = el.nextSibling; } while(el && el.nodeType != 1); } return el; }<file_sep>/Front-End/HTML Template/README.md ## jQuery Plug-in ### Accodian ### slide ## CSS Naming Guide ### id/class 규칙 - **id** : Camelcase 방식 - **class** : under_score 방식 - **helper-class** : hyphen 방식 - **HTML5 사용자 정의 attribute** : hyphen 방식 > 예) ```java <div id="boardView"> <div class="board_view"> <div class="text-overflow"> <div data-target="board-list"> ``` ### prefix/subfix/suffix 정의 #### prefix : 접두사, 주로 형태를 나타내는데 사용한다. - 기본 프리픽스는 형태별로 통일 - 서브프리픽스가 필요한경우 `_`(underscore)로 구분하여 표기 `(btn / btn_dash)` | 분류 | prefix | 설명 | |--------|--------|---------| | 타이틀 | tit | 각종 타이틀 | | 영역 | section | h1~h6 태그를 지닌 영역구분 | | 영역 | wrap | 요소들의 묶음 | | 영역 | inner | 부모 wrap이 존재하며 자식 묶음이 별도로 필요할경우 사용 | | 네비게이션 | gnb | 전체 메뉴목록 (글로벌) | | 네비게이션 | lnb | 지역 네비게이션 (페이지별 메뉴) | | 네비게이션 | snb | 사이드 네비게이션(일반적으로 좌측메뉴) | | 폼 | tf | textfield (input 타입 text / textarea ) | 폼 | inp | input 타입 radio, checkbox file | 폼 | opt | selectbox | 탭 | tab | 일반적인 탭 | 테이블 | tbl | 테이블 클래스 부여시 | 목록 | list | ul,ol 등의 목록 | 버튼 | btn | 버튼 | 박스 | box | 박스모델 | 배경 | bg | 배경 관련 | 썸네일 | thumb | 썸네일 이미지 | 텍스트 | txt | 일반텍스트 | 텍스트 | num | num1, num2...숫자 사용시 `_`언더스코어 사용하지 않는다 | 강조 | emph | 강조할 항목 | 링크 | link | 일반링크 | 링크 | link_more | 더보기 링크 | 순서 | fst, mid, lst | 일반링크 | 상세내용 | desc | 배경이미지(IR 기법시에도 사용가능) #### subfix : 하부 기호로서 subfix는 prefix와 함께 부가설명 용도로만 사용 ```css ex) ico_arr_news.jpg ``` | 분류 | subfix | 설명 | |--------|--------|---------| | 공용 | comm | 전역으로만 사용 | | 위치 | top/mid/bot/left/right | 위치를 표시 | | 순서변화 | fst / lst | 이벤트 제어시 주로 사용 | | 버튼상태변화 | nor | 이벤트 제어시 사용 | #### subfix : 접미사, prefix와 함께 부가설명 용도로만 사용하며 주로 `상태`를 나타내는데 사용 ```java ex) btn_confirm_on, btn_prev, btn_next ``` | 분류 | subfix | 설명 | |--------|--------|---------| | 상태변화 | _on / _off / _over / _hit / _focus | 주로 마우스, 키보드 이벤트 | | 위치변화 | _top / _mid / _bot / _left / _right | js animation | | 순서변화 | _fst / _lst | 이벤트 제어시 주로 사용 | | 이전/다음 | _prev / _next | 버튼의 상태에 주로 사용 | <file_sep>/php/09.3 파일-파일 업로드.md ## 파일 - 파일 업로드 ** << 목록 >> ** 1. 파일 업로드 --------------- ##### 파일 업로드 <br> 파일 올리는 예제 ```xml << upload.php >> <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> </head> <body> <form enctype="multipart/form-data" action="il.php" method="POST"> <input type="hidden" name="MAX_FILE_SIZE" value="30000" /> <input name="userfile" type="file" /> <input type="submit" value="upload" /> </form> </body> </html> ``` <br> 파일 검사하는 예제 ```xml << il.php >> <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> </head> <body> <?php ini_set("display_errors", "1"); $uploaddir = 'C:\Apache2\htdocs\file\\'; $uploadfile = $uploaddir . basename($_FILES['userfile']['name']); echo '<pre>'; if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) { echo "파일이 유효하고, 성공적으로 업로드 되었습니다.\n"; } else { print "파일 업로드 공격의 가능성이 있습니다!\n"; } echo '자세한 디버깅 정보입니다:'; print_r($_FILES); // print_r은 변수에 대한 정보를 사람이 읽을 수 있는 방법으로 표시한다. print "</pre>"; ?> </body> </html> ``` <file_sep>/java/java_web_develop_workBook/README.md # 열혈강의 자바 웹 개발 워크북 ## 1. 웹 애플리캐이션의 이해 1. 데스크톱 애플리케이션 2. 클라이언트 - 서버 애플리케이션 3. 다중 클라이언트의 요청 처리 4. 클라이언트 , 서버 아키텍쳐의 진화 5. 웹 애플리케이션 아키텍쳐의 특징 6. 정리 ## 2. 웹 프로그래밍 기초 다지기 1. HTTP 프로토콜의 이해 2. GET 요청 3. POST 요청 4. 파일 업로드 5. 정리 ## 3. 서블릿 프로그래밍 1. CGI 프로그램과 서블릿 2. 서블릿, JSP vs. Java EE vs. WAS 3. 웹 프로젝트 준비 4. 서블릿 만들기 5. 웹 애플리케이션 배치 6. GenericServlet의 사용 7. 정리 ## 4. 서블릿과 JDBC 1. 데이터베이스에서 데이터 가져오기 2. HttpServlet으로 GET 요청 다루기 3. HttpServlet으로 POST 요청 다루기 4. 요청 매개변수의 한글 깨짐 처리 5. 리프래시 6. 리다이렉트 7. 서블릿 초기화 매개변수 8. 컨텍스트 초기화 매개변수 9. 필터 사용하기 10. 정리<file_sep>/guide/android/android.MD # 안드로이드 ## 1. 자바 파일 구조 및 설명 #### 설정(config) |폴더 |파일명 |설명 | |-----------|-------------------|---------------------| |`gradle` |`bulid` |앱 gradle(환경정보)| |`manifest` |`AndroidManifest` |앱 메니페스트(환경정보) | |`common` |`AppNetwork` |네트워크 체크 | |`common` |`AppApplication` |애플리케이션 설정 | |`common` |`AppPreference` |프리퍼런스 설정 | |`common` |`Constant` |공통 상수 정의 | |`common` |`SiteUrl` |웹 url 정의 | ----------------------------------------------------- #### 액티비티(activity) |폴더 |파일명 |설명 | |-----------|-------------------|---------------------| |`common` |`ShortCutActivity` |바탕화면 바로가기 | |`setting` |* |설정 | | |`BaseActivity` |기본이 되는 액티비티 | | |`IntroActivity` |인트로 액티비티 | | |`WebActivity` | 웹 액티비티 | ----------------------------------------------------- #### 뷰(view) |폴더 |파일명 |설명 | |-------|-------------------|------------------ | | |`AppTextView` |텍스트 폰트적용| | |`AppWebView` |웹뷰 | | |`MainGnbView` |메인 GNB | | |`MainTopView` |메인 상단 | | |`ToggleMenuView` |토글메뉴 | | |`WebTopView` |웹 뷰 상단 | ----------------------------------------------------- #### 유틸(util) |폴더 |파일명 |설명 | |-----------|-------------------|---------------------| |`util` |`JavaScriptBuilder` | 자브스크립트 코드 자동맞춤 생성| ----------------------------------------------------- #### 자바스크립트 통신관련 |폴더 |파일명 |설명 | |-----------|-------------------|---------------------| |`web` |`JavaScriptClientInterface` |자바스크립트 연동 인터페이스 정의| |`web` |`JavaScriptWebInterface` |자바스크립트 연동 인터페이스 정의| ----------------------------------------------------- ## 2. 리소스 파일 구조 및 설명 #### drawable(이미지) #### layout(뷰) #### anim(슬라이드 애니메이션) 액티비티 이동시 슬라이드 효과 |파일명 |설명 | |---------------------------|-------| |`anim_slide_in_bottom` || |`anim_slide_in_left` || |`anim_slide_in_right` || |`anim_slide_in_top` || |`anim_slide_out_bottom` || |`anim_slide_out_left` || |`anim_slide_out_right` || |`anim_slide_out_top` || ----------------------------- #### value 값 정의 |파일명 |설명 | |---------------|--------| |`attrs` |설정 정의| |`colors` |색상 정의| |`dimens` |거리 정의| |`string` |문자 정의| |`style` |테마 정의| -------------------------- <file_sep>/javascript/inside_javascript/README.md #인사이드 자바스크립트 ## 1. 자바스크립트 기본개요 ## 2. 자바스크립트 개발 환경 ## 3. 자바스크립트 데이터 타입과 연산자 ## 4. 함수와 프로토타입 체이닝 ## 5. 실행 컨넥스트와 클로저 ## 6. 객체지향 프로그래밍 ## 7. 함수형 프로그래밍 <file_sep>/javascript/inside_javascript/chapter05 실행 컨텍스트와 클로저/README.md ## 5. 실행 컨텍스트와 클로저 살펴볼 내용 1. 실행컨텍스트의개면 2. 활성객체와 변수객체 3. 스코프체인 4. 클로저 ### 5.1 실행 컨텍스트 개념 ECMAScript 에서는 실행 컨텍스트를 **"실행 가능한 코드를 형상화하고 구분하는 추상적인 개념"**으로 기술한다. 이를 **콜스택**과 연관하여 정의하면 **"실행 가능한 자바스크립트 코드 블록이 실행되는 환경"**이라고 할 수 있고, 이 컨텍스트 안에 실행에 필요한 여러가지 정보를 담고 있다. 여기서 말하는 실행 가능한 코드 블록은 대부분의 경우 함수가 된다. ECMAScript 에서는 실행 컨텍스트가 형성되는 경우를 세가지로 규정하고 있는데, - 전역코드 - `eval()`함수로 실행되는 코드 - 함수 안의 코드를 실행할 경우 대부분의 프로그래머는 함수로 실행 컨텍스트를 만든다. 그리고 이 코드 블록 안에 변수 및 객체, 실행 가능한 코드가 들어있다. 이 코드가 실행되면 실행컨텍스트가 생성되고, 실행 컨텍스트는 스택 안에 하나씩 차곡차곡 쌓이고, 제일 위에 위치하는 실행 컨텍스트가 현재 실행되고 있는 컨텍스트다. ECMAScript 는 실행 컨텍스트의 생성을 다음처럼 설명한다. > "현재 실행되는 컨텍스트에서 이 컨텍스트와 관련 없는 실행 코드가 실행되면, 새로운 컨텍스트가 생성되어 스택에 들어가고 제어권이 그 컨텍스트로 이동한다." ```javascript console.log("This is global context"); function ExContext1() { console.log("This is ExContext1"); }; function ExContext2() { ExContext1(); console.log("This is ExContext2"); }; ExContext2(); ``` > 출력결과 ``` This is global context This is ExContext1 This is ExContext2 ``` ### 5.2 실행 컨텍스트 생성 과정 알아볼내용 - 활성 객체와 변수 객체 - 스코프 체인 ```javascript function execute(param1, param2) { var a = 1, b = 2; function func() { return a+b; } return param1+param2+func(); } execute(3, 4); ``` #### 5.2.1 활성 객체 생성 실행 컨텍스트가 생성되면 자바스크립트 엔진은 해당 컨텍스트에서 실행에 필요한 여러가지 정보를 담을 객체를 생성하는데, 이를 활성 객체라고 한다. 이 객체에 앞으로 매개변수나 사용자가 정의한 변수 및 객체를 저장하고, 새로 만들어진 컨텍스트로 접근 가능하게 되어있다. #### 5.2.2 arguments 객체 생성 다음 단계에서는 arguments 객체를 생성한다. 앞서 만들어진 활성 객체는 arguments 프로퍼티로 이 arguments 객체를 참조한다. #### 5.2.3. 스코프 정보 생성 현재 컨텍스트의 유효범위를 나타내는 스코프 정보를 생성한다. 이 스코프 정보는 현재 실행 중인 실행 컨텍스트 안에서 연결리스트와 유사한 형식으로 만들어진다 현재 컨텍스트에서 특정 변수에 접근해야 할 경우, 이 리스트를 활용한다. 이 리스트를 스코프 체인이라고 하는데 `[[scope]]`프로퍼티로 참조된다. 더 자세한 사항은 이후에 알아보고 여기서는 현재 생성된 활성 객체가 스코프 체인의 제일 앞에 추가되며, 예제의 `excute()`함수의 인자나 지역변수 등에 접근할 수 있다는 것만 알고 넘어가자 #### 5.2.4 변수 생성 현재 실행 컨텍스트 내부에서 사용되는 지역 변수의 생성이 이루어진다. 변수 객체 안엣 호출된 함수 인자는 각각의 프로퍼티가 만들어지고 그 값이 할당된다. 여기서 주의할 점은 이 과정에서는 변수나 내부 함수를 단지 메모리에 생성하고, 초기화는 변수나 함수에 해당하는 표현식이 실행되기 전가지는 이루어지지 않는다는 점이다. 표현식의 실행은 변수 객체 생성이 다 이루어진 후 시작된다. #### 5.2.5 this 바인딩 마지막 단게에서는 this 키워드를 사용하는 값이 할당된다. 여기서 this가 참조하는 객체가 없으면 전역 객체를 참조한다. #### 5.2.6 코드실행 이렇게 하나의 실행 컨텍스트가 생성되고, 변수 객체가 만들어진 후에, 코드에 있는 여러가지 표현식 실행이 이루어진다. 이렇게 실행되면서 변수의 초기화 및 연산, 또 다른 함수 실행 등이 이루어진다. 예제에서 undefined가 할당된 변수 a와 b에도 이 과정에서 1,2의 값이 할당된다. --- ### 5.3 스코프 체인 - 자바스크립트 코드를 이해하려면 스코프 체인의 이해는 필수적이다. - 이를 알아야, 변수에 대한 인식 메커니즘을 알 수 있고, 현재 사용되는 변수가 어디에서 선언된 변수인지 정확히 알 수 있기 때문이다. - 프로토타입 체인과 거의 비슷한 메커니즘 이므로 참고하자 자바스크립트도 다른 언어와 마찬가지로 스코프, 즉 유효범위가 있다. 단 다른 언어처럼 `{}` 로 묶여있는 범위 안에서 선언된 변수는 `{}`가 끝나는 순간 사라지고 밖에서는 접근할 수 가 없지만 자바스크립트에서는 함수내의 `{}` 이를테면 `for(){}`, `if{}`와 같은 구문은 유효범위가 없다. 오직 함수만이 유효범위의 한 단위가 된다. > 이 유효 범위를 나타내는 스코프가 [[scope]]프로퍼티로 각 함수 객체 내에서 연결 리스트 형식으로 관리되는데, > 이를 스코프 체인이라고 한다. 스코프 체인은 각 실행 컨텍스트의 변수 객체가 구성 요소인 리스트와 같다. **각각의 함수는 [[scope]]프로퍼티로 자신이 생성된 실행 컨텍스트의 스코프 체인을 참조한다.** 함수가 실행되는 순간 실행 컨텍스트가 만들어지고, **이 실행 컨텍스트는 실행된 함수의 [[scope]]프로퍼티를 기반으로 새로운 스코프 체인을 만든다.** #### 5.3.1 전역 실행 컨텍스트의 스코프 체인 ```javascript var var1 = 1; var var2 = 2; console.log(var1); //출력값 1 console.log(var2); //출력값 2 ``` > 위 예제는 전역코드이다. 함수선언및 호출이 없고, 실행 가능한 코드들만 나열되어 있다. 이 코드를 실행하면, 먼저 전역 실행 컨텍스트가 생성되고, 변수 객체가 만들어진다. 이 변수 객체의 스코프 체인은 어떻게 될까? 현재 전역 실행 컨텍스트 단 하나만 실행되고 있어 참조할 상위 컨텍스트가 없다. 자신이 최상위에 위치하는 변수 객체인 것이다. 따라서, 이 변수 객체의 스코프 체인은 자기 자신만을 가진다. 다시 말해 변수 객체의 [[scope]]는 변수객체 자신을 가리킨다. #### 5.3.2 함수를 호출한 경우 생성되는 실행 컨텍스트의 스코프 체인 ```javascript var var1 = 1; var var2 = 2; function func() { var var1 = 10; var var2 = 20; console.log(var1); // 10 console.log(var2); // 20 } func(); console.log(var1); // 1 console.log(var2); // 2 ``` 위 예제를 실행하면 전역 실행 컨텍스트가 생성되고, func() 함수 객체가 만들어진다. > 이 함수 객체의 [[scope]]는 어떻게 될까? 함수 객체가 생성될 때, 그 함수 객체의 [[scope]]는 현재 실행되는 컨텍스트의 변수 객체에 있는 [[scope]를 그대로 가진다. 따라서, func 함수 객체의 [[scope]]는 전역 변수 객체가 된다. 정리해보자 - 각 함수 객체는 [[scope]]프로퍼티로 현재 컨텍스트의 스코프 체인을 참조한다. - 한 함수가 실행되면 새로운 실행 컨텍스트가 만들어지는데, 이 새로운 실행 컨텍스트는 잣니이 사용할 스코프 체인을 다음과 같은 방법으로 만든다. - 현재 실행되는 함수 객체의[[scope]]프로퍼티를 복사하고, 새롭게 생성된 변수 객체를 해당 체인의 제일 앞에 추가한다. - 요약하면 스코프 체인은 다음과 같이 표현할 수 있다. > 스코프 체인 = 현재 실행 컨텍스트의 변수객체 + 상위 컨텍스트의 스코프 체인 ```javascript var value = "value1"; function printValue() { return value; } function printFunc(func) { var value = "value2"; console.log(func()); } printFunc(printValue); ``` > 위 예제의 결과를 예측해보자. 각 함수 객체가 처음 생성될 때 [[scope]]는 전역 객체의 [[scope]]를 참조한다. 따라서 각 함수가 실행될 때 생성되는 실행 컨텍스트의 스코프 체인은 전역 객체와 그 앞에 새롭게 만들어진 변수 객체가 추가된다. > 지금까지 실행 컨텍스트가 만들어지면서 스코프 체인이 어떻게 형성되는지 살펴보았다. 이렇게 만들어진 스코프체인으로 식별자 인식이 이루어진다. 식별자 인식은 스코프체인의 첫번째 변수 객체부터 시작한다. 식별자와 대응되는 이름을 가진 프로퍼티가 있는지를 확인한다. 첫번째 객체에 대응되는 프로퍼티를 발견하지 못하면, 다음 객체로 이동하여 찾는다. 이런식으로 프로퍼티를 찾을 때 까지 계속된다. --- ### 5.4 클로저 #### 5.4.1 클로저의 개념 > 우선 예제를 통해 살펴보자 ```javascript function outerFunc(){ var x=10; var innerFunc = function(){console.log(x);} return innerFunc; } var inner = outerFunc(); inner(); //10 ``` `innerFunc()`은 `outerFunc()`의 실행이 끝난 후 실행된다. 그렇다면 outerFunc 실행 컨텍스트가 생성되는 것인데, innerFunc()의 스코프 체인은 outerFunc 변수객체를 여전히 참조할 수 있을까? outerFunc 실행 컨텍스트는 사라졌지만, outerFunc 변수 객체는 여전히 남아있고, innerFunc의 스코프 체인으로 참조되고있다. > 이것이 바로 자바스크립트에서 구현한 클로저라는 개념이다. 되돌아보는 의미에서 다시한번 정리를 해보자면 - 자바스크립트의 함수는 일급 객체로 취급된다. - 이는 함수를 다른함수의 인자로 넘길 수도 있고, return으로 함수를 통째로 반환받을 수도 있음을 의미한다. 여기서 최종반환되는 함수가 외부 함수의 지역변수에 접근하고 있다는 것이 중요하다. 이 지역변수에 접근하려면, 함수가 종료되어 외부 함수의 컨텍스트가 반환되더라도 변수 객체는 반환되는 내부 함수의 스코프 체인에 그대로 남아있어야만 접근할 수 있다. 이것이 바로 `클로저`다 조금 쉽게 풀어 말하면 > #### 이미 생명 주기가 끝난 외부 함수의 변수를 참조하는 함수를 클로저라고 한다. 위의 에제에서는 outerFunc에서 선언된 `x`를 참조하는 `innerFunc`가 클로저가 된다. 그리고 클로저로 참조되는 외부 변수 즉, outerFunc의 `x`와 같은 변수를 `자유변수`라고 한다. > 다른 예제를 살펴보자 ```javascript function outerFunc(arg1, arg2){ var local=8; function innerFunc(innerArg){ console.log((arg1+arg2)/(innerArg + local)); } return innerFunc; } var exam1 = outerFunc(2,4); exam1(2) ``` #### 5.4.2 클로저의 활용 - 클로저의 개념을 이해했다면, 이제 이 클로저를 어떻게 활용할 것인지 고민해야 한다. - 클로저는 성능적인 면과 자원적인 면에서 약간 손해를 볼 수 있으므로 무차별적으로 사용해서는 안된다. - 클로저를 잘 활용하려면 경험이 가장 중요하게 작용한다. ##### 5.4.2.1 특정함수에 사용자가 정의한 객체의 메서드 연결하기 ```javascript function HelloFunc(funcc){ this.greeting = "hello"; } HelloFunc.prototype.call = function(func){ func ? func(this.greeting) : this.func(this.greeting); } var userFunc = function(greeting){ console.log(greeting); } var objHello = new HelloFunc(); objHello.func = userFunc; objHello.call(); ``` > `Hellofunc()`는 greeting만을 인자로 넣어 사용자가 인자로 넘긴 함수를 실행시킨다. > 그래서 사용자가 정의한 함수도 한 개의 인자를 받는 함수를 정의할 수 밖에 없다. > 여기서 사용자가 원하는 인자를 더넣어서 HelloFunc()를 이용하여 호출하려면 어떻게 해야 할까? ```javascript function saySomething(obj, methodName, name) { return (function(greeting) { return obj[methodName](greeting, name); }); } function newObj(obj, name) { obj.func = saySomething(this, "who", (name || "everyone")); return obj; } newObj.prototype.who = function(greeting, name) { console.log(greeting + " " + (name || "everyone") ); } var obj1 = new newObj(objHello, "zzoon"); obj1.call(); ``` > 앞 에제는 정해진 형식의 함수를 콜백해주는 라이브러리가 있을 경우, > 그 정해진 형식과는 다른 형식의 사용자 정의 함수를 호출할 때 유용하게 사용된다. > 예를 들어 브라우저에서는 onclick, onmouseover와 같은 프로퍼티에 해당 이벤트 핸들러를 사용자가 정의해 놓을 수가 있는데, > 이 이벤트 핸들러의 형식은 `function(event){}`이다. 이를 통해 브라우저는 발생한 이벤트를 event인자로 사용자에게 넘겨주는 방식이다. > 여기에 event 외의 원하는 인자를 더 추가한 이벤트 핸들러를 사용하고 싶을 때, 앞과 같은 방식으로 클로저를 적절히 활용해 줄 수 있다. ##### 5.4.2.2. 함수의 캡슐화 다음과 같은 함수를 작성한다고 가정해보자 `"i am XXX. I live in XXX. i'am XX years old" 라는 문장을 출력하는데, XX 부분은 사용자에게 인자로 입력받아 값을 출력하는 함수` 가장 먼저 생각해볼수 있는것은 위의 문장 템플릿을 전역 변수에 저장하고, 사용자의 입력을 받은 후, 이 전역 변수에 접근하여 완성된 문장을 출력하는 방식으로 함수를 작성하는 것이다. > 이 방식으로 구현한 코드느느 다음과 같다. ```javascript var buffAr = [ 'I am ', '', '. I live in ', '', '. I\'am ', '', ' years old.', ]; function getCompletedStr(name, city, age){ buffAr[1] = name; buffAr[3] = city; buffAr[5] = age; return buffAr.join(''); } var str = getCompletedStr('zzoon', 'seoul', 16); console.log(str); ``` 위 에제코드는 정상적으로 작동하지만, 단점이 있다. 바로 `buffAr`이라는 매열은 전역 변수로서, 외부에 노출되어 있다는 점이다. 이는 곧 다른 함수에서 이 배열에 쉽게 접근하여 값을 바꿀 수도 있고, 실수로 같은 이름의 변수를 만들어 버그가 생길수도 있다. 특히 다른코드와의 통합 혹은 이 코드를 라이브러리로 만들려고 할 때, 문제를 발생시킬 가능성이 있다. > 이 경우 클로저를 활용하여 `buffAr`을 추가적인 스코프에 넣고 사용하게 되면, 이 문제를 해결할 수 있다 ```javascript var getCompletedStr = (function(){ var buffAr = [ 'I am ', '', '. I live in ', '', '. I\'am ', '', ' years old.', ]; return (function(name, city, age) { buffAr[1] = name; buffAr[3] = city; buffAr[5] = age; return buffAr.join(''); }); })(); var str = getCompletedStr('zzoon', 'seoul', 16); console.log(str); ``` 위 코드에서 가장먼저 주의해서 봐야할 점은 변수 `getCompletedStr`에 익명의 함수를 즉시 실행시켜 반환되는 함수르르 할당하는 것이다. 이 반환되는 함수가 클로저가 되고, 이 클로저는 자유변수 buffAr을 스코프체인에서 참조할 수 있다. ##### 5.4.2.3 setTimeout()에 지정되는 함수의 사용자 정의 setTimeout 함수는 웹 브라우저에서 제공하는 함수인데, 첫번째 인자로 넘겨지는 함수 실행의 스케쥴링을 할 수 있다. 두번재 인자인 밀리 초 단위 숫자만큼의 시간 간격으로 해당 함수를 호출한다. 자신의 코드를 호출하고 싶다면 첫 번째 인자로 해당 함수 객체의 참조를 넘겨주면 되지만, 이것으로는 실제 실행될 때 함수에 인자를 줄 수 없다. 그렇다면 자신이 정의한 함수에 인자를 넣어줄 수 있게 하려면 어떻게 해야 할까? 이역시 클로저로 해결할 수 있다. ```javascript function callLater(obj, a, b) { return (function(){ obj["sum"] = a + b; console.log(obj["sum"]); }); } var sumObj = { sum : 0 } var func = callLater(sumObj, 1, 2); setTimeout(func, 500); ``` 사용자가 정의한 함수 callLater를 setTimeout 함수로 호출하려면, 변수 func에 함수를 반환받아 setTimeout()함수의 첫번째 인자로 넣어주면 된다. 반환받는 함수는 당연히 클로저고, 사용자가 원하는 인자에 접근할 수 있다. #### 5.4.3 클로저를 활용할 때 주의 사항 지금까지 클로저의 개념과 활용을 알아봤는데, 앞서 언급한대로 클로저는 자바스크립트의 강력한 기능이지만, 너무 남발하여 사용하면 안된다. 클로저에서 사용자가 쉽게 간과할 수 있는 사항을 알아보자 ##### 5.4.3.1. 클로저의 프로퍼티값이 쓰기 가능하므로 그값이 여러 번 호출로 항상 변할 수 있음에 유의해야 한다. ```javascript function outerFunc(argNum){ var num = argNum; return function(x){ num += x; console.log('num: '+num); } } var exam=outerFunc(40); exam(5); exam(-10); ``` > 자유변수 num의 값이 계속해서 변화하는걸 볼수 있다. ##### 5.4.3.2. 하나의 클로저가 여러 함수 객체의 스코프 체인에 들어가 있는 경우도 있다. ```javscript function func(){ var x =1; return{ func1 : function(){console.log(++x);}, func2 : function(){console.log(-x);} }; }; var exam = func(); exam.func1(); exam.func2(); ``` > 반환되는 객체에는 두 개의 함수가 정의되어 있는데, 두 함수 모두 자유 변수 `x`를 참조한다. > 그리고 각각의 함수가 호출될 때마다 x 값이 변화하므로 유의해야 한다. ##### 5.4.3.3 루프 안에서 클로저를 활용할 때는 주의하자 ```javascript function countSeconds(howMany) { for (var i = 1; i <= howMany; i++) { setTimeout(function () { console.log(i); }, i * 1000); } }; countSeconds(3); ``` > 위 예제는 1,2,3 을 1초 간격으로 출력하는 의도로 만든 예제다. > 하지만 결과는 4가 연속 3번 1초 간격으로 출력된다. setTimeout 함수의 ㅇ니자로 들어가는 함수는 자유변수 `i`를 참조한다. 하지만 이 함수가 실행되는 시점은 countSecondes() 함수의 실행이 종료된 이후이고, i값은 이미 4가 된 상태이다. 그러므로 setTimeout()로 실행되는 함수는 모두 4를 출력하게 된다 > 그럼 이제 원하는 결과를 얻기 위해 코드를 수정해 보자 ```javascript function countSeconds(howMany) { for (var i = 1; i <= howMany; i++) { (function (currentI){ setTimeout(function(){ console.log(currentI); }, currentI * 1000); }(i)); } }; countSeconds(3); ``` > 즉시 실행 함수를 실행시켜 루프 `i`값을 currentI에 복사해서 setTimeout()에 들어갈 함수에서 사용하면, 원하는 결과를 얻을 수 있다. <file_sep>/게시판만들기/struts1 게시판 만들기/bbs2/SQL/board.SQL create table jsp_board( idx number primary key, writer varchar2(25), email varchar2(30), homepage varchar2(50), pwd varchar2(20), subject varchar2(200), content varchar2(2000), writedate date, readnum number, filename varchar2(200), filesize number, refer number, lev number, sunbun number ); create sequence scott.jsp_board_idx increment by 1 start with 1 nocache; //꼬리글 테이블 create table reply( no number primary key, writer varchar2(25), pwd varchar2(20), content varchar2(1000), writedate date, readnum number, reply_idx_fk references jsp_board(idx) ); create sequence scott.reply_no increment by 1 start with 1 nocache;<file_sep>/java/java_web_develop_workBook/5장. MVC 아키텍쳐/README.md ## 5. MVC 아키텍쳐 - 서블릿의 단점을 보완하기 위해 등장한 JSP(JavaServer Page) - MVC 아키텍쳐 ### 1. MVC 이해하기 #### 올인원 방식과 문제점 지금까지의 예제는 클라이언트의 요청 처리를 서블릿 홀로 담당하는 올인원 방식이었다. - 규모가 작거나 업무 변경이 많지 않은 경우에 적합하지만, 규모가 크거나 업무 변경이 잦은 경우에는 오히려 유지보수가 어렵다. - 요즈음에 추세에 맞지 않다. #### 글로벌 환경과 MVC 아키텍쳐 - 시스템 변경이 잦은 상황에서 유지보수를 보다 쉽게 하려면, 중복 코드의 작성을 최소화 하고,코드변경이 쉬워야 한다. - 이를 위해 기존 코드의 재사용성을 높이는 방향으로 설계해야 한다. - 특히 객체지향의 특성을 십분 활용하여 좀 더 역할을 세분화하고 역할 간 의존성을 최소화한다. > MVC 구조에서는 클라이언트의 요청 처리를 서블릿 혼자서 담당하지 않고 세개의 컴포넌트가 나누어 처리한다. 1) 컨트롤러 - 클라이언트의 요청을 받았을 때 그 요청에 대해 실제 업무를 수행하는 모델 컴포넌트를 호출하는 일. - 클라이언트가 보낸 데이터가 있다면 모델을 호출할 때 전달하기 쉽게 데이터를 적절히 가공하는 일 - 모델이 업무 수행을 완료하면, 그 결과를 가지고 화면을 생성하도록 뷰에게 전달 > 즉 클라이언트 요청에 대해 모델과 뷰를 결정하여 전달하는 일을 한다. (조정자) 2) 모델 - 데이터 저장소와 연동하여 사용자가 입력한 데이터나 사용자에게 출력할 데이터를 다루는 일 - 특히 여러개의 데이터 변경 작업(추가,변경,삭제)을 하나의 작업으로 묶은 트랜잭션을 다루는 일 3) 뷰 - 모델이 처리한 데이터나 그 작업 결과를 가지고 사용자에게 출력화면을 만드는 일 - 이렇게 생성된 화면은 웹브라우저가 출력 > 뷰 컴포넌트는 `HTML`과 `CSS`, `Javascript`를 사용하여 웹브라우저가 출력할 UI를 만든다. #### MVC 이점 1) 높은 재사용성, 넓은 융통성 - 룩앤필(look and feel)을 쉽게 교체할 수 있다. - 즉 화면 생성 부분을 별도의 컴포넌트로 분리하였기 때문에, 모델에 상관없이 뷰 교체만으로 배경색이나 모양, 레이아웃, 글꼴등 사용자 화면을 쉽게 바꿀수 있다. - 원소스 멀티 유즈(one source multi use)를 구현할 수 있다. - 모델 컴포넌트가 작업한 결과를 다양한 뷰 컴포넌트를 통하여 PDF나 HTML,XML,JSON등으로 출력할 수 있다. - 코드를 재사용할 수 있다. - 면을 바꾸거나 데이터 형식을 바꾸더라도 모델 컴포넌트는 그대로 재사용 가능 2) 빠른 개발, 저렴한 비용 - 다른 프로젝트에서도 모델 컴포넌트를 재사용 할 수 있기 때문에 개발속도가 빨라진다. - ex) 자바 개발자는 컨트롤러와 모델 개발에 전념하고, JSP개발자나 HTML개발자는 뷰 개발에 전념! - 소스코드를 역할에 따라 여러 컴포넌트로 쪼개개 되면, 그 컴포넌ㅌ의 난이도에 따라 좀 더 낮은 수준의 개발자를 투입할 수 있어서 전체적인 개발 및 유지보수 비용을 줄일 수 있다. #### MVC 구동원리 1. 웹브라우져가 웹애플리케이션 실행을 요청하면, 웹 서버가 그 요청을 받아서 서블릿 컨테이너(톰캣이라던지..)넘겨준다. 서블릿 컨테이너는 URL을 확인하여 그 요청을 처리할 서블릿을 찾아서 실행 2. 서블릿은 실제 업무를 처리하는 모델 자바 객체의 메소드를 호출한다. 만약 웹 브라우저가 보낸 데이터를 변경하거나 저장해야 한다면 그 데이터를 가공하여 값 객체 (VO; Value Object)를 생성하고, 모델 객체의 메소드를 호출할 때 인자값으로 넘긴다. 모델 객체는 `엔터프라이즈 자바빈`일 수도 있고, `일반 자바 객체`일 수도 있다. 3. 모델 객체는 JDBC 를 사용하여 매개변수로 넘어온 값 객체를 데이터베이스에 저장하거나, 데이터베이스로부터 질의 결과를 가져와서 값 객체로 만들어 반환한다. 이렇게 값 객체는 객체와 객체 사이에 데이터를 전달하는 용도로 사용하기 때문에 `데이터 전송 객채(DTO; Data Transfer Object)`라고도 부른다. 4. 서블릿은 모델 객체로부터 반환받은 값을 JSP에 전달한다. 5. JSP는 서블릿으로부터 전달받은 값 객체를 참조하여 웹브라우저가 출력할 결과 화면을 만든다. 그리고 웹 브라우져에 출력함으로써 요청 처리를 완료한다. 6. 웹 브라우저는 서버로부터 받은 응답 내용을 화면에 출력한다. > MVC 구조로 만들게 되면 추가적으로 더 많은 클래스를 작성해야 하고 처리되는 절차도 복잡하다 기술문서에서는 이런경우를 '트레이드오프'라고 자주 표현한다. --- ### 2. 뷰 컴퓨넌트와 JSP MVC 아키텍쳐에서 뷰 컴포넌트를 만들 때 보통 JSP를 사용한다. #### JSP를 사용하는 이유 ```java @Override protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html; charset=UTF-8"); PrintWriter out = response.getWriter(); out.println("<html><head><title>회원 등록</title></head>"); out.println("<body><h1>회원 등록</h1>"); out.println("<form action='add' method='post'>"); out.println("이름: <input type='text' name='name'><br>"); out.println("이메일: <input type='text' name='email'><br>"); out.println("암호: <input type='password' name='password'><br>"); out.println("<input type='submit' value='추가'>"); out.println("<input type='reset' value='취소'>"); out.println("</form>"); out.println("</body></html>"); } ``` > HTML을 출력하려고 out.println()을 호출하고 있는데 상당히 복잡하다 > 이런 부분을 해소하고자 나온 기술이 `JSP`이다 #### JSP 구동 원리 - JSP기술의 가장 중요한 목적은 콘텐츠를 출력하는 코딩을 단순화하는 것이다. > 어떠한 원리로 이것이 가능한지 알아보자 1. 개발자는 서버에 JSP파일을 작성해둔다. 클라이언트가 JSP를 실행해 달라고 요청하면, 서블릿 컨테이너는 JSP파일에 대응하는 자바 서블릿을 찾아서 실행한다. 2. 만약 JSP에 대응하는 서블릿이 없거나 JSP파일이 변경되었다면, JSP엔진을 통해 JSP 파일을 해석하여 서블릿 자바 소스를 생성한다. 3. 서블릿 자바 소스는 자바 컴파일러를 통해 서블릿 클래스 파일로 컴파일 된다. JSP파일을 바꿀 때마다 이 과정을 반복한다. 4. JSP로부터 생성된 서블릿은 서블릿 구동 방식에 따라 실행된다. 즉 서블릿의 `service()`메소드가 호출되고, 출력 메소드를 통해 서블릿이 생성한 HTML화면을 웹브라우저로 보낸다. #### JSP 구동과정 확인 WebContent 폴더에 jsp파일을 생성한후 (서버에 올리고 브라우져에서 테스트)를 해보면 JSP를 실행할 때 비로소 JSP엔진은 서블릿을 만든다. > 서블릿 소스를 확인하고 싶다면 워크스페이스 폴더를 확인해보자 > .metadata/.plugins/org.eclipse.wst.server.core/tmp0 에서 쭉 따라가 보자 PHP나 파이썬등은 인터프리터 방식으로 소스를 바로 읽어서 실행하지만, JSP파일은 그 자체로 실행되지 않고 자바 서블릿 클래스로 만들어진 다음에 실행된다. 따라서 JSP가 더 빠르다... #### HttpJspPage 인터페이스 JSP 엔진은 JSP파일로부터 서블릿 클래스를 생성할 때 HttpJspPage 인터페이스를 구현하나 클래스를 만든다. > `HttpJspPage`를 구현한다는 것은 결국 `Servlet 인터페이스`도 구현한다는 것이기 때문에 해당 클래스는 서블릿이 될 수 밖에 없다. 이 인터페이스에 선언된 메소드를 알아보자 1) _jspInit() - JspPage에 선언된 `jspInit()`는 JSP 객체(JSP로부터 만들어진 서블릿 객체)가 생성될 때 호출된다. - 자동 생성된 서블릿 소스 코드를 보면 init()가 호출될 때 jspInit()를 호출하도록 코딩되어 있다. - 만약 JSP 페이지에서 init()를 오버라이딩할 일이 있다면 init() 대신 jspInit()을 오버라이딩 하면 된다. 2) _jspDestroy() - jspPage의 jspDestroy()도 마찬가지다. JSP객체(JSP로부터 만들어진 서블릿 객체)가 언로드(Unload)될 때 호출된다. - 마찬가지로 destory()를 오버라이딩 할 일이 있다면 destory()대신 jspDestroy()를 오버라이딩 하자 3)_jspService() - HttpJsppage에 선언된 _jspService()는 JSP 페이지가 해야 할 작업이 들어 있는 메소드다. - JSP파일에 작성된 대부분의 내용이 이 메소드 안으로 들어간다. - 서블릿 컨테이너가 service()를 호출하면 service()메소드 내부에서는 바로 이 메소드를 호출 함으로써 JSP 페이지에 작성했던 코드들이 실행 되는 것이다. #### JSP 객체의 실체 분석 톰캣 실행 환경의 임시배치 폴더에서 Hello.jsp로부터 생성된 자바 서블릿 소스 파일을 에디터로 확인해보자 ```java /* * Generated by the Jasper component of Apache Tomcat * Version: Apache Tomcat/7.0.65 * Generated at: 2015-11-23 01:27:07 UTC * Note: The last modified time of this file was set to * the last modified time of the source file after * generation to assist with modification tracking. */ package org.apache.jsp; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; public final class Hello_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { private static final javax.servlet.jsp.JspFactory _jspxFactory = javax.servlet.jsp.JspFactory.getDefaultFactory(); private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants; private volatile javax.el.ExpressionFactory _el_expressionfactory; private volatile org.apache.tomcat.InstanceManager _jsp_instancemanager; public java.util.Map<java.lang.String,java.lang.Long> getDependants() { return _jspx_dependants; } public javax.el.ExpressionFactory _jsp_getExpressionFactory() { if (_el_expressionfactory == null) { synchronized (this) { if (_el_expressionfactory == null) { _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory(); } } } return _el_expressionfactory; } public org.apache.tomcat.InstanceManager _jsp_getInstanceManager() { if (_jsp_instancemanager == null) { synchronized (this) { if (_jsp_instancemanager == null) { _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig()); } } } return _jsp_instancemanager; } public void _jspInit() { } public void _jspDestroy() { } public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response) throws java.io.IOException, javax.servlet.ServletException { final javax.servlet.jsp.PageContext pageContext; javax.servlet.http.HttpSession session = null; final javax.servlet.ServletContext application; final javax.servlet.ServletConfig config; javax.servlet.jsp.JspWriter out = null; final java.lang.Object page = this; javax.servlet.jsp.JspWriter _jspx_out = null; javax.servlet.jsp.PageContext _jspx_page_context = null; try { response.setContentType("text/html; charset=UTF-8"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; out.write("\r\n"); out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\r\n"); out.write("<html>\r\n"); out.write("<head>\r\n"); out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\r\n"); out.write("<title>Insert title here</title>\r\n"); out.write("</head>\r\n"); out.write("<body>\r\n"); out.write("\t<p>hello</p>\r\n"); out.write("</body>\r\n"); out.write("</html>"); } catch (java.lang.Throwable t) { if (!(t instanceof javax.servlet.jsp.SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) try { if (response.isCommitted()) { out.flush(); } else { out.clearBuffer(); } } catch (java.io.IOException e) {} if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } } ``` > 자동생성된 서블릿 클래스 이름 - 서블릿 클래스의 이름이 Hello_jsp로 되어있다. 톰캣 서버에서는 이런식으로 명명하고, 이름 짓는 방식은 서블릿 컨테이너마다 다른다. > HttpJspBase클래스 - Hello_jsp 는 HttpJspBase를 상속받고 있는데, HttpJspBase는 톰캣 서버에서 제공하는 클래스다. - 소스코드를 보면 결국 HttpServlet 클래스를 상속받았고 HttpJspPage 인터페이스를 구현했다. - 즉 HttpJspBase를 상속받은 Hello_jsp는 서블릿이라는 뜻이다. > JSP 내장객체 - _jspService()의 매개변수는 HttpServletRequest 와 HttpServletResponse 객체다. - 또한 선언된 지역변수 중에서 다음의 참조 변수들은 반드시 이 이름으로 존재해야 한다. ```java final javax.servlet.jsp.PageContext pageContext; javax.servlet.http.HttpSession session = null; final javax.servlet.ServletContext application; final javax.servlet.ServletConfig config; javax.servlet.jsp.JspWriter out = null; final java.lang.Object page = this; ``` - 위와 같은 객체들은 이 메소드가 호출될 때 반드시 준비되는 객체들이기 때문에, 이 객체들을 가리켜 JSP내장객체 라고 부른다. - 이 객체들은 별도의 선언 없이 JSp페이지에서 마음껏 사용할 수 있다. #### HttpJspBase 클래스의 소스 Hello_jsp의 슈퍼 클래스인 HttpJspBase 클래스에 대해 간단히 알아보자. - 톰캣 서버의 JSP 엔진은 서블릿 소스를 생성할 때 슈퍼 클래스로서 HttpJspBase를 사용한다. ( 이 클래스는 톰캣 ㅅ버ㅓ에 포함된 클래스다. ) #### JSP프리컴파일 웹 어플리케이션을 서버에 배치할 때 모든 JSP파일에 대해 자바 서블릿 클래스를 미리 생성하기도 한다. 그 이유는 JSP실행 요청이 들어 왔을 때, 곧바로 서블릿을 호출할 수 있기때문이다. 즉 이렇게 미리 자바 서블릿을 만들게 되면, JSP를 실행할 때 마다 JSP파일이 변경되었는지, JSP파일에 대해 서블릿 파일이 있는지 매번 검사할 필요가 없다. 또한 실행속도를 높일 수 있다. 다만 이 방식의 문제는 JSP를 편집하면 서버를 다시 시작해야 한다. 그래야만 변경된 JSP에 대해 서블릿 코드가 다시 생성된다. 그러므로 시스템 도입 초기에는 가능한 이런 설정을 피하고 어느정도 안정화된 이후에 JSP프리컴파일을 고려하자 ### JSP의 주요 구성 요소 JSP를 구성하는 요소는 크게 두 가지로 나눌 수 있다. - 템플릿 데이터 - JSP 전용태그 템플릿 데이터는 클라이언트로 출력되는 콘텐츠(예:HTML, 자바스크립트, css, JSON, xml 등...)이며, JSP 전용태그는 특정 자바 명령문으로 바뀌는 태그다. > 계산기 예제를 통해 살펴보자 ```php <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String v1 = ""; String v2 = ""; String result = ""; String[] selected = {"", "", "", ""}; if(request.getParameter("v1") != null){ v1 = request.getParameter("v1"); v2 = request.getParameter("v2"); String op = request.getParameter("op"); result = calculate( Integer.parseInt(v1), Integer.parseInt(v2), op); if ("+".equals(op)) { selected[0] = "selected"; } else if ("-".equals(op)) { selected[1] = "selected"; } else if ("*".equals(op)) { selected[2] = "selected"; } else if ("/".equals(op)) { selected[3] = "selected"; } } %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <h2>JSP 계산기</h2> <form action="Calculator.jsp" method="get"> <input type="text" name="v1" size="4" value="<%=v1%>"> <select name="op"> <option value="+" <%=selected[0]%>>+</option> <option value="-" <%=selected[1]%>>-</option> <option value="*" <%=selected[2]%>>*</option> <option value="/" <%=selected[3]%>>/</option> </select> <input type="text" name="v2" size="4" value="<%=v2%>"> <input type="submit" value="="> <input type="text" size="8" value="<%=result%>"><br> </form> </body> </html> <%! private String calculate(int a, int b, String op) { int r = 0; if ("+".equals(op)) { r = a + b; } else if ("-".equals(op)) { r = a - b; } else if ("*".equals(op)) { r = a * b; } else if ("/".equals(op)) { r = a / b; } return Integer.toString(r); } %> ``` #### 템플릿 데이터 - 템플릿 데이터는 클라이언트로 출력되는 콘텐츠다. - 즉 HTMl이나 XML, 자바스크립트, 스타일시트, JSON문자열, 일반 텍스드 등을 말한다. - 이 템플릿 데이터는 서블릿 코드를 생성할 때 출력문으로 바뀐다. #### JSP전용 태그 - 지시자 `<%@ 지시자... %>`는 JSP전용태그로 '지시자'나 '속성'에 따라 특별한 자바 코드를 생성한다. JSP 지시자에는 page, taglib, include 가 있다. 1) page 지시자 page 지시자는 JSP 페이지와 관련된 속성을 정의할 때 사용하는 태그다. ```Java <%@ page language="java" contentType="text/html; charset=UTF-8" %> ``` #### JSP 전용 태그 - 스크립트릿 JSP페이지 안에 자바 코드를 넣을 때는 스크립트릿 태그 `<% %>`안에 작성한다. 이러한 스크립트릿의 내용은 서블릿 파일을 생성할 때 그대로 복사된다. #### JSP 내장객체 JSP 페이지에서 스크립트릿이나 표현식을 작성할 때 별도의 선언 없이 사용하는 자바 객체가 있다. 이런 객체를 JSP 내장객체라 한다. 예제 코드에선 `request 객체`가 여기에 해당한다 ```Java v1 = request.getParameter("v1"); v2 = request.getParameter("v2"); String op = request.getParameter("op"); ``` JSP 기술 사양서에는 스크립트릿이나 표현식에서 JSP 내장 객체의 사용을 보장한다고 되어 있다. 그래서 객체를 선언하지 않고 바로 사용할 수 있는 것이다. 이는 JSP 엔진이 만든 서블릿 파일에서 `_jspService()`에 선언된 변수들을 보고 확인할 수 있다. #### JSP 전용태그 - 선언문 JSP 선언문(Declarations) `<%! %>`는 서블릿 클래스의 멤버(변수나 메소드)를 선언할 때 사용하는 태그다. 이때 선언문을 작성하는 위치는 어디든 상관없다. 왜냐하면 선언문은 `_jspService()`메소드 안에 복사되는 것이 아니라, 밖의 클래스 블록안에 복사되기 때문이다. #### JSP 전용태그 - 표현식 표현식(Expressions) 태그는 문자열을 출력할 때 사용한다. 따라서 표현식 `<%=%>` 안에는 결과를 반환하는 자바 코드가 와야 한다. 표현식도 스크립트릿과 같이 `_jspService()`안에 순서대로 복사한다. --- ### 서블렛에서 뷰 분리하기 클라이언트로부터 요청이 들어오면 서블릿은 데이터를 준비(모델)하여 JSP에 전달(컨트롤러 역할)합니다. JSP는 서블릿이 준비한 데이터를 가지고 웹 브라우저로 출력할 화면을 만든다. #### 값 객체(VO) = 데이터 수송 객체(DTO) 데이터베이스에서 가져온 정보를 JSP페이지에 전달하려면 그 정보를 담을 객체가 필요하다. 이렇게 값을 담는 용도로 사용하는 객체를 `값 객체(value object)`라고 부른다. 값 객체는 계층간 또는 객체 간에 데이터를 전달하는 데 이용하므로 `데이터 수송 객체(DTO)` 라고도 부른다. > 값 객체 역할을 수행할 Member 클래스를 만들어 보자 ```java package spms.vo; import java.util.Date; public class Member { protected int no; protected String name; protected String email; protected String password; protected Date createdDate; protected Date modifiedDate; public int getNo() { return no; } public Member setNo(int no) { this.no = no; return this; } public String getName() { return name; } public Member setName(String name) { this.name = name; return this; } public String getEmail() { return email; } public Member setEmail(String email) { this.email = email; return this; } public String getPassword() { return password; } public Member setPassword(String password) { this.password = <PASSWORD>; return this; } public Date getCreatedDate() { return createdDate; } public Member setCreatedDate(Date createdDate) { this.createdDate = createdDate; return this; } public Date getModifiedDate() { return modifiedDate; } public Member setModifiedDate(Date modifiedDate) { this.modifiedDate = modifiedDate; return this; } } ``` > Member 클래스는 회원 목록 출력에 필요한 데이터 뿐만 아니라 등록이나 변경할 때 사용하는 데이터도 포함하고 있다. 위 코드를 살펴보면 특이한 점이 있는데 세터(Setter)메소드의 리턴값이 void가 아니라 Member 이다. 이렇게 한 이유는 세터 메소드를 연속으로 호출하여 ㄱ밧을 할당할 수 있게 하기 위함이다. 즉, 다음과 같이 코드를 작성할 수 있다. ```java new Member().setNo(1).setName("홍길동").setEmail("<EMAIL>"); ``` MemberListServlet 클래스에서 뷰 역할을 분리하기 위해 코드를 제거해보자 ```java ArrayList<Member> members = new ArrayList<Member>(); ``` > ArrayList 객체를 위와 같이 생성한 후 ResultSet 객채 rs를 통해 DB로부터 받은 레코드를 값 객체 Member에 담은 과정을 한다. ```java while(rs.next()) { members.add(new Member() .setNo(rs.getInt("MNO")) .setName(rs.getString("MNAME")) .setEmail(rs.getString("EMAIL")) .setCreatedDate(rs.getDate("CRE_DATE")) ); } ``` 위와같이 세터메소드를 연속으로 호출할 수 있는 이유가 바로 세터 메소드의 반환값을 this로 한 이유다.(객체를 생성하고 바로 초기화할 수 있다.) 회원 목록 데이터가 준비되었으니, 화면 생성을 위해 JSp로 작업을 위임해야 한다. 이렇게 다른 서블릿이나 JSP로 작업을 위임할 때 사용하는 객체가 RequestDispatcher 이다. 이 객체는 HttpServletRequest를 통해 얻는다 ```java RequestDispatcher rd = request.getRequestDispatcher("/member/MemberList.jsp"); ``` `RequestDispatcher`를 얻을 때, 반드시 어떤 서블릿(또는 JSP)으로 위임할 것인지 알려줘야 한다. 이제 `RequestDispatcher`객체를 얻었으면 `포워드`하거나 `인클루드`를 하면 된다. 포워드로 위임하면 해당 서블릿으로 제어권이 넘어간 후 다시 돌아오지 않는다. 인클루드로 위임하면 해당 서블릿으로 제어권을 넘긴 후 그 서블릿이 작업을 끝내면 다시 제어권이 넘어온다. ```java rd.include(request, response); ``` 위 인클루드는 MemberListServlet.doGet() 메소드의 매개변수 값을 그대로 넘겼다. 즉 MemberListServlet과 MemberList.jsp는 request 와 response를 공유한다. 바로 이 부분을 이용해서 데이터를 전달 할 수 있다. ServletRequest 는 클라이언트의 요청을 다루는 기능 외에 어떤 값을 보관하는 보관소 기능도 있다. `setAttribute()를 호출하여 값을 보고나할 수 있고, getAttribute()를 호출하여 보관된 값을 꺼낼 수 있다. 예제는 바로 이 기능을 사용해서 회원목록을 MemberList.jsp에 전달하고 있는 것이다. ```java request.setAttribute("members", members); ``` MemberListServlet의 request는 MemberList.jsp와 공유하기 때문에, request에 값을 담아 두면 MemberList.jsp에서 꺼내 쓸 수 있다. #### 뷰 컴포넌트 만들기 MemberListServlet으로부터 받은 회원 목록 데이터를 가지고 화면을 생성하는 JSP를 만들어 보자 ```php <%@page import="spms.vo.Member"%> <%@page import="java.util.ArrayList"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>회원 목록</title> </head> <body> <h1>회원목록</h1> <p><a href='add'>신규 회원</a></p> <% ArrayList<Member> members = (ArrayList<Member>)request.getAttribute("members"); for(Member member : members) { %> <%=member.getNo()%>, <a href='update?no=<%=member.getNo()%>'><%=member.getName()%></a>, <%=member.getEmail()%>, <%=member.getCreatedDate()%> <a href='delete?no=<%=member.getNo()%>'>[삭제]</a><br> <%} %> </body> </html> ``` > Page 지시자를 아래와 같이 선언하면 ```java <%@page import="spms.vo.Member"%> <%@page import="java.util.ArrayList"%> ``` > JSP엔진이 서블릿 소스를 생성할 때 다음과 같이 import코드를 만든다 ```java import spms.vo.Member; import java.util.ArrayList; ``` `MemberListServlet`에서 넘겨준 회원 목록 데이터를 꺼내기 위해 `getAttribute()를 호출했다. ```java ArrayList<Member> members = (ArrayList<Member>)request.getAttribute("members"); for(Member member : members) { //뿌려줄 내용 } ``` `request`는 JSP 내장객체라 불리며, _jspService()의 매개변수로 선언된 HttpServletRequest객체이다. 따라서 request는 변수 선언 없이 바로 사용할 수 있다. 위와 같이만 하면 이하 뿌려주는 내용은 이처럼 훨씬 편하게 사용할 수 있다. --- ### 포워딩과 인클루딩 이번 절에서는 서블릿 끼리 작업을 위임하는 방법에 대해 알아보자. 작업을 위임하는 방법에는 위에서 잠깐 언급했던 것처럼 두가지가 있다. 1) 포워딩(Forwarding) > 포워드 방식은 작업을 한 번 위임하면 다시 이전 서블릿으로 제워권이 돌아오지 않는다. - 웹 브라우저가 `서블릿A`를 요청하면, `서블릿A`는 작업을 수행한다. - 서블릿A에서 '서블릿B'로 실행을 위임한다. - 서블릿B 는 작업을 수행하고 나서 응답을 완료한다. 이때 서블릿 A로 제어권이 돌아가지 않는다 2) 인클루딩(including) > 인클루드 방식은 다른 서블릿으로 작업을 위임한 후, 그 서블릿의 실행이 끝나면 다시 이전 서블릿으로 제어군이 넘어온다. - 웹브라우저가 '서블릿A'를 요청하면 서블릿A는 작업을 수행한다. - 서블릿A 에서 '서블릿B'로 실행을 위임한다. - 서블릿B는 작업을 수행하고 나서 다시 서블릿A로 제어권을 넘긴다. - 서블릿A는 나머지 작업을 수행한 후 응답을 완료한다. #### 포워딩과 인클루딩 실습 서블릿을 실행하다가 오류가 발생하면, 현재는 예외 객체를 던졌다. 이부분을 포워딩으로 오류 정보를 출력하는 페이지로 위임해보자 또한 인크루딩 방식에서 전형적으로 사용되는 사례와 헤더와 푸터를 인크루딩하는 코드를 살펴보자 > 기존에 예외를 던지는 catch 블록안의 코드를 아래처럼 `Error.jsp`라는 페이지로 위임하자 > setAttribute()로 값을 객체에 보관하고 `인클루드` 혹은 `포워드`를 통해 처리하는 부분은 완전히 같다. > ```java catch (Exception e) { //throw new ServletException(e); request.setAttribute("error", e); RequestDispatcher rd = request.getRequestDispatcher("/Error.jsp"); rd.forward(request, response); } ``` 이젠 JSP페이지에 각각 헤더와 푸터 (예제에서는 Header.jsp, Tail.jsp파일이다)를 인클루드 하는데 이때 사용하는 태그는 아래를참고하자 ```java <jsp:include page="/Header.jsp"> <jsp:include page="/Tail.jsp"/> ``` 위의 태그들은 JSP엔진에 의해 서블릿이 생성될 때 결국 아래와 같은 코드로 바뀐다. ```java RequestDispatcher rd = request.getReponseDispatcher("/Header.jsp"); rd.inlcude(request, reponse); ``` > 물론 여기서 위내용을 스크립트릿 `<% %>`을 사용해서 처리해도 된다. --- ### 데이터 보관소 서블릿 기술은 데이터를 공유하기 위한 방안으로 네 가지 종류의 데이터 보관소를 제공하며ㅡ, 각각의 데이터 보관소는 공유 범위를 기준으로 구분된다. 1) ServletContext 보관소 - 웹 애플리케이션이 시작될 때 생성되어 웹 애플리케이션이 종료될 때까지 유지된다. - 이 보관소에 데이터를 보관하면 웹 애플리케이션이 실행되는 동안에는 모든 서블릿이 사용할 수 있다. - JSP에서는 `application 변수`를통해 이 보관소를 참조할 수 있다. 2) HttpSession 보관소 - 클라이언트의 최초 요청시 생성되어 브라우저를 닫을 때까지 유지된다. - 보통 로그인할 때 이 보관소를 초기화하고, 로그아웃하면 이 보관소에 저장된 값들을 비운다. - 따라서 이 보관소에 값을 보관하면 서블릿이나 JSP페이지에 상관없이 로그아웃 전까지 계속 값을 유지할 수 있다 - JSP에서는 `session 변수`를 통해 참조 할 수 있다. 3) ServletRequest 보관소 - 클라이언트의 요청이 들어올 때 생성되며, 클라이언트에게 응답할 때까지 유지된다. - 포워딩이나 인클루딩하는 서블릿들 사이에서 값을 공유할때 유용하다 - JSP에서는 `request 변수`를 통해 이 보관소를 참조할 수 있다. 4) JSPContext 보관소 - JSP페이지를 실행하는 동안만 유지된다. - JSP에서는 pageContext변수를 통해 이 보관소를 참조할 수 있다. 보관소에 값을 넣고 빼내는 방법은 모두 같다. 다음의 메소드를 호출하여 값을 저장하고 조회할 수 있다. ```java 보관소 객체.setAttribute(키, 값); //값 저장 보관소 객체.getAttribute(키); //값 조회 ``` Map객체의 put()과 get()메소드와 유사하다. #### ServletContext의 활용 AppInit ServetletContext 객체는 웹 애플리케이션이 시작될 때 생성되어, 웹 애플리케이션이 종료될 때까지 유지되는 객체다 지금까지 DB를 사용하는 서블릿들은 모두, 호출될 때마다 데이터베이스 커넥션을 생성했다. 이 데이터베이스 커넥션 객체를 웹 애플리케이션이 시작될 대 생성하여 ServletContext에 저장해보자 > 먼저 ServletContext를 활용할 새로운 클래스를 만들자.! 또한 서블릿이 되어야 하기 때문에 HttpServlet을 상속받는 클래스여야 한다 ```java package spms.servlets; import java.sql.*; import javax.servlet.*; import javax.servlet.http.HttpServlet; public class AppInitServlet extends HttpServlet { @Override public void init(ServletConfig config) throws ServletException{ System.out.println("AppInitServlet 준비 ...."); super.init(config); try{ ServletContext sc = this.getServletContext(); Class.forName(sc.getInitParameter("driver")); Connection conn = DriverManager.getConnection(sc.getInitParameter("url"), sc.getInitParameter("username"), sc.getInitParameter("password")); sc.setAttribute("conn", conn); } catch(Throwable e){ throw new ServletException(e); } } @Override public void destroy(){ System.out.println("AppInitServlet 마무리...."); super.destroy(); Connection conn = (Connection)this.getServletContext().getAttribute("conn"); try{ if(conn != null && conn.isClosed() == false){ conn.close(); } } catch(Exception e){} } } ``` 이번에 만든 서블릿은 클라이언트에게 호출할 서블릿이 아니므로 service()나 doGet(), doPost()등을 오버라이딩하지 않는다. 그 대신 `init()`을 오버라이딩 했다. 이 `init()`은 서블릿 객체가 생성될 때 딱 한번 호출되기 때문에 공유자원을 준비하는 코드가 놓이기에 최적의 장소라 할 수 있다 (콘솔로 새로고침을 확인했을때 service()만 계속해서 찍혔던거 생각하면 될듯 ) > 이제 위의 AppInitServlet의 배치정보를 DD파일(web.xml)에 추가하자. ```xml <servlet> <servlet-name>AppInitServlet</servlet-name> <servlet-class>spms.servlets.AppInitServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> ``` 여기서 주목할 부분은 `<load-on-startup>` 부분이다. 서블릿 객체는 ++**클라이언트의 최초 요청시 생성**++된다고 분명히 말했었다. 그말은 클라이언트가 단 한번도 요청하지 않으면 그 서블릿은 생성되지 않는다는 말이다. 그러나 우리가 만든 `AppInitServlet` 처럼 다른 서블릿이 생성되기 전에 미리 준비 작업을 해야 하는 서블릿이라면, 클라이언트의 요청이 없더라도 생성되어야만 한다. `<load-on-startup>`태그는 바로 이런 용도의 서블릿을 배치할 때 사용한다. 이 태그의 값은 생성 순서다. 만약 생성순서가 같은 서블릿이 여러개 일댄 먼저 선언된 것이 먼저 생성된다. > 또한 AppInitServlet은 `<servlet-mapping>`태그가 없다. > 즉, 이 클래스에 대한 URL 이 지정되지 않았고, 이렇게 URL매핑정보가 없는 서블릿은 클라이언트에서 실행을 요청할 수 없다. > 이렇게 다른 서블릿을 위해(여기서는 데이터베이스 접속정보) 준비 작업을 수행하는 서블릿인 경우 URL을 지정하지 않는다. 이제 MemberListServlet 에서도 DB 커넥션 코드를 삭제해도 된다 ( 물론 getAttibute()를 통해 방금 만든 inin... 처리한 클래스 불러와야 된다.) ```java ServletContext sc = this.getServletContext(); /* Class.forName(sc.getInitParameter("driver")); conn = DriverManager.getConnection( sc.getInitParameter("url"), sc.getInitParameter("username"), sc.getInitParameter("password")); */ conn = (Connection) sc.getAttribute("conn"); ``` > 또한 DB커넥션 객체를 서블릿에서 관리하지 않으므로 finally 블록에 있는 conn.close()명령문도 삭제한다. ```java try {if (rs != null) rs.close();} catch(Exception e) {} try {if (stmt != null) stmt.close();} catch(Exception e) {} //try {if (conn != null) conn.close();} catch(Exception e) {} ``` #### HttpSession의 활용 HttpSession객체는 클라이언트 당 한개가 생성된다. 웹 브라우저로부터 요청이 들어오면, 그 웹브라우저를 위한 HttpSession객체가 있는지 검사하고, 없다면 새로 HttpSession 객체를 만든다. 이렇게 생성된 HttpSession객체는 그 웹 브라우저로부터 일정 시간 동안 Timeout 요청이 없으면, 삭제된다. 따라서 로그인되어 있는 동안 지속적으로 사용할 데이터를 HttpSession객체에 저장한다. > LogInServlet 클래스 ```java package spms.servlets; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import spms.vo.Member; @WebServlet("/auth/login") public class LogInServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RequestDispatcher rd = request.getRequestDispatcher( "/auth/LogInForm.jsp"); rd.forward(request, response); } @Override protected void doPost( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { ServletContext sc = this.getServletContext(); conn = (Connection) sc.getAttribute("conn"); stmt = conn.prepareStatement( "SELECT MNAME,EMAIL FROM MEMBERS" + " WHERE EMAIL=? AND PWD=?"); stmt.setString(1, request.getParameter("email")); stmt.setString(2, request.getParameter("password")); rs = stmt.executeQuery(); if (rs.next()) { Member member = new Member() .setEmail(rs.getString("EMAIL")) .setName(rs.getString("MNAME")); HttpSession session = request.getSession(); session.setAttribute("member", member); response.sendRedirect("../member/list"); } else { RequestDispatcher rd = request.getRequestDispatcher( "/auth/LogInFail.jsp"); rd.forward(request, response); } } catch (Exception e) { throw new ServletException(e); } finally { try {if (rs != null) rs.close();} catch (Exception e) {} try {if (stmt != null) stmt.close();} catch (Exception e) {} } } } ``` > doGet(), doPost()로 나누어 작업했으며 Member객체를 HttpSession에 보관한다. > 로그인 성공이면 멤버리스트 페이지로 리다이렉트 하고 로그인에 실패한다면 로그인실패 JSP페이지로 포워딩한다. > 이때 로그인 실패의 경우 값을 다시 받을 필요가 없으므로 `인클루드`가 아닌 `forward` 처리했다고 보면 된다. - > /auth/LogInForm.jsp 로그인 폼 JSP 페이지 구현 ```java <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>로그인</title> </head> <body> <h2>사용자 로그인</h2> <form action="login" method="post"> 이메일: <input type="text" name="email"><br> 암호: <input type="password" name="password"><br> <input type="submit" value="로그인"> </form> </body> </html> ``` 여기서 form action값을 `login`으로 입력폼 요청할 때의 URL과 같은 이유는 서버에서 GET, POST로 나누어서 처리하도록 해놨기때문이다. > Header.jsp 파일 - 로그인 한 사용자정보를 헤더정보에 표기 ```java <%@page import="spms.vo.Member"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% Member member = (Member)session.getAttribute("member"); %> <div style="background-color:#00008b;color:#ffffff;height:20px;padding: 5px;"> SPMS(Simple Project Management System) <span style="float:right;"> <%=member.getName()%> <a style="color:white;" href="<%=request.getContextPath()%>/auth/logout">로그아웃</a> </span> </div> ``` > 세션으로 저장한 Member 객체를를 getAttribute()를 통해 JSP에서도 불러와서 사용할 수 있음을 알 수 있다. ```java Member member = (Member)session.getAttribute("member"); ``` 여기서 `getAttribute("member")`의 "member"는 `setAttribute()`에서 값을 넣을때 지정한 **키값**이다. > 로그아웃 LogoutServlet 클래스 ```java package spms.servlets; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; @WebServlet("/auth/logout") public class LogOutServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); session.invalidate(); response.sendRedirect("login"); } } ``` HttpSession 객체를 무효화 하기 위해 `invalidate()를 호출한다. 세션 객체가 무효화 된다는 것은 HttpSession객체가 제거된다는 것을 의미한다. HttpSession 객체를 무효화시킨 후 , 새로운 요청이 들어오면 HttpSession 객체가 새로 만들어진다. #### ServletRequest의 활용 ServletRequest 객체에 데이터를 보관하면 포워딩이나 인클루딩을 통해 협업하는 서블릿(JSP 포함)끼리 데이터를 공유할 수 있다. 그 이유는 request와 response를 같이 사용하기 때문이다. ```java protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 중간 생략 rd.forward(request, response); ``` 위 코드에서 forward()를 호출할때 doGet()의 매개변수를 그대로 넘겨주고 있음을 알수 있다. 지금까지 작성한 예제를 통해 설명하자면 LogInServlet 과 LogInForm.jsp 사이에는 `ServletRequest`를 공유한다는 뜻이다. #### JspContext의 활용 JspContext 보관소는 JSP페이지를 실행할 때 생성되고, 실행이 완료되면 이 객체는 제거된다. 따라서 JSP페이지 내부에서만 사용도리 데이터를 공유할 때 사용한다. 말이 어려우니 작성했던 예제로 예를 들어보자면 MemberList.jsp에 헤더페이지를 `<jsp:include page="/Header.jsp" />`의 형식으로 선언했었는데 이런 태그들은 JSP엔진이 서블릿 클래스를 생성할 때 특정 자바 코드로 변환된다고 했었다. 이때 이 태그의 값을 다루는 객체를 `태그 핸들러` 라고 부른다. 바로 이 태그 핸들러에게 데이터를 전달하고자 할때 JspContext 보관소를 사용하는 것이다. --- ### JSP 액션 태그의 사용 이번 절에서는 JSP페이지를 좀 더 개선해보자. JSP 페이지를 작성할 때, 가능한 자바코드의 삽입을 최소화하는 것이 유지보수에도 좋고 JSP라는 기술의 취지에도 부합한다. 이를 위해 JSP에서는 JSP전용태그들을 제공하고 있는데 이런 태그들의 집합을 `JSP액션(Action)`이라 한다. - `<jsp:useBean>` 자바 인스턴스를 준비한다. 보관소에서 자바 인스턴스를 새로 만들어 보관소에 저장하는 코드를 생성한다. 자바 인스턴스를 자바 빈(JavaBean)이라고 부른다. - `<jsp:setProperty>` 자바 빈의 프로퍼티 값을 설정한다. 자바 객체의 세터 메소드를 호출하는 코드를 생성한다. - `<jsp:getProperty>` 자바 빈의 프로퍼티 값을 꺼낸다. 자바 객체의 게터 메소드를 호출하는 코드를 생성한다. - `<jsp:include>` 정적(HTML, 텍스트파일등)또는 동적 자원(서블릿/JSP)을 인클루딩 하는 자바 코드를 생성한다. - `<jsp:forward>` 현재 페이지의 실행을 멈추고 다른 정적 자원(HTML, 텍스트파일)이나 동적자원자원으로 포워딩하는 자바 코드를 생성한다. - `<jsp:param>` jsp:include, jsp:forward, jsp:params의 자식태그로 사용할 수 있다. ServletRequest 객체에 매개변수를 추가하는 코드를 생성한다. - `<jsp:plugin>` Object또는 EMBED HTML 태그를 생성한다. - `<jsp:element>` 임의의 XML 태그나 HTML태그를 생성한다. > JSP 액션태그 - `<jsp:useBean>` ```java <jsp:useBean id="members" scope="request" class="java.util.ArrayList" type="java.util.ArrayList<spms.vo.Member>" /> ``` 위의 `<jsp:useBean />` 액션 태그를 자바 코드로 바꾼다면 다음과 같다. ```java java.util.ArrayList<spms.vo.Member> members = (java.util.ArrayList<spms.vo.Memeber>)request.getAttribute("members"; if(members == null){ members = new java.util.ArrayList(); request.setAttribute("members", member); } ``` `Id 속성`은 객체의 이름을 설정하는 부분이며, 이 이름을 사용하여 보관소로부터 값을 꺼낸다. 또한 꺼낸 객체의 참조 변수 이름으로 사용한다. `scope 속성`은 객체를 조회하거나 새로 만든 객체를 저장할 보관소를 지정할 수 있으며, 네가지 보관소 중에서 하나를 지정할 수 있다. - `page` 는 `JspContext` - `request` 는 `ServletRequest` - `session`은 `HttpSession` - `application`은 `ServletContext` 보관소를 의미한다. `class 속성`은 자바 객체를 생성할 때 사용할 클래스 이름을 지정한다. 따라서 클래스 이름은 반드시 패키지 이름을 포함해야하고, 인터페이스 이름은 안된다. 만약 `scope`에 지정된 보관소에서 객체를 찾지 못하면, 이 속성의 클래스 이름을 사용하여 객체를 생성한다. 만약 이 속성이 없다면, 객체를 생성할 수 없다. `type 속성`은 참조변수를 선언할 때 사용할 타입의 이름이다. 클래스 이름 또는 인터페이스 이름이 올 수 있다. 클래스 이름과 인터페이스 이름은 반드시 패키지 이름을 포함해야 한다. --- ### EL 사용하기 - EL(Expression Language)은 콤마`.`와 대괄호`[]`를 사용하여 자바 빈의 프로퍼티나 맵, 리스트, 배열의 값을 보다 쉽게 꺼내게 해주는 기술이다. - `static`으로 선언된 메소드를 호출할 수도 있다. - JSP에서는 주로 보관소에 들어 있는 값을 꺼낼 때 사용한다. - 액션태그를 사용하는 것보다 훨씬 더 간단하게 보관소에 들어 있는 객체에 접근하여 값을 꺼내기 쉽다. #### EL표기법 EL은 `${}`와 `#{}`를 사용하여 값을 표현한다. 1) `${표현식}` - `${표현식}` 으로 지정된 값은 JSP가 실행될 때 JSP페이지에 즉시 반영된다. - 즉시 적용(immediate evaluation)이라 부른다. 2) `#{표현식}` - 시스템에서 필요하다고 판단될 때 그 값을 사용한다. - 지연 적용(deferred evaluation)이라 부른다. - 객체 프로퍼티의 값을 꺼내기보다는, 사용자가 입력한 값을 객체의 프로퍼티에 담는 용도로 많이 사용한다. - JSF(JavaSErver Faces)기술에서 UI를 만들 때 많이 사용한다. > EL 실제 표기법 ```java ${member.no} 또는 ${member["no"]} // member = 객체이름 // no = 프로퍼티 ``` 이 `EL 표기법`을 자바 코드로 표현하면 다음과 같다. ```java Member obj = (Member)pageContext.findAttribute("member"); int value=obj.getNo(); ``` 3) EL 에서 검색 범위 지정 EL도 `<jsp:useBean>`처럼 네 군대 보관소에서 값을 꺼낼 수 있다. 다만 차이점은 EL로는 객체를 생성할 수 없다는 것이다. 보관소를 참조할 때 사용하는 이름은 다음과 간다. - pageScope -> JspContext - requestSession -> ServletRequest - sessionScope -> HttpSession - applicationScope -> ServletContext --- ### JSTL 사용하기 JSTL(JSP Standard Tag Library)은 JSP 확장태그이다 JSP의 기본태그가 아니므로 사용하려면 JSTL API 및 이를 구현한 자바 라이브러리를 별도로 내려 받아야 한다. ##### JSTL 라이브러리 1. [JSTL 사이트](http://jstl.java.net)에 접속하여 `JSTP API` 와 `JSTP Implementation`을 각각 다운 받는다. 2. WebContent/WEB-INF/lib 폴더로 위치시킨다. ##### JSTL 주요 태그의 사용법 1) 사용할 태그 라이브러리를 선언 `Java`에서는 `java.lang`패키지에 소속된 클래스인 경우 별도의 선언 없이 사용한다. `JSP` 에서도 `<jsp:useBean>`태그와 같이 기본으로 제공되는 태그는 별도의 선언 없이 사용한다. 그러나 JSTL 확장 태그를 사용하려면 그 태그의 라이브러리를 선언해야 한다. 다음은 태그 라이브러리를 선언하는 문법이다 ```java <%@ taglib uri="사용할 태그의 라이브러리 URI" prefix="접두사" %> ``` `<%@ taglib %>`은 JSP의 지시자 태그이다. uri속성은 태그 라이브러리의 네임스페이스 이름이다. 네임스페이스 이름은 URI로 되어 있다. prefix속성은 JSTL 태그를 사용할 때 태그 이름 앞에 붙일 접두사다 > 다음 표는 각 태그라이브러리에 정의된 URI 식별자와 JSTL 에서 제안하는 접두사 이름이다 | 태그 라이브러리 | 접두사 | 네임스페이스의 URI 식별자 |--------|--------| | Core | c | http://java.sun.com/jsp/jstl/core | XML | x | http://java.sun.com/jsp/jstl/xml | \18N | fmt | http://java.sun.com/jsp/jstl/fmt | Database | sql | http://java.sun.com/jsp/jstl/sql | Functions | fn | http://java.sun.com/jsp/jstl/functions 접두사 이름은 반드시 위의 표와 같을 필요는 없지만, 대부분의 개발자들이 JSTL에서 제안하는 접두사 이름을 사용하므로, 가급적 저 양식대로 사요하다 > 예를 들어 JSTL 기본(Core)태그를 사용하려 한다면, 다음과 같이 taglib 지시자를 선언하면 된다 ```java <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> ``` ##### `<c:out> 태그` - 출력문을 만드는 태그 > 문법 ```java <c:out value="출력할 값" default="기본값" /> 또는 <c:out value="출력할 값" >기본값</c:out> ``` - value 속성의 값으로 EL표현식을 사용할 수 있다. - value 값이 null이면 기본값이 출력된다. - 기본값마저 없다면 빈 문자열이 출력된다 > 예제 ```java <c:out value="안녕하세요!" /></br> <c:out value="${null}" >반갑습니다.</c:out></br> <c:out value="안녕하세요!" >반갑습니다.</c:out></br> <c:out value="${null}" /></br> ``` > 출력값 ```html 1) 안녕하세요! 2) 반갑습니다. 3) 안녕하세요! 4) ``` ___ ##### `<c:set> 태그` - 변수를 생성하거나 기존 변수의 값을 덮어쓸 때 사용 - 이 태그로 생성한 변수는 JSP 페이지의 로컬 변수가 아니라 보관소(JspContext, ServletRequest, HttpSession, ServletContext)에 저장된다. > 문법 ```java // value 속성을 사용하여 값 설정 <c:set var="변수명" value="값" scope="page|request|session|application" /> // 태그 콘텐츠를 사용하여 값 설정 <c:set var="변수명" scope="page|requset|session|application" />값</c:set> ``` `scope`속성의 기본값은 page 이다. scope 값을 생략하면 JspContext(page)에 변수명으로 값이 저장된다. > `<c:set>태그를 이용한 객체의 프로퍼티 값 설정` `<c:set>`을 이용하면, 보관소에 저장된 객체의 프로퍼티 값도 바꿀 수 있다. > 예제 ```java <h3>객체의 프로퍼티 값 변경</h3> <%! public static class MyMember{ int no; String name; public int getNo(){ return no; } public void setNo(int no){ this.no = no; } public String getName(){ return name; } public void setName(String name){ this.name = name; } } %> <% MyMember member = new MyMember(); member.setNo(100); member.setName("홍길동"); pageContext.setAttribute("member", member); %> ${member.name }<br> <c:set target="${member}" property="name" value="임꺽정" /> ${member.name}<br> ``` `<c:set>`을 사용하여 객체의 프로퍼티 값을 설정할 때는 안타깝게도 세터 메소드의 리턴타입이 `void`여야 한다. Member 클래스처럼 세터 메소드의 리턴 타입이 `void`가 아니라면, "프로퍼티에 해당하는 세터 메소드를 찾을 수 없다."는 예외가 발생한다. 즉 세터 메소드의 리턴 타입을 `void`로 할 것인지, 아니면 해당 객체의 주소를 리턴하게 할 것인지 선택해야 한다. ```java pageContext.setAttribute("member", member); ``` 위 코드는 MyMember 내장 클래스를 정의한 후 JSP 페이지에서 객체를 생성한다. 그리고 JspContext 에 저장한다. ___ ##### `<c:remove> 태그` - 보관소에 값을 저장하는 태그가 있으면, 이 태그는 보관소에 저장된 값을 제거하는 태그다. - `var` 속성에 이름을 지정하면, 보관소에서 해당 이름을 가진 값을 제거한다. - 물론 `scope`속성으로 보관소를 명시 할 수 있다. (기본값은 마찬가지로 page 이다.) > 문법 ```java //value 속성을 사용하여 값 설정 <c:remove var="변수명" scope="page|request|session|application"/> ``` > 예제 ```java <h3>보관소에 저장된 값 제거</h3> <% pageContext.setAttribute("username1", "홍길동"); %> ${username1 }<br> <c:remove var="username1"/> ${username1 }<br> ``` > 출력결과 ```html 1) 홍길동 2) ``` ___ ##### `<c:if> 태그` - test 속성 값이 참이면, 콘텐츠가 실행된다. - 참거짓 테스트결과를 보관소에 저장할수도 있다. > 문법 ```java <c:if test="조건" var="변수명" scope="page|request|session|application"> 콘텐츠 </c:if> ``` > 예제 ```java <c:if test="${10>20 }" var="result1"> 10은 20보다 크다. <br> </c:if> ${result1 }<br> <c:if test="${10<20 }" var="result2"> 10은 20보다 크다. <br> </c:if> ${result2 }<br> ``` > 출력결과 ```html 1) false 2) 10은 20보다 크다. 3) true ``` ___ ##### `<c:choose> 태그` - 자바의 switch.. case 등과 같은 기능을 수행한다 - 여러가지 조건에 따른 작업을 해야 할 필요가 있을 때 사용한다. > 문법 ```java <c:shoose> <c:when test="참거짓 값"></c:whie> <c:when test="참거짓 값"></c:whie> ... <c:otherwise></otherwise> </c:choose> ``` 이때 `<c:when>` 태그는 한 개 이상 있어야 한다. ___ ##### `<c:forEach> 태그` - 반복적인 작업을 정의할 때 사용 - 목록에서 값을 꺼내어 처리하고 싶을 때 이 태그를 사용한다. > 문법 ```java <c:forEach var="변수명" items="목록데이터" begin="시작인덱스" end="종료인덱스"> 콘텐츠 </c:forEach> ``` `items` 속성의 값으로 다음의 값이 올 수 있다. - java.util.Collection 구현체. 예)ArrayList, LinkedList, Vector, EnumSet 등 - java.util.Iterator 구현체 - java.util.Enumeration 구현체 - java.util.Map 구현체 - 콤마(,) 구분자로 나열된 문자들 `var` 속성은 반복문을 돌면서 items 에서 꺼낸 항목값을 가리키는 참조 변수다. begin 과 end 속성은 items 를 반복할 때 몇 번째 인덱스에서 시작하고, 몇 뻔째 인덱스에서 종료할 것인지를 지정한다. ___ ##### `<c:forTokens> 태그` - 문자열을 특정 구분자(delimiter)로 분리하여 반복문을 돌릴 수 있다. > 예제 ```java <% pageContext.setAttibute("tokens", "v1=20&v2=30&op=+"); %> <ul> <c:forTokens var="item" items="${tokens}" delims="&"> <li>${item}</li> </c:forTokens> </ul> ``` ___ ##### `<c:url> 태그` - URl을 만들 때 사용하는 태그다. - 이 태그를 사용하면 매개변수를 포함한 URL을 손쉽게 만들 수 있다. > 예제 ```java <c:url var="calcUrl" value="http://localhost:9999/calc"> <c:param name="v1" value="20"/> <c:param name="v2" value="30"/> <c:param name="op" value="+"/> </c:url> <a href="${calcUrl} }">계산하기</a> ``` ___ ##### `<c:import> 태그` - 여러 사이트의 내용을 가져와서 새로운 서비스를 만드는 매쉬업(Mashup)에 매우 유용한 태그. - url 속성에 콘텐츠가 있는 주소를 지정하면, 해당 주소로 요청하고, 응답 결과를 받아서 반환한다. > 예제 ```java <textarea name="" id="" cols="80" rows="10"> <c:import url="http://www.zdnet.co.kr/Include2/ZDNetKorea_News.xml" /> </textarea> ``` 위 예제를 실행해보면 ZDNET 사이트의 RSS 피드를 가져와서 뿌려주는걸 볼 수 있다. 이때 var 속성을 설정하면, URL 응답결과를 바로 출력하지 않고 var에 설정된 이름으로 보관소에 저장한다. ___ ##### `<c:redirect> 태그` - 리다이렉트 처리를 할 수 있다. - 내부적으로 HttpServletResponse의 sendRedirect()를 호출한다 > 예제 ```java <c:redirect url="http://www.daum.net"/> ``` ___ ##### `<fmt:parseDate> 태그` - 날짜 형식으로 작성된 문자열을 분석하여 java.util.Date객체를 생성한 후 지정된 보관소에 저장한다. > 예제 ```java <fmt:parsedate var="date1" value="2015-12-01" pattern="yyyy-MM-dd" /> ``` ##### `<fmt:formatDate> 태그` - 날짜 객체로부터 우리가 원하는 형식으로 날짜를 표현하고자 할 때 이 태그를 사용한다. - 사용법은 위 `parseDate`와 유사하며 value에 java.util.Date 객체를 설정하고, pattern에 표현 방식을 지정한다. > 예제 ```java <fmt:formatDate value="${date1}" pattern="yyyy-MM-dd" /> ``` > 출력결과 ```java 12/01/15 ``` --- ### DAO 만들기 데이터 처리를 전문으로 하는 객체를 `DAO(data access object)`라고 부른다. - DAO는 데이터베이스나 파일, 메모리 등을 이용하여 애플리케이션 데이터를 생성, 조회, 변경, 삭제하는 역할을 수행한다. - DAO는 보통 하나의 DB테이블이나 DB 뷰에 대응한다. ```java package spms.dao; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import spms.vo.Member; public class MemberDao { Connection connection; public void setConnection(Connection connection) { this.connection=connection; } public List<Member> selectList() throws Exception { Statement stmt=null; ResultSet rs=null; try { stmt=connection.createStatement(); rs=stmt.executeQuery( "SELECT MNO,MNAME,EMAIL,CRE_DATE"+ "FROM MEMBERS"+ "ORDER BY MNO ASC"); ArrayList<Member> members=new ArrayList<Member>(); while(rs.next()){ members.add(new Member() .setNo(rs.getInt("MNO")) .setName(rs.getString("MNAME")) .setEmail(rs.getString("EMAIL")) .setCreatedDate(rs.getDate("CRE_DATE")) ); } return members; } catch(Exception e){ throw e; } finally { try {if(rs!=null) rs.close();} catch(Exception e){} try {if(stmt!=null) stmt.close();} catch(Exception e){} } } } ``` `selectList()`의 리턴타입이 `List인터페이스`인 것을 볼 수 있다. `selectList()`에서 실제로 리턴하는 것은 ArrayList 객체인데 리턴타입은 `List`로 작성되어있다. 그 이유는 ++**프로그래밍의 유연성**++ 때문이다. > 프로그래밍의 유연성을 향상시키는 방법! > 메소드의 리턴타입이나 매개변수 타입을 특정 클래스로 명시하게되면, 반드시 그 클래스(서브 클래스 포함)의 객체를 주고 받아야 하기 때문에, 유연성이 떨어진다. > 이런 이유로 메소드를 호출하는 쪽과 그메소드를 만드는 쪽 모두 유연성을 높이고자,구체적인 클래스를 사용하기보다느 주로 인터페이스를 사용한다. connection 인스턴스 변수와 셋터 메소드. `MemberDao`에서는 ServletContext`에 접근할 수 없기 때문에, ServletContext에 보관된 DB Connection 객체를 꺼낼 수 없다. 이를 해결하기 위해, 외부로부터 Connection 객체를 주입 받기 위한 셋터 메소드와 인스턴스 변수를 준비한 것이다. ```java Connection connection; public void setConnection(Connection connection){ this.connection = connection } ``` 이렇게 작업에 필요한 객체를 외부로부터 주입받는 것을 '의존성 주입(DI, Dependency Injection)'이라고 부른다. 다른 말로 역제어(IoC, Inversion of Control)라고도 부른다. > 이제 MemberListServlet에서 MemberDao를 사용하는 코드로 변경해보자 ```java public void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { ServletContext sc = this.getServletContext(); Connection conn = (Connection) sc.getAttribute("conn"); MemberDao memberDao = new MemberDao(); memberDao.setConnection(conn); request.setAttribute("members", memberDao.selectList()); response.setContentType("text/html; charset=UTF-8"); RequestDispatcher rd = request.getRequestDispatcher("/member/MemberList.jsp"); rd.include(request, response); } catch (Exception e) { e.printStackTrace(); request.setAttribute("error", e); RequestDispatcher rd = request.getRequestDispatcher("/Error.jsp"); rd.forward(request, response); } } ``` `MemberDao`를 사용하기 전에, 세터를 먼저 호출하여 ServletContext에서 꺼낸 DB 커낵션 객체를 주입했다. ```java ServletContext sc = this.getServletContext(); Connection conn = (Connection) sc.getAttribute("conn"); MemberDao memberDao = new MemberDao(); memberDao.setConnection(conn); ``` 이제 `MemberListServlet`클래스에는 더이상 데이터베이스와 관련된 코드는 없고 `MemberDao`에 이관되었다. 즉 새로 변경된 `MemberListServlet`이 할 일은, 클라이언트의 요청에 대해 어떤 Dao를 사용하고, 어느 JSP로 그 결과를 보내야 하는지 조정(Control)하는 것이다. 이로써 컴포넌트 별로 역할 구분이 명확해졌다. 즉 아래와 같이 구조 변경이 이루어졌다고 생각하면 될것 같다. 서블릿 -> 컨트롤러 Dao -> 모델 JSP -> 뷰 --- ### ServletContextListener 와 객체 공유 서블릿 컨테이너는 웹 에플리케이션의 상태를 모니터링 할 수 있도록 웹 에플리케이션의 시작에서 종료까지 주요한 사건에 대해 알림 기능을 제공한다. 이런 알림 기능을 이용하고 싶다면, 규칙에 따라 객체를 만들어 DD파일(web.xml)에 등록하면 된다. > 이렇게 사건이 발생했을 때 알림을 받는 객체를 '리스너(Listener)' 라고 부른다. 지금까지 작성한 예제의 `서블릿`은 요청을 처리하기 위해 매번 `DAO~ 인스턴스를 생성한다. 이렇게 처리할 때 마다 객체를 만들게 되면 많은 가비지(gabage)가 생성되고, 실행 시간이 길어진다. 서비스를 요청하는 클라이언트가 많아진다면 분명 문제가 될 소지가 있다 `DAO`의 경우처럼 여러 서블릿이 사용하는 객체는 서로 공유하는 것이 메모리 관리나 실행 속도 측면에서 좋다. DAO를 공유하려면 `ServletContext`에 저장하는 것이 좋은데, 그 이유는 **웹에플리케이션이 종료될 때까지 유지되는 보관소**이기 때문이다. > 그러면 서블릿이 사용할 DAO 객체는 언제 준비해야 될까? 공유할 객체들은 서블릿이 실행되기전에 준비되어야 한다. 따라서 보통 웹 에플리케이션을 시작할 때 공유 객체들을 준비한다. 이미 지난 예제과정에서 DB커넥션 객체를 공유하기 위해 `AppInitServlet`을 만든적이 있다. 이 서블릿에서 DAO객체를 준비해도 되지만, 서블릿을 통해 공유 객체를 준비하는 것 보다, 더 좋은 방법이 있다. > 바로 이번 장의 주제인 웹 에플리케이션 이벤트를 이용하는 것이다. 웹에플리케이션이 시작되거나 종료되는 사건이 발생하면, 이를 알리고자 서블릿 컨테이너는 리스너의 메소드를 호출한다. 바로 이 리스너에서 DAO를 준비하면 된다. DAO뿐만 아니라 AppInitServlet이 하던 일도 이 리스너에서 처리하면 된다. #### ServletContextListener의 활용 - 웹 어플리케이션의 시작과 종료 사건을 담당할 리스너를 준비한다. - AppInitServlet이 하던일을 이 리스너로 옮긴다. - MemberDao의 인스턴스 생성도 이 리스너에서 준비한다. #### 리스터 ServletContextListener 만들기 > 웹어플리케이션의 시작과 종료 이벤트를 처리할 리스너는 ServletContextListener 인터페이스를 구현해야 한다. - contextInitialized()는 웹에플리케이션이 시작될 때 호출된다. 공용객체를 준비해야 한다면, 바로 이 메소드에 작성하면 된다. - contextDestroyed()는 웹어플리케이션이 종료되기 전에 호출된다. 자원해체를 해야 한다면, 바로 이 메소드에 작성하면 된다. > 참고로 클래스의 이름을 ContextLoaderListener로 정한 이유는, 나중에 스프링 프레임워크를 배울때 좀더 이해하기 쉽게 만들기 위함인데 스프링에도 같은 역할의 같은 이름을 가진 클래스가 존재한다. ___ > spms.listeners 패키지의 ContextLoaderListener 클래스 ```java package spms.listeners; import java.sql.Connection; import java.sql.DriverManager; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import spms.dao.MemberDao; @WebListener public class ContextLoaderListener implements ServletContextListener { Connection conn; @Override public void contextInitialized(ServletContextEvent event){ try{ ServletContext sc = event.getServletContext(); Class.forName(sc.getInitParameter("driver")); conn=DriverManager.getConnection( sc.getInitParameter("url"), sc.getInitParameter("username"), sc.getInitParameter("password")); MemberDao memberDao = new MemberDao(); memberDao.setConnection(conn); sc.setAttribute("memberDao", memberDao); } catch(Throwable e){ e.printStackTrace(); } } @Override public void contextDestroyed(ServletContextEvent event){ try{ conn.close(); } catch (Exception e){} } } ``` ##### ServletContextListener 인터페이스의 구현 웹 에플리케이션의 시작과 종료사건을 처리하려면, 리스너 클래스는 반드시 ServletContextListener 규칙에 따라 작성해야 한다. 위의 ContextLoaderListener 클래스는 이 인터페이스를 구현하고 있다. ```java public class ContexxtLoaderLister implements ServletContextListener{} ``` ##### contextInitialized() 메소드 contextInitialized()메소드를 보면, AppInitServlet 클래스에 있던 DB커넥션 객체를 준비하는 코드를 가져왔다. ```java Class.forName(sc.getInitParameter("driver")); conn=DriverManager.getConnection(...); ``` > 이 리스너의 핵심은 웹 에플리케이션이 시작될 때 MemberDao 객체를 준비하여 ServletContext에 보관하는 것이다 ```java MemberDao memberDao=new MemberDao(); memberDao.setConnection(conn); sc.setAttribute("memberDao", memberDao); ``` ##### contextDestroyed() 메소드 DB커넥션 객체의 참조변수 'conn'은 리스너의 인스턴스 변수다. 인스턴스 변수로 만든 이유는 contextDestroyed()에서 conn을 사용하기 때문이다. 즉 웹 에플리케이션이 종료되기 저에 데이터베이스와의 연결을 끊어야 하기 때문이다 ##### ContextLoaderListener의 배치 리스너의 배치는 두 가지 방법이 있다. 1. 앞의 예제처럼 어노테이션을 선언하는 방법으로 클래스 선언위에 @WebListener라고 하면 된다. 2. DD파일(web.xml)에 XML 태그를 선언하는 것이다. ```xml <!-- 리스너 선언 --> <listener> <listener-class>spms.listeners.ContextLoaderListener</listener-class> </listener> ``` 위 의 태그를 web.xml 파일의 `<web-app>`태그 안에 작성하면 된다. Servlet 2.4버전 까지는 `<listener>` 태그를 작성할때 순서를 지켜야 한다. 즉, `<filter-mapping>`태그 다음에, `<servlet>`태그 이전에 와야 한다. 2.5버전 부터는 순서에 상관없다. #### 기존의 서블릿 변경하기 기존의 서블릿을 직접 MemberDao 객체를 생성하는대신, ServletContext에 저장된 DAO객체를 꺼내 쓰는것으로 변경해보자 > MemberListServlet 클래스 ```java @Override public void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { ServletContext sc = this.getServletContext(); //변경전 코드 //Connection conn = (Connection) sc.getAttribute("conn"); //MemberDao memberDao = new MemberDao(); //변경된 코드 MemberDao memberDao = (MemberDao)sc.getAttribute("memberDao"); memberDao.setConnection(conn); ... 이하 생략 } ``` > 이렇게 ServletContext에 들어 있는 MemberDao 객체를 재사용하게 되면, 객체를 생성할 필요가 없기 때문에 > 실행속도가 빨라지고, 가비지가 발생하지 않는다. #### AppInitServlet 제거 AppInitServlet 이 하던 일은 ContextLoaderListener로 이관되었다. 이 클래스는 더이상 서블릿으로서 역할을 수행할 필요가 없으므로 DD파일 에서 배치정보를 제거해도 무방하다. --- ### DB 커넥션풀 DB 커넥션 객체를 여러 개 생성하여 풀(Pool)에 담아 놓고 필요할 때 꺼내쓰는 방식으로 즉, 자주 쓰는 객체를 미리 만들어 두고, 필요할 때마다 빌리고, 사용한 다음 반납하는 방식을 `풀링(pooling)`이라 한다. 이렇게 여러 개의 객체를 모아둔 것을 `객체 풀(object pool)`이라고 하고, 여러 개의 DB 커넥션을 관리하는 객체를 DB 커넥션풀 이라고 부른다. 사용한 DB 커넥션 객체는 다른 작업에서 다시 쓸 수 있도록 풀에 반환한다. > 지금까지는 DB 커넥션 객체를 하나만 만들어 사용했고 테스트에도 문제가 없었다. 그럼 왜 DB커넥션 객체를 여러개 생성해야 할까? DAO1~3까지 3개의 DAO가 있다고 가정했을때 이 DAO들이 사용하는 `Statement`는 같은 커넥션에서 생성한 객체이다. SQL문을 실행하다 보면 예외가 발생했을 때 이전 상태로 되도려야 할 경우가 있다. 이렇게 작업하기 전 상태로 되돌리는 것을 `롤백(rollback)`이라고 하는데, 안타깝게도 Statement객체에는 롤백 기능이 없고, 커넥션 객체를 통해서만 롤백을 수행할 수 있다. > 문제는 바로 여기서 발생한다. DAO3가 커넥션 객체의 롤백 기능을 호출할 경우, 그 커넥션을 통해 이루어지는 다른 모든 작업도 롤백된다는 것이다. 즉, DAO1,2가 작업한 것 까지 이전 상태로 되돌려진다. **이러한 이유로 웹브라우져의 요청을 처리할 때, 각 요청에 대해 개별 DB커넥션을 사용해야 한다.** 그리고 이런 문제를 해결하기 위해 등장한 것이 바로 DB 커넥션 풀이기 때문에, 각 요청에 대해 별도의 커넥션 객체를 사용하여 다른 작업에 영향을 주지 않으며, 또한 사용된 DB커넥션 객체는 버리지 않고 풀에 보관해 두었다가 다시 사용한다. 그렇기에 가비지가 생성되지 않고 속도도 빨리지게 된다. <file_sep>/java/god_of_java/Vol.1/16. 이제 기본 문법은 거의 다 배웠으니 정리해 봅시다/README.md ## 16. 이제 기본 문법은 거의 다 배웠으니 정리해 봅시다 ### 1. 객체지향 개발과 관련된 용어들 1. 클래스~class~ 2. 상태~state~와 행위~behavior~ 3. 캡슐화~Encapsulation~ 4. 메시지 5. 객체~Object~ 6. 상속~Inheritance~ 7. 다형성~Polymorphism~ 8. Overriding 9. Overloading ##### 1) 클래스(Class) > `상태` 와 `행위`를 갖는 자바의 기본 단위를 의미한다. ##### 2) 상태(state)와 행위(behavior) > `상태`는 클래스나 인스턴스 변수로, `행위`는 메소드로 표현할 수 있다. ##### 3) 캡슐화(Encapsulation) > 연관된 `상태`와`행위`를 결정하는 기능을 묶어 주는 것을 의미한다. > 이렇게 묶어주면 기능을 클래스 밖에서 접근 가능한 대상을 제한하는 `정보은닉`이 가능하다 > 그리고, 하나의 객체를 위한 코드가, 다른 객체를 위한 코드와 무관하게 수행할 수 있는 `모듈화`가 가능해진다. > 이처럼 묶여 있는 가장 작은 단위를 클래스라고 보면 된다. ```java public class Common{ private int state; //private로 선언함으로써 정보 은닉 public void setState(int newState){ // 상태를 변경 가능 } } ``` ##### 4) 메시지 > 메소드에서 다른 메소드를 호출할 때 전달하는 값을 메시지라고 한다. > 자바에서는 메소드를 호출할 때 넘겨주는 매개 변수들이 여기에 속한다. ##### 5) 객체(Object) > 클래스는 사물의 단위를 의미하지만, 객체는 각 사물을 의미한다. 예를 들면 "책"은 클래스 > <자바의신>은 책 중의 하나를 의미하는 객체라고 볼 수 있다. > `Book javaSolutions=new Book();` ##### 6) 상속 > 부모에 선언된 변수와 메소드에 대한 사용권을 갖는 것을 말한다. > 즉, 클래스 선언시 extends를 사용하여 확장하거나, implements를 사용하여 구현한 경우가 여기에 속한다. ##### 7) 다형성 > 이 세상에 부모와 자식이 똑같을 수가 없고, 자식들도 같을 수가 없다. > 마찬가지로 자바에서는 부모 클래스에서 파생된 자식 클래스들의 기능이 각기 다를 수 있다는 것을 의미한다. ##### 8) Overriding > 부모 클래스에 선언되어 있는 메소드와 동일한 선언을 갖지만 구현이 다른것을 의미한다. > 자바에서 다형성을 제공하는 하나의 방법이 바로 Overriding 이다. ##### 9) Overloading > 메소드의 이름은 동일해도, 매개 변수들을 다르게 하는 것을 의미한다. > 그래서, 동일한 기능은 하지만, 메소드에 넘겨줄 수 있는 매개 변수의 타입을 다양하게 함으로써 메소드를 사용하는 다른 개발자가 쉽게 구현할 수 있게 해준다. --- ### 2. 패키지와 import 패키지는 클래스들을 그룹화하기 위한 단위이다. 만약 이러하나 패키지가 없다면, 자바의 소스코드들은 뒤죽 박죽되어 매우 복잡해질 것이다. 다른 패키지에 선언되어 있는 클래스를 사용하기 위해서는 클래스 선언 앞에 import 문장들이 있어야 한다 패키지 선언시 유의사항들 - 패키지는 `package`로 시작하며 패키지로 내려갈 때마다 `.`을 찍어 주어야 한다. - 반드시 소스의 가장 첫 줄에 존재해야 한다 - 패키지 이름에 자바 예약어가 포함되면 안된다. - 모두 소분자로 구성하는 것이 일반적이다 - 일반적인 패키지는 `java`나 `javax`로 시작하면 안된다. - 패키지에 해당하는 폴더에 클래스가 존재하는 것이 일반적이다. `import`는 - 다른 패키지에 있는 클래스를 사용하기 위한 문장이다. - 다른 클래스에 `static`으로 선언되어 있는 접근 가능한 변수를 참조하려면 `import static`을 사용한다. - 하나의 패키지 내에 있는 모든 클래스를 참조하려면 `*`를 사용 --- ### 3. 자바에서 사용되는 타입의 종류 자바의 타입은 크게 기본 자료형과 참조 자료형으로 나뉜다. 8개의 기본 자료형 숫자와 불린값을 나타내기 위한 자료형으로 마음대로 추가로 만들 수 없다. - 정수형 : byte, short, int, long, char - 소수형 : float, double - 기타 : boolean > 정수형 값의 범위는 다음과 같다. | 타입 | 최소 | 최대 | 비트수 | |-------|---------|---------|----| | byte | -2^7^ | 2^7^-1 | 8 | | short | -2^15^ | 2^15^-1 | 16 | | int | -2^31^ | 2^31^-1 | 32 | | long | -2^63^ | 2^36^-1 | 64 | | char | 0 | 2^16^-1 | 16 | > 기본 자료형의 기본값은 다음과 같다. - byte : 0 - short : 0 - int : 0 - long : 0L - float : 0.0f - double : 0.0d - char : '\u0000' - boolean : false 참조 자료형 기본 자료형을 제외한 모든 타입을 말한다. 모든 클래스는 참조 자료형이라고 생각하면 된다. > 참조 자료형과 기본 자료형의 차이 - 초기화할 때 : 기본 자료형은 값을 바로 지정하면 되지만, 참조 자료형은 일반적으로 `new`와 `생성자`를 지정하여 객체를 생성한다. - 메소드를 호출할 때의 매개 변수 : 기본 자료형 및 참조 자료형 모두 값을 전달하지만, 참조 자료형 안에 있는 변수들은 참조 주소를 전달한다. > 특수한 참조 자료형 - String : String 클래스는 `new`를 이용하여 객체를 생성할 필요가 없는 특수한 클래스다. 그리고, + 연산까지 가능한 유일한 클래스다 --- ### 4. 변수의 종류 자바 변수의 종류 1. `지역변수(local variables)` : 지역 변수를 선언한 곳에서부터 생명이 시작되고, 지역변수를 선언한 중괄호가 끝나면 소멸 2. `매개 변수(parameters)` : 메소드가 호출될 때 생명이 시작되고, 메소드가 끝나면 소멸(정확히 호출될 때 시작하지는 않지만, 이렇게 기억해두어도 무방) 3. `인스턴스 변수(instance variables)` : 객체가 생성될 때 생명이 시작되고, 그 객체를 참조하고 있는 다른 객체가 없으면 소멸 4. `클래스 변수(class variables)` : 클래스가 생성될 때 생명이 시작되고, 자바 프로그램이 끝날 때 소멸 ```java public class VariableTypes{ int instanceVariable; static int classVariable; public void method(int parameter){ int localVariable; } } ``` --- ### 5. 계산을 쉽게 도와주는 연산자들 연산자의 종류 - 할당 연산자 : `=` - 사칙 연산자 : `+`, `-`, `*`, `/`, `%` - 대입 연산자 : `+=`, `-=`, `*=`, `/=`, `%=` - 단항 연산자 : `++`, `--` - 비교 연산자 : `==`, `!=`, `>`, `<`, `>=`, `<=` - 조건적 논리 연산자 : `&&`, `||` - 논리 연산자 : `!`, `&`, `|`, `^` - 삼항 연산자 : `? :` - Bitwise 연산자 : `&(AND)`, `|(OR)`, `^(XOR)`, `~(NOT)` - Bit 이동 연산자 : `<<`, `>>`, `>>>` - Bit 대입 연산자 : `&=`, `|=`, `^=`, `<<=`, `>>=`, `>>>=` > 자세한 연산자 연산순위는 p.461 참조 --- ### 6. 아무나 사용 못하게 막아주는 접근 제어자 자바는 4가지 접근 제어자를 제공한다. 이 접근 제어자는 클래스, 변수, 메소드 등을 선언할 때 사용하고, 선언한 해당 항목의 범위를 제한하는 것이 그 목적이다 - public : 누구나 접근 가능하다 - protected : 같은 패키지 내에 있거나 상속받은 경우에만 접근가능하다. - package-private : 접근제어자 적지 않을 경우이며, 같은 패키지 내에 있을때만 접근가능하다 - private : 해당 클래스 내에서만 접근 가능하다. | | 해당 클래스 안에서 | 같은 패키지에서 | 상속받은 클래스에서 | import한 클래스에서 |--------|--------|--------|-------- | public | O | O | O | O | protected | O | O | O | X | package private | O | O | X | X | private | O | X | X | X --- ### 7. 선언할 때 사용할 수 있는 각종 제어자들 > 클래스, 메소드, 변수를 선언할 때 사용할 수 있는 제어자는 접근 제어자만 있는 것이 아니다. 어떤 제어자들이 어디에서 사용할 수 있는지는 다음 표를 참고 | 제어자 | 클래스 | 메소드 | 변수 | |--------|--------|--------| | 접근제어자 : `public`,`protected`,`private` | O | O | O | | 구현필요제어자 : `abstract` | O | O | X | | 하나의 인스턴스만 허용하는 제어자 : `static` | O | O | O | | 값수정 제한제어자 : `final` | O | O | O | | strict 소수값제어자 : `strictfp` | O | O | X | | 어노테이션 | O | O | O | | 동시접근 제어자 : `synchronized` | X | O | X | | 다른언어로 구현된것을 명시하는 제어자 : `native` | X | O | X | | 실행시의 동작 방법을 알리는 제어자 : `transient`, `volatile` | X | O | O | --- ### 8. 자바를 구성하는 클래스, 인터페이스, abstract 클래스 자바에서 만든 코드를 관리하는 클래스 파일(.class)이 되는 타입의 종류 - 클래스 - 인터페이스 - abstract 클래스 - enum 클래스 - 어노테이션 선언 클래스 > `인터페이스`와 `abstract클래스`, `클래스`의 차이 1) 인터페이스 - 어떤 메소드가 존재해야 하는지에 대한 선언만 되어 있다. - 절대로 구현되어 있는 메소드가 있어서는 안된다. - 인터페이스를 구현하는 클래스에서는 `implements`를 사용하여 선언한다 2) ==abstract== 클래스 - 구현되어 있는 메소드가 있어도 상관없다. - `abstract`로 선언된 메소드가 1개 이상일 경우에는 반드시 abstract 클래스로 선언해야 한다. - `abstract`으로 선언된 메소드는 절대로 구현되어 있어서는 안된다. - `인터페이스`나 `abstract` 클래스와는 다르게 모든 메소드가 구현되어 있어야 한다. 3) 클래스 - `인터페이스`나 `abstract` 클래스와는 다르게 모든 메소드가 구현되어 있어야 한다. > 클래스 선언 예 ```java public class Sample extends SuperClass implements InterfaceA, InterfaceB{ //내용생략 } ``` > Sample이라는 이름을 가지는 클래스 선언 - 파일 이름은 `Sample.java` - 대문자로 시작하고, 추가 단어가 있을 경우에는 첫 문자만 대문자를 사용 > SuperClass라는 클래스를 확장 - `extends` 뒤에 부모 클래스의 이름을 명시하며, 반드시 하나의 클래스만 지정 가능 - `abstract` 클래스도 `extends`로 확장할 수 있다. > InterfaceA 와 InterfaceB를 구현함 - 한개 이상의 구현할 인터페이스 이름을 명시한다. - `implements`로 구현을 한다고 명시할 때에는 인터페이스에 선언된 모든 메소드가 이 클래스에서 구현되어야 한다. > 인터페이스 선언 예 ```java public interface InterfaceA{ public void methodA(); public void methodB(); } ``` - 구현되어 있는 메소드가 하나라도 있으면 안된다 > abstract 클래스 선언 예 ```java public abstract class AbstractClass{ public abstract void methodC(); public void methodD(){ } } ``` - abstract로 선언된 메소드가 하나라도 있을 경우 클래스는 abstract로 선언되어야만 한다 > enum 클래스 선언 예 ```java pubblic enum EnumClass{ THREE_HOUR(18000), FIVE_HOUR(30000), /* 중간 생략 */ } ``` - enum 클래스는 상수를 열거하기 위한 용도로 사용한다. - enum 클래스의 상수는 이름만 정의해도 된다. - 별도의 생성자를 만들어 각 상수의 값을 지정할 수 있다. - 모든 enum 클래스의 부모 클래스는 java.lang.Enum클래스 뿐이다. - enum에 메소드를 만들어 기능 추가 가능 > 어노테이션 선언 예 ```java import java.lang.annotation.*; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface AnnotationDefinition{ public int number(); public String text() default "This is first annotation"; } ``` - 대상(@Target)과 적용범위(@Retention)를 명시하는 것이 좋다 - `@interface`를 상요하여 어노테이션이라는 것을 명시한다 `참고로 interface나 abstract 클래스 모두 클래스 변수나 인스턴스변수를 선언할 수 있으며, 구현 및 확장하는 클래스에서는 이 값들을 사용할 수 있다.` --- ### 9. 메소드의 선언 > 기본적인 메소드의 선언 예 ```java public void method(String param, int... params){ } ``` - `method`라는 이름을 갖는 메소드다 - `public` 과 같은 제어자 선언이 가능하다 - `void`로 선언되어 있어 리턴되는 값이 없다. - `param`이라는 `String`타입의 매개 변수를 가진다. - `params`라는 여러개의 `int` 타입을 콤마로 구분하여 매개 변수로 지정 가능하다. --- ### 10. 자주 사용하게 되는 상속 자바 개발시에는 상속을 자주 사용하게 된다. 만약, 자주 사용하지 않고 상속되어 있는 클래스가 적다면, 리팩토링이라는 단계를 거쳐서 반복되는 메소드를 상위 클래스로 구분해 주는 것이 좋다. 그래야 코드의 재사용성과 유지보수성, 가독성이 높아진다. 상속 관계가 발생했을 때 생성자, 메소드, 변수는 각각 어떻게 지정하고 동작하게 되는지 정리해보자 1) 생성자 - 자식 클래스의 생성자가 호출되면 자동으로 부모 클래스의 매개 변수가 없는 기본생성자가 호출됨. 명시적으로 `super()`라고 지정 가능하다 - 부모 클래스의 생성자를 명시적으로 호출하려면 `super()`를 사용하면 된다. 2) 메소드 - 부모 클래스에 선언된 메소드들이 자신의 클래스에 선언된 것처럼 사용 가능하다(private 제외) - 부모 클래스에 선언된 메소드와 동일한 시그네쳐를 사용함으로써 메소드 `overriding`이 가능하다 - 부모 클래스에 선언되어 있지 않은 이름의 새로운 메소드 선언이 가능하다. 3) 변수 - 부모 클래스에 private로 선언된 변수를 제외한 모든 변수가 자신의 클래스에 선언된 것처럼 사용 가능 - 부모 클래스에 선언된 변수와 동일한 이름을 가지는 변수 선언 가능(권장하지 않음) - 부모 클래스에 선언되어 있지 않는 이름의 변수 선언 가능 --- ### 11.예외를 처리하자 > try-catch 기본구문 ```java try{ //예외가 발생 가능한 문자 } catch(예외1 e1){ // 예외1이 발생했을 때 처리문장 } catch(예외2 e2){ // 예외2가 발생했을 때 처리문장 } finally{ // try나 catch가 어떻게 수행되었든 간에 수행되는 문장 } ``` > 자바에서 사용하는 예외의 종류 - checked exception : try-catch로 묶어줘야 하는 예외이며, 컴파일시 예외처리여부를 체크한다. - error : 자바 프로세스에 영향을 주는 예외이며, 실행시 발생한다. - runtime exception 혹은 unchecked exception : try-catch로 묶지 않아도 컴파일시 체크를 하지 않는 예외이며, 실행시 발생하는 예외이다. > throw 와 throws - `thorw` : 예외 객체를 던지기 위해서 사용한다. - `throws` : 예외가 발생하면 던질 것이라고 메소드 선언시 사용한다. - 메소드를 선언할 때 매개 변수 소괄호 뒤에 `throws`라는 예약어를 적어 준 뒤 예외를 선언하면, 해당 메소드에서 선언한 예외가 발생할 때 호출한 메소드로 예외가 전달된다. - 두 가지 이상의 예외를 던지게 된다면 `implements`처럼 콤마로 구분하여 예외 클래스 이름을 적어준다 - `try` 블록 내에서 예외를 발생시킬 경우에는 throw 라는 예약어를 적어 준 뒤 예외 객체를 생성하거나, 생성되어 있는 객체를 명시한다. - `throw`한 예외 클래스가 catch 블록에 선언되어 있지 않거나, `throws` 선언에 포함되어 있지 않으면 컴파일 에러가 발생한다. - `catch` 블록에서 예외를 `throw`할 경우에는 메소드 선언의 `throws` 구문에 해당 예외가 정의되어 있어야 한다. --- ## 총정리 요약 문제 1) 참조 자료형(Reference type)과 기본 자료형(Primitive type)의 차이를 정리해 주세요. 기본 자료형은 이미 정해져 있는 값으로 정수형 소수형 불린 등이 이에 속한다 또한 마음대로 추가하거나 변경할수 없다. 참조 자료형은 기본형을 제외한 나머지로 주로 클래스가 이에 속하며 일반적으로 new 라는 예약어를 통해 생성한다 . 이때 string은 new없이도 생성가능한 특이한 케이스이다 2) 기본 자료형 8 가지를 나열하고 각 타입의 특징을 정리해 주세요. byte 8비트가 모여 1바이트가 된다. int 정수형으로 데이터 타입으로 일반적으로 가장 많이 사용한다. short 그다음 long 정수형중 가장 큰 범위를 가진다 float 소수형이다. double 소수형으로 일반적으로 가장 많이 사용한다 char 단일 문자열 타입이다. boolean true, false 갑을 가지며 기본값은 false이다 3) 형 변환이란 무엇이고 왜 해야 하나요? 넓은 범위로의 변환은 상관없지만 작은 범위로(축소)변환시에는 캐스팅을 명시적으로 해줘야 한다 4) if 문의 용도는 무엇이며, if-else와 if-else if 는 어떤 점이 다른지 정리해 주세요. 조건문으로 만약 ~~ 라면 else는 if의 조건문에 해당되지 않될경우 넘어가며 순차적으로 체크한다 5) switch-case 문의 용도를 정리해 주세요. 각 조건별로 로직을 수행하게 되며 break 문을 통해 각 케이스별로 설정을 해줘야 한다. 6) for, do-while, while 를 어떻게 사용하는지 1부터 10까지 더하는 코드를 예를 들어 정리해 주세요. ```java int amount =0; for( int i=1; i<=10; i++ ){ amount +=i; } System.out.println(amount); int k=0; int amount3=0; while(k<11){ amount3 += k; k++; } System.out.println("while = "+amount3); ``` 7) 학생이라면 지금까지의 자신의 학점이나 등수를, 회사원이라면 지금까지의 고과를 String 배열에 넣고 출력하는 코드를 작성해 주세요. ```java public void printScore(String score){ System.out.println("Score = "+score); } ``` 8) 생성자는 무엇을 하는데 사용하는 것이며, 별도로 만들지 않아도 자동으로 생성되는 생성자에 대해서 정리해 주세요. 변수를 초기화 하는데 사용되며, 매개변수를 받는 생성자를 별도로 생성하지 않을 경우 기본생성자가 자동으로 생성된다. 9) Overloading은 무엇인가요? public void setData(int a) 라는 메소드를 원하시는 대로 Overloading 해 주세요. ```java public void setData(int a String str){ } ``` 10) 패키지를 선언하는 위치와 이름을 지정할 때의 유의점을 정리해 주세요. 페이지의 최상단에 위치하며 패키지 안으로 들어갈수록 `.`로 연결한다. 또한 이름에 자바 예약어를 사용하면 안되며 보통 소문자로 표기한다. 11) 다른 패키지에 선언된 클래스를 사용하기 위한 import 는 어디 위치에 선언해야하며, static import 은 무엇인지 정리해 주세요. 클래스 상단에 위치하며 패키지 하단에 입력한다. static import 는 static으로 정의된 메소드에 접근할때 사용된다. 12) 클래스란 무엇인가요? 다음의 단어들이 포함되는 문장을 작성하고, 주어진 단어의 의미도 같이 정리해 주세요.(속성, 상태) 자바의 가장 작은 단위로 속성은 인스턴스 변수나 클래스 변수들을 의미하며 상태혹은 속성이라고 정의하며 상태는 행동을 구현하는 메소드들이다. 클래스들은 이러한 것들을 묶어논 것이다. 13) 인터페이스, abstract 클래스, 클래스, Enum 클래스가 있는데 각각의 특징 및 다른 점을 정리해 주세요. 인터페이스는 "이러이러하게" 구현될 것이라고 선언만 해놓고 구현해놓지 않은 것, abstract 클래스는 일부 구현되어있는 클래스로 구현하려는 클래스를 extends로 상속하여 구현한다. enum클래스는 상수를 정의한 클래스들 14) instanceof 라는 연산자의 용도를 정리해 주세요. 배열의 타입이 부모인지 자식인지 확인할때 사용한다. 15) 어떤 클래스를 상속받아 확장을 하면, 부모 클래스의 어떤 것들을 사용할 수 있는지 정리해 주세요. 변수, 메소드에 접근 가능 16) 변수를 final 로 선언하는 것이 어떤 의미가 있는지 정리해 주세요. 값의 변경이 안된다 17) 클래스를 final 로 선언하는 것이 어떤 의미가 있는지 정리해 주세요. 상속을 줄수 없다. 18) 변수를 static 으로 선언하는 것이 어떤 의미가 있는지 정리해 주세요. 클래스 변수로static 메소드에서 접근가능하다 19) 메소드를 static 으로 선언하는 것이 어떤 의미가 있는지 정리해 주세요. 객체를 생성하지 않아도 사용가능하며 단 클래스 변수만 사용가능하다.(인스턴스 변수는 사용 불가능) 20) try-catch-finally 블록은 왜 사용하고 각각의 블록이 어떤용도로 사용되는지 정리해 주세요. 예외처리를 할때 사용되며 try는 예외가 발생할 코드 catch 예외에 해당할때 실행될 코드 finally는 예외에 상관업이 무조건 출력될 부분 <file_sep>/java/god_of_java/Vol.1/02. helloJava/README.md 1. main() 메소드의 메소드 이름 앞에는 어떤 예약어들이 들어 가나요? -> public static void => public : 어떤 클래스에서도 접근 가능하며 static : static 메소드이며( 객체를 생성하지 않아도 접근 가능한 메소드이며 ) void : 리턴값이 없음 2. main() 메소드의 매개 변수에는 어떤 값이 들어가나요? -> String[] args => 즉 String 문자열의 배열이 들어간다. 3. 만약 여러분들이 만든 클래스에 main() 메소드가 없다면, java 명령어로 그 클래스를 수행할 수 있나요? -> 아니요 4. 메소드를 선언할 때 반드시 꼭 있어야 하는 세가지는 무엇인가요? -> 메소드이름, 리턴값 => 메소드이름, 메소드내용, 리턴타입 <file_sep>/게시판만들기/c-cgi-mysql 게시판 만들기/cgi-bin/common.h #include <stdio.h> #include "cgic.h" #include <string.h> #include <stdlib.h> #include <math.h> #define MAX_LEN 255 /* 문자열 배열의 최대 길이 */ #define SITE_URL "http://dev-smc.com/cgi-bin" char seq[MAX_LEN], name[MAX_LEN], title[MAX_LEN], content[MAX_LEN]; char query[MAX_LEN]; int strcheck(char *str) { /* 문자열이 NULL이거나 길이가 0인지 체크 */ if (str == NULL) return 0; if (strlen(str) == 0) return 0; return 1; }<file_sep>/python/algorithm/pairs.py def pairs(a): n=len(a) result = set() for i in range(0, n-1): for j in range(i+1, n): result.add(a[i]+" - " +a[j]) return result v=["Risa", "Jenny", "Jisoo"] print(pairs(v)) <file_sep>/게시판만들기/c-cgi-mysql 게시판 만들기/cgi-bin/pagination.h int page, page_num, limit; int block, block_start_page, block_end_page, total_page, total_block; int query_stat; int list = 10; int block_page_num_list = 5; int total_count = 0; int i, j ,k; // 반복문에 사용할 int 변수 char search_query[MAX_LEN]; void pagingInit(page, list, block_page_num_list, total_count){ if(&page == NULL){ page_num = 1; }else{ page_num = page; } block = ceil((float)page_num/block_page_num_list); if(block < 1){ block = 1; } block_start_page = ( (block - 1) * block_page_num_list )+1; block_end_page = (block_start_page + block_page_num_list) -1; total_page = ceil( (float)total_count/list ); total_block = ceil( (float)total_page/block_page_num_list ); if( block_end_page > total_page ){ block_end_page = total_page; } limit = (page -1)*list; } void pagingData(){ // 처음으로 가기 버튼 if(page_num <= 1){ printf(" <li class='disabled'> \n"); printf(" <a href='#' aria-label='Previous'> \n"); printf(" <span aria-hidden='true'>처음</span> \n"); printf(" </a> \n"); printf(" </li> \n"); }else{ printf(" <li> \n"); printf(" <a href='%s/list.cgi?page=&list=%d%s' aria-label='Previous'> \n", SITE_URL, list, search_query); printf(" <span aria-hidden='true'>처음</span> \n"); printf(" </a> \n"); printf(" </li> \n"); } // 이전 블록으로 이동 if(block <= 1){ }else{ printf(" <li> \n"); printf(" <a href='%s/list.cgi?page=%d&list=%d%s' aria-label='Previous'> \n", SITE_URL, block_start_page-1, list, search_query); printf(" <span aria-hidden='true'>이전</span> \n"); printf(" </a> \n"); printf(" </li> \n"); } // 페이징 출력 부분 for( j=block_start_page; j <= block_end_page; j++ ){ if(page_num == j) { printf("<li class='active'><a href='%s/list.cgi?page=%d&list=%d%s '>%d</a></li> \n", SITE_URL, j, list, search_query, j ); }else{ printf("<li><a href='%s/list.cgi?page=%d&list=%d%s'>%d</a></li> \n", SITE_URL, j, list, search_query, j ); } } // 다음 블록으로 이동 if( block >= total_block ){ } else{ printf(" <li> \n"); printf(" <a href='%s/list.cgi?page=%d&list=%d%s' aria-label='Next'> \n", SITE_URL, block_end_page+1, list, search_query); printf(" <span aria-hidden='true'>다음</span> \n"); printf(" </a> \n"); printf(" </li> \n"); } // 마지막으로 가기 버튼 if(page_num >= total_page){ printf(" <li class='disabled'> \n"); printf(" <a href='' aria-label='Next'> \n"); printf(" <span aria-hidden='true'>마지막</span> \n"); printf(" </a> \n"); printf(" </li> \n"); } else{ printf(" <li> \n"); printf(" <a href='%s/list.cgi?page=%d&list=%d%s' aria-label='Next'> \n", SITE_URL, total_page, list, search_query); printf(" <span aria-hidden='true'>마지막</span> \n"); printf(" </a> \n"); printf(" </li> \n"); } }<file_sep>/javascript/inside_javascript/chapter07 함수형 프로그래밍/README.md ## 7. 함수형 프로그래밍 - 함수형 프로그래밍은 프로그래밍의 여러 가지 패러다임 중 하나이다. - 함수형 프로그래밍은 오랫동안 학문적으로 연구되었고 - 함수형 프로그래밍 언어 역시 역사가 깊다. - 자바스크립트에서 사용되는 함수형 프로그래밍 방식의 여러가지 기본적인 함수를 알아보자 ### 7.1 함수형 프로그래밍의 개념 함수형프로그래밍은 함수의 조합으로 작업을 수행함을 의미한다. 중요한 것은 이 작업이 이루어지는 동안 작업에 필요한 데이터와 상태는 변하지 않는다는 점이다. 변할 수 있는 건 오로지 함수뿐이다. 이 함수가 바로 연산의 대상이 된다. (기존 프로그래밍 방식과 다른만큼 이해하기 어려울수도 있다) 우선 쉬운 예를 들어보자. 이 예는 **함수형 프로그래밍을 표현하는 슈도코드**다. > 아래처럼 특정 문자열을 암호화하는 함수가 여러 개 있다고 하자. ```javascript f1 = encrypt1; f2 = encrypt2; f3 = encrypt3; ``` > 여기서 f1,f2,f3은 입력값이 정해지지 않고, 서로 다른 암호화 알고리즘만 있다. ```javascript pure_value = 'zzoon'; encrypted_value = get_encrypted(x); ``` pure_value는 암호화할 문자열이고, encrypted_value는 암호화된 문자열이다. get_encrypted()는 암호화 함수를 받아서 입력받은 함수로 pure_value를 암호화한 후 반환한다. 즉 다음과 같이 처리할 수 있다. ```javascript encrypted_value = get_encrypted(f1); encrypted_value = get_encrypted(f2); encrypted_value = get_encrypted(f3); ``` 여기서 pure_value는 작업에 필요한 데이터고 작업이 수행되는 동안 변하지 않는다. get_encrypted()가 작업하는 동안 변할 수 있는것은 오로지 입력으로 들어오는 함수뿐이다. f1,f2,f3은 외부(예제에서는 zzoon이라는 변수)에 아무런 영향을 미치지 않는 함수라고 할 수 있다. 이를 **순수 함수**라고 한다. get_encrypted함수는 인자로서 f1,f2,f3함수를 받는다. 그리고 이 예에서는 결과값이 encrypted_value라는 값이지만 결과값을 또 다른 형태의 함수로서 반환할 수도 있다. 이렇게 함수를 또 하나의 값으로 간주하여 함수의 인자 혹은 반환값으로 사용할 수 있는 함수를 **고계함수**라고 한다. 즉 이 예제에서 프로그래머는 입력으로 넣을 암호화 함수를 새롭게 만드는 방식으로 암호화 방법을 개선할 수 있다. 이와 같이 내부 데이터 및 상태는 그대로 둔 채 제어할 함수를 변경 및 조합함으로써 원하는 결과를 얻어내는 것이 함수형 프로그래밍의 중요한 특성이다. 이 특성은 높은 수준의 모듈화가 가능하다는 점에서 큰 장점이 된다. 앞서 설명한 순수함수의 조건을 충족하는 함수 구현으로 모듈 집약적인 프로그래밍이 가능하다 간단한 모듈의 적절한 재구성과 조합으로 프로그래밍할 수 있다. --- ### 7.2 자바스크립트에서의 함수형 프로그래밍 자바스크립트에서도 함수형 프로그래밍이 가능하다. 그 이유는 자바스크립트가 다음을 지원하기 때문이다. - 일급 객체로서의 함수 - 클로저 > 이를 쉽게 이해하려면 앞에서 언급한 암호화 예를 자바스크립트로 구현해 보자. ```javascript var f1 = function(input){ var result; /* 암호화 작업 수행 */ result = 1; return result; } var f2 = function(input){ var result; /* 암호화 작업 수행 */ result = 2; return result; } var f3 = function(input){ var result; /* 암호화 작업 수행 */ result = 3; return result; } var get_encrypted = function(func){ var str = 'zzoon'; return function(){ return func.call(null, str); } } var encrypted_value = get_encrypted(f1)(); console.log(encrypted_value); var encrypted_value = get_encrypted(f2)(); console.log(encrypted_value); var encrypted_value = get_encrypted(f3)(); console.log(encrypted_value); ``` 이처럼 자바스크립트에서 앞서 예로 든 함수형 프로그래밍 슈도코드를 구현할 수 있다. 이것이 가능한 이유는 앞서 언급한 대로 함수가 일급 객체로 취급되기 때문이다. 그래서 함수의 인자로 함수를 넘기고, 결과로 함수를 반환할 수도 있다. 게다가 변수 str 값이 영향을 받지 않게 하려고 클로저를 사용했다. get_encrypted()함수에서 반환하는 익명함수가 클로저다 이 클로저에서 접근하는 변수 str은 외부에서 접근할 수 없으므로 클로저로 함수형 프로그래밍의 개념을 정확히 구현해낼 수 있다. #### 7.2.1 배열의 각 원소 총합 구하기 배열의 각 원소 합을 구하는 프로그램을 작성해 보자( 시그마 ) ```javascript function sum(arr){ var len = arr.length; var i = 0, sum =0; for (; i<len;i++){ sum += arr[i]; } return sum; } var arr = [1, 2, 3, 4, 5]; console.log(sum(arr)); ``` > 이번에는 배열의 각원소를 모두 곱한 값을 구해보자 ```javascript function multiply(arr){ var len = arr.length; var i = 0, result =1; for (; i<len;i++){ result *= arr[i]; } return result; } var arr = [1, 2, 3, 4]; console.log(multiply(arr)); ``` > 위 두개의 에제는 명령형 프로그래밍 방식으로 작성된 코드다 > 문제 하나하나를 각각의 함수를 구현하여 문제를 풀고있다. > 즉 다른 방식의 연산을 원한다면 새로운 함수를 다시 구현해야 한다. > 하지만 함수형 프로그래밍을 이용하면 이러한 수고를 덜 수 있다 ```javascript function reduce(func, arr, memo) { var len = arr.length, i = 0, accum = memo; for (; i < len; i++) { accum = func(accum, arr[i]); } return accum; } var arr = [ 1, 2, 3, 4 ]; var sum = function(x, y) { return x+y; }; var multiply = function(x, y) { return x*y; }; console.log(reduce(sum, arr, 0)); console.log(reduce(multiply, arr, 1)); ``` #### 7.2.2 팩토리얼 먼저 명령형 프로그래밍 방식의 소스를 보자 ```javascript function fact(num) { var val = 1; for (var i = 2; i <= num; i++) val = val * i; return val; } console.log(fact(100)); ``` > 또한 다음과 같이 재귀 호출을 이용할 수도 있다. ```javascript function fact(num) { if (num == 0) return 1; else return num* fact(num-1); } console.log(fact(100)); ``` > 확인해보면 위 두 코드 모두 성공적인 결과가 나온다. > 하지만 이런 종류의 함수 구현은 항상 성능을 고려하게 된다. 이를 함수형 프로그래밍으로 성능을 고려하여 구현해보자 그전에 먼저 팩토리얼 특성을 살펴보자 처음 10!을 실행한 후 20!을 실행한다고 가정해보자 20!을 실행할 때는 앞에서 실행한 10!을 중복하여 계산한다. 이렇게 중복되는 값, 즉 앞서 연산한 결과를 캐시에 저장하여 사용할 수 있는 함수를 작성한다면 성능향상에 도움이 된다. ```javascript var fact = function(){ var cache = {'0' : 1}; var func = function(n){ var result = 0; if (typeof(cache[n]) === 'number'){ result = cache[n]; } else{ result = cache[n] = n * func(n-1); } return result; } return func; }(); console.log(fact(10)); console.log(fact(20)); ``` fact는 cache에 접근할 수 있는 클로저를 반환 받는다. 클로저로 숨겨지는 cache에는 팩토리얼을 연산한 값을 저장하고 있다. 연산을 수행하는 과정에서 캐시에 저장된 값이 있으면 곧바로 그 값을 반환하는 방식이다. 이렇게 하면 한번 연산된 값을 캐시에 저장하고 있으므로, 중복된 연산을 피하여 보다 나은 성능의 함수를 구현할 수 있다. > 메모이제이션 패턴 p.209~212 참조 #### 7.2.3 피보나치 수열 마지막으로 피보나치 수열을 구현해보자 이 절에서는 명령형 프로그래밍 방식을 생략하고 곧바로 함수형 프로그래밍을 알아보자 (메모이제이션 기법) ```javascript var fibo = function(){ var cache = {'0':0,'1':1}; var func = function(n){ if(typeof(cache[n]) === 'number'){ result = cache[n]; } else{ result = cache[n] = func(n-1) + func(n-2); } return result; } return func; }(); console.log(fibo(10)); ``` --- ### 7.3 자바스크립트에서의 함수형 프로그래밍을 활용한 주요 함수 #### 7.3.1 함수 적용 앞서 배운 `Function.prototype.apply` 함수로 함수 호출을 수행할 수 있음을 배웠다 그런데 왜 이름이 `apply`일까? 함수 적용(Applying function)은 함수형 프로그래밍에서 사용되는 용어다. 함수형 프로그래밍에서는 특정 데이터를 여러 가지 함수를 적용시키는 방식으로 작업을 수행한다. 여기서 함수는 단순히 입력을 넣고 출력을 받는 기능을 수행하는 것뿐만 아니라, 인자 혹은 반환 값으로 전달된 함수를 특정 데이터에 적용시키는 개념으로 이해해야 한다. 그래서 자바스크립트에서도 함수를 호출하는 역할을 하는 메소드를 apply라고 이름 짓게 된 것이다. > 따라서 `func.apply(Obj.Args)`와 같은 함수 호출을 'func 함수를 Obj 객체와 Args 인자 배열에 적용시킨다'라고 표현할 수 있다. #### 7.3.2 커링 커링이란 특정 함수에서 인자의 일부를 넣어 고정시키고, 나머지를 인자로 받는 새로운 함수를 만드는 것을 의미한다. ```javascript function Calculate(a, b, c) { return a*b+c; } function Curry(func) { var args = Array.prototype.slice.call(arguments, 1); return function() { return func.apply(null, args.concat(Array.prototype.slice.call(arguments))); } } var new_func1 = Curry(Calculate, 1); console.log(new_func1(2,3)); // 5 var new_func2 = Curry(Calculate, 1, 3); console.log(new_func2(3)); // 6 ``` `calculate()`함수는 인자 세개를 받아 연산을 수행하고 결과값을 반환한다. 여기서 `curry()`함수로 첫 번째 인자를 1로 고정시킨 새로운 함수 new_func1()과 첫 번째, 두 번째 인자를 1과 3으로 고정시킨 new_func2()함수를 새롭게 만들 수 있다. 여기서 핵심적인 역할을 하는 curry()함수의 역할은 간단하다. curry()함수로 넘어온 인자를 args에 담아놓고, 새로운 함수 호출로 넘어온 인자와 합쳐서 함수를 적용한다. 이러한 커링은 함수형 프로그래밍 언어에서 기본적으로 지원하는데, 자바스크립트에서는 기본으로 제공하지는 않는다. 그러나 사용자는 다음과 같이 Function.prototype에 커링 함수를 정의하여 사용할 수있다. ```javascript Function.prototype.curry = function(){ var fn = this, args = Array.prototype.slice.call(arguments); return function(){ return fn.apply(this, args.concat(Array.prototype.slice.call(arguments))); }; } ``` #### 7.3.3 bind `bind`함수는 4장에서 언급됬었다. 이 함수 역시 함수형 프로그래밍 방식을 사용한 대표적인 함수이다. 아래 코드는 bind()함수의 가장 기본적인 기능만을 구현한 코드이다 ```javascript Function.prototype.bind = function (thisArg){ var fn = this, slice = Array.prototype.slice, args = slice.call(argments, 1); return function(){ return fn.apply(thisArg, args.concat(slice.call(arguments))); }; } ``` > 이 앞절에서 살펴본 curry() 함수와 유사한 면에서 보듯이 `bind()`함수는 커링 기법을 활용한 함수이다. 커링과 같이 상요자가 고정시키고자 하는 인자를 bind()함수를 호출할 때 인자로 넘겨주고 반환받은 함수를 호출하면서 나머지 가변 인자를 넣어줄 수 있다. 앞에서 소개한 curry()함수와 다른 점은 함수를 호출할 때 this에 바인딩시킬 객체를 사용자가 넣어줄 수 있다는 점이다. curry() 함수가 자바스크립트 엔진에 내장되지 않은 것도 이 bind()함수로 충분히 커버가 가능하기 때문일 것이다 ```javascript var print_all = function(arg) { for (var i in this){ console.log(i + " : " + this[i]); } for (var i in arguments){ console.log(i + " : " + arguments[i]); } } var myobj = { name : "zzoon" }; var myfunc = print_all.bind(myobj); myfunc(); // name : zzoon var myfunc1 = print_all.bind(myobj, "iamhjoo", "others"); myfunc1("insidejs"); ``` > myfunc()함수는 myobj객체를 this에 바인딩시켜 print_all()함수를 실행하는 새로운 함수이다. > 한발 더 나아가서 my-func1()을 실행하면 인자도 bind()함수에 모두 넘겨진다. > 이와 같이 특정 함수에 원하는 객체를 바인딩시켜 새로운 함수를 사용할 때 bind()함수가 사용된다. #### 7.3.4 래퍼 래퍼(wrapper)란 쉽게 말하면 특정 함수를 자신의 함수로 덮어쓰는 것을 말한다. 객체지향 프로그래밍에서 **다형성**의 특성을 살리려면 **오버라이드**를 지원하는데, 이와 유사한 개념으로 생각하자 ```javascript function wrap(object, method, wrapper){ var fn = object[method]; return object[method] = function(){ //return wrapper.apply(this, [ fn.bind(this) ].concat( return wrapper.apply(this, [ fn ].concat( Array.prototype.slice.call(arguments))); }; } Function.prototype.original = function(value) { this.value = value; console.log("value : " + this.value); } var mywrap = wrap(Function.prototype, "original", function(orig_func, value) { this.value= 20; orig_func(value); console.log("wrapper value : " + this.value); }); var obj = new mywrap("zzoon"); ``` Function.prototype에 original이라는 함수가 있고, 이는 인자로 넘어온 값을 value에 할당하고 출력하는 기능을 한다. 이를 사용자가 덮어쓰기 위해 wrap 함수를 호출하였다. 세번째 인자로 넘긴 자신의 익명 함수를 `Function.prototype.original`에 덮어쓰려는 것이다. > 래퍼는 기존에 제공되는 함수에서 사용자가 원한느 로직을 추가하고 싶다거나, 기존에 있는 버그를 피해가고자 할 때 많이 사용된다. > 특히, 특정 플랫폼에서 버그를 발생시키는 함수가 있을 경우 이를 컨트롤할 수 있으므로 상당히 용이하다 #### 7.3.5 반복함수 ##### 7.3.5.1 each PHP의 foreach 와 유사한 구문이라고 생각하면 된다. 대부분의 자바스크립트 라이브러리에 기본적으로 구현되어 있는 함수이다. jQuery 1.0의 each()함수를 알아보자 ```javascript function each( obj, fn, args ) { if ( obj.length == undefined ) for ( var i in obj ) fn.apply( obj[i], args || [i, obj[i]] ); else for ( var i = 0; i < obj.length; i++ ) fn.apply( obj[i], args || [i, obj[i]] ); return obj; }; each([1,2,3], function(idx, num) { console.log(idx + ": " + num); }); var zzoon = { name : "zzoon", age : 30, sex : "Male" }; each(zzoon, function(idx, value) { console.log(idx + ": " + value); }); ``` ##### 7.3.5.3 reduce reduce()는 배열의 각 요소를 하나씩 꺼내서 사용자의 함수를 적용시킨 뒤, 그 값을 계속해서 누적시키는 함수다. ```javascript Array.prototype.reduce = function(callback) { // this 가 null 인지, 배열인지 체크 // callback이 함수인지 체크 var obj = this; var value, accumulated_value = 0; for ( var i = 0; i < obj.length; i++ ) { value = obj[i]; //console.log("exe"); accumulated_value = callback.call(null, accumulated_value, value); } return accumulated_value; }; var arr = [1,2,3]; var accumulated_val = arr.reduce(function(a, b) { return a + b*b; }); console.log(accumulated_val); ``` 배열의 각 요소를 순차적으로 제곱한 값을 더해 누적된 값을 반환받는 예제다. 각 요소를 사용자가 원하는 특정 연산으로 누적된 값을 반환받고자 할 때 유용하게 사용된다. <file_sep>/git/branch.md 원격저장소로 GitHub을 이용하고 있고, Branch를 만들고 삭제하는 방법에 대해서 알아보자. 1) 브랜치 생성, 삭제 순서 - local 저장소에 branch를 만든다 - remote 저장소로 branch를 push 하여 추적(tracking) 한다 - 사용하지 않는 branch는 삭제한다 //////////////////////////////////////////////// // 새로운 브랜치를 생성하고 checkout 한다 $ git checkout -b shopping_cart Switched to a new branch 'shopping_cart' //////////////////////////////////////////////// // 원격 저장소로 브랜치를 push 한다 $ git push origin shopping_cart Username for 'https://github.com': Password for '<PASSWORD>@yu<EMAIL>@github.com': Total 0 (delta 0), reused 0 (delta 0) To https://github.com/ysyun/pro_git.git * [new branch] shopping_cart -> shopping_cart // github에 새로운 브랜치가 추가 되었다. /////////////////////////////////////////////// // 새로운 파일을 추가하고 원격으로 push 한다 $ touch cart.js $ git add cart.js $ git commit -m "add cart javascript file" [shopping_cart 4856f8d] add cart javascript file 0 files changed create mode 100644 cart.js $ git push Username for 'https://github.com': Password for '<PASSWORD>.<EMAIL>@github.com': Counting objects: 3, done. Delta compression using up to 2 threads. Compressing objects: 100% (2/2), done. Writing objects: 100% (2/2), 245 bytes, done. Total 2 (delta 1), reused 0 (delta 0) To https://github.com/ysyun/pro_git.git f42a865..4856f8d shopping_cart -> shopping_cart /////////////////////////////////////////////// // 로컬 브랜치 내역 과 원격 브랜치 내역을 본다 $ git branch master * shopping_cart $ git branch -r origin/HEAD -> origin/master origin/master origin/shopping_cart //////////////////////////////////////////////////// // 로컬의 새로 추가한 shopping_cart 브랜치를 삭제한다 $ git checkout master Switched to branch 'master' $ git branch -d shopping_cart error: The branch 'shopping_cart' is not fully merged. If you are sure you want to delete it, run 'git branch -D shopping_cart'. $ git branch -D shopping_cart Deleted branch shopping_cart (was 4856f8d). $ git branch * master /////////////////////////////////////////////// // 로컬에 이제 shopping_cart 브랜치가 없다 다시 복구 하고 싶다면 // 원격 저장소를 통하여 checkout 하면 된다 $ git checkout shopping_cart Branch shopping_cart set up to track remote branch shopping_cart from origin. Switched to a new branch 'shopping_cart' $ git branch master * shopping_cart /////////////////////////////////////////////// // 원격의 브랜치 내역을 보자 // 어떤 브랜치들이 존재하는지 한눈에 알 수 있다 $ git remote show origin * remote origin Fetch URL: https://github.com/ysyun/pro_git.git Push URL: https://github.com/ysyun/pro_git.git HEAD branch: master Remote branches: master tracked shopping_cart tracked Local branches configured for 'git pull': master merges with remote master shopping_cart merges with remote shopping_cart Local refs configured for 'git push': master pushes to master (up to date) shopping_cart pushes to shopping_cart (up to date) /////////////////////////////////////////////// // 원격에 있는 브랜치를 삭제 하자 $ git push origin :shopping_cart Username for 'https://github.com': Password for 'https://<EMAIL>@github.com': To https://github.com/ysyun/pro_git.git - [deleted] shopping_cart // shopping_cart 브랜치가 삭제되었음을 알 수 있다 $ git remote show origin * remote origin Fetch URL: https://github.com/ysyun/pro_git.git Push URL: https://github.com/ysyun/pro_git.git HEAD branch: master Remote branch: master tracked Local branch configured for 'git pull': master merges with remote master Local ref configured for 'git push': master pushes to master (up to date) /////////////////////////////////////////////// // remote 브랜치 clean up 하기 $ git remote prune origin UserXP@NUKNALEA /d/Git_repositories/pro_git (master) $ git remote show origin * remote origin Fetch URL: https://github.com/ysyun/pro_git.git Push URL: https://github.com/ysyun/pro_git.git HEAD branch: master Remote branch: master tracked Local branch configured for 'git pull': master merges with remote master Local ref configured for 'git push': master pushes to master (up to date) 2) master가 아닌 local 브랜치를 remote 저장소의 master 브랜치에 push 하기 - 조건 : local 저장소의 브랜치가 master가 아닌 다른 브랜치로 checkout 되어 있을 경우 예) shopping_cart - 명령 : git push [원격저장소 주소 alias] [로컬저장소명칭]:master - 예 : git push origin shopping_cart:master - 의미 : origin 원격 주소의 master 브랜치에 local저장소의 shopping_cart 브랜치를 push 한다<file_sep>/java/god_of_java/Vol.2/02. String/StringSample2.java public class StringSample2 { public static void main(String[] args) { StringSample2 sample=new StringSample2(); sample.constructors(); } public void printByteArray(byte[] array){ for(byte data:array){ System.out.print(data+" "); } System.out.println(); } public void constructors(){ try{ String str="ÇѱÛ"; byte[] array1=str.getBytes(); printByteArray(array1); String str1=new String(array1); System.out.println(str1); byte[] array2=str.getBytes(); printByteArray(array2); String str2=new String(array2, "EUC-KR"); System.out.println(str2); byte[] array3=str.getBytes("UTF-8"); printByteArray(array3); String str3=new String(array3, "UTF-8"); System.out.println(str3); } catch(Exception e){ e.printStackTrace(); } } }<file_sep>/javascript/Ninja_javascript/README.md # JavaScript Ninja (자바스크립트 닌자 비급) ## 1부 훈련준비 ### 1. 닌자입문 #### 생략 ( 소개 내용들 ) ### 2. 테스팅과 디버깅 갖추기 #### 2.1 코드 디버깅 #### 2.2 테스트생성 #### 2.3 테스트 프레임워크 #### 2.4 테스트 스위트의 기본 #### 2.5 정리 <file_sep>/게시판만들기/struts1 게시판 만들기/WEB-INF/classes/my/bbs2/controller/action/BbsRewriteOkAction.java package my.bbs2.controller.action; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import javax.servlet.ServletContext; import javax.servlet.http.*; import com.oreilly.servlet.*; import com.oreilly.servlet.multipart.*; import my.bbs2.BbsManager; public class BbsRewriteOkAction extends Action{ @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { /** * 1. ActionForm은 만들지 않을 예정 * 만든다고 해도 파일 업로드 관련 데이터 * 셋팅이 되지 않으며... * 업로드할 경우 request의 기능이 상실됨. * -->MultipartRequest가 가져가므로.... * */ HttpSession session = request.getSession(); ServletContext ctx = session.getServletContext(); String upDir = ctx.getRealPath("/bbs2/Upload"); MultipartRequest mr = new MultipartRequest(request,upDir,10*1024*1024,"UTF-8", new DefaultFileRenamePolicy()); BbsManager mgr = BbsManager.getInstance(); int result = mgr.rewriteOk(mr); String msg="", url=""; if(result > 0){ msg = "답글쓰기 성공!"; url = "bbs-list.do?method=list"; }else{ msg = "답글쓰기 실패!"; url = "javascript:history.go(-1)"; } request.setAttribute("bbs-msg", msg); request.setAttribute("bbs-url", url); return mapping.findForward("gb-bbs-msg"); //bbs_msg.jsp와 매핑; } //execute() -------------- } /////////////////////////////////////////////////// <file_sep>/게시판만들기/struts1 게시판 만들기/README.md ## 스트럿츠 1 으로 게시판 만들기 기본게시판 - 글쓰기, 글 상세보기, 글편집 분리 - 답글 구현 - 꼬릿말 구현<file_sep>/java/god_of_java/Vol.1/15. 어노테이션이라는 것도 알아야 한다/README.md ## 15. 어노테이션이라는 것도 알아야 한다 ### 1. 어노테이션이란? 어노테이션은 클래스나 메소드 등의 선언시에 `@`를 사용하는 것을 말한다. 어노테이션은 영어로 Annotation이며, 메타데이터~metadata~라고 불리기도 한다. 어노테이션은 다음과 같은 경우에 사용한다 - 컴파일러에게 정보를 알려주거나 - 컴파일할 때와 설치시의 작업을 지정하거나 - 실행할 때 별도의 처리가 필요할 때 이와 같이 매우 다양한 용도로 사용할 수 있는 어노테이션은 클래스, 메소드, 변수등 모든 요소에 선언할 수 있다. > 그런데 이러한 어노테이션이 프로그램에 영향을 미칠까?? 영향이 있는 어노테이션도 있고, 그렇지 않은 것도 있다. ### 2. 미리 정해져 있는 어노테이션들은 딱 3개뿐 > 자바언어에서 사용하기 위해서 정해져 있는 어노테이션은 3개가 있고, 어노테이션을 선언하기 위한 메타 어노테이션이라는 것은 4개가 있다. > 하지만, 이 메타 어노테이션은 선언을 위해서 존재하기 때문에 일반적으로 사용 가능한 어노테이션은 다음의 3개뿐이다. - `@Overrid` - `@Deprecated` - `@SuppressWarnings` (위의 세가지는 JDK 6 기준이다.) 1) `@Override` 해당 메소드가 부모 클래스에 있는 메소드를 Override 했다는 것을 명시적으로 선언하는 기능이지만 잘못 상요할 경우 컴파일 단계에서 에러를 표시해주기때문에 제대로 override 했는지 확인하는 수단으로 사용할 수도 있다. 2) `@Deprecated` 아직 자바API에 대해서 배우지는 않았지만, 미리 만들어져 있는 클래스나 메소드가 더 이상 사용되지 않는 경우가 있다. 그런 것을 deprecated라고 하는데, 컴파일러에게 "얘는 더 이상 사용하지 않으니까 그렇게 알아줘. 그리고, 나중에 누가 이거 쓰면 경고 한번 때려주고..." 라고 일러주는 것이라고 생각하면 된다. > 이렇게 하면 해당 메소드가에 에러가 아닌 경고만 날려주기 때문에, 클래스 파일은 생성된다 3) `@SuppressWarnigs` 간혹 코딩을 하다보면 컴파일러에서 경고~warning~를 알리는 경우가 있다. 프로그램에 문제가 없는데 이럴경우 컴파일러에게 " 얘는 일부러 이렇게 코딩한 거니까 경고 해줄 필요 없어" 라고 이야기 해주는 것이다. #### 정리해 봅시다 1. @Override 어노테이션의 용도는 무엇인가요? -> 오버라이드 했음을 명시적으로 표현해줌 => 메소드가 부모 클래스에 있는 메소드를 Override했다는 것을 명시적으로 선언할 때 @Override 어노테이션을 사용한다. 이 어노테이션을 사용하는 가장 큰 이유는 해당 메소드 선언이 정확히 부모 클래스를 Override했는지를 확인하기 위함이며, 다른 개발자가 해당 코드를 보고 쉽게 이해할 수 있도록 하는 이유도 존재한다. 2. @SupressWarnings 어노테이션의 용도는 무엇인가요? -> 컴파일러에게 이 코드는 문제가 없다고 명시 => 컴파일시 발생 할 수 있는 경고(warning)을 컴파일러에게 이야기 해 주는 것이다. 따라서, 반드시 사용할 필요는 없다. 3. @Deprecated 어노테이션의 용도는 무엇인가요? -> 해당 메소드를 더이상 사용하지 않는다고 명시 => 더 이상 사용하지 않는 메소드를 선언 앞에 @Deprecated 를 사용한다. 만약 해당 메소드를 다른 메소드에서 참조하면, 경고가 발생한다. 4. 어노테이션을 선언할 때 사용하는 어노테이션을 무엇이라고 부르나요? -> @ => 어노테이션을 선언할 때 사용하는 어노테이션을 메타 어노테이션(Meta annotation)이라고 부른다. 5. 4번 문제의 답에 있는 어노테이션들을 사용할 때 import 해야 하는 패키지는 무엇인가요? -> java.lang.annotation => 6. @Target 어노테이션의 용도는 무엇인가요? -> 어노테이션을 어떤 것에 적용할지를 선언할 때 사용한다. => @Target 어노테이션은 선언하는 어노테이션의 적용 범위를 정할 때 사용한다. 7. @Retention 어노테이션의 용도는 무엇인가요? -> 얼마나 오래 어노테이션 정보가 유지되는지를 선언 => 8. @Inherited 어노테이션의 용도는 무엇인가요? -> 모든 자식 클래스에서 부모클래스의 어노테이션을 사용할 수 있다고 선언 => @Inherited 어노테이션은 모든 자식 클래스에서 부모 클래스의 어노테이션을 사용 가능하다는 것을 선언한다. 9. 어노테이션을 선언할 때에는 class 대신 어떤 예약어를 사용해야 하나요? -> @Target => 어노테이션을 선언할 때에는 class라는 예약어 대신 @interface라는 어노테이션을 사용한다. <file_sep>/java/diskstaion_java_lec/02/DataType.java public class DataType { 6. 클래스의 구조 1) 패키지 선언: 최상단에 위치해야 한다 import문 보다도 먼저 와야 함 2) import 문: 사용하고자 하는 패키지 경로를 ㅈ거는다. 3) class 선언: class키워드로 선언하고 클래스 이름을 기재 이때 주의. 클래스명 == 파일명 4) 클래스의 구성원(Member) 1> 속성(멤버변수) ex) int a = 10; int a; 같은 형식으로 선언시 기본값이 들어감 ex) int a; 선언시 0 double d; 선언시 0.0 종류: ㄱ) 클래스변수 : static 변수 ㄴ) 멤버변수 : instance 변수 2> 생성자(Constructor) - 멤버변수의 초기화 ex) int a; public Demo() { a=100; //멤버변수의 초기화 } - 객체를 생성할 때 호출한다. - 생성자 이름 == 클래스 이름 - 반환 타입을 명시하지 않는다. void 등을 면시하면 생성자가 아닌 메소드로 인식해버린다. 3> 메소드 종류: ㄱ) 클래스 메소드 : static메소드 ㄴ) 멤버 메소드 : non-static 메소드 7. 변수란? 값을 담는 바구니라고 생각하자 즉 변수란 값을 저장하는 공간의 위치를 의미한다. 1) 변수의 종류 선언된 위치에 따라 ㄱ) 멤버변수 +--a) 인스턴스 변수 :객체명으로 접근해야 함. +--a) 클래스 변수 :클래스 명으로 접근해야 함 ㄴ) 지역변수 +-- 메소드나 블럭 안에 선언된 변수 local변수, automatic변수라고도 함 !! 주의: 자바의 지역변수는 반드시 초기화하고 사용해야 한다. 인스턴스변수와 클래스 변수는 초기화하지 않아도 디폴트 값이 들어간다. 2) 변수의 명명 규칙 ㄱ) 영문자와 숫자를 섞어 쓸 수 있으나 숫자로 시작되어선 안된다. ㄴ) 한글/한자도 변수명으로 사용가능 ㄷ) 특수문자는 변수로 사용할 수 없다. 단, 언더바, $는 식별자로 사용가능 ㄹ) 변수명은 명사형으로 지으며, 소문자로 시작. 8. 자바의 자료형 1) Primitive Type : 기본자료형 ex) int a = 10; char ch='A'; 2) Reference Type : 참조형 ex) Demo d = new Demo(); 여기서 d는 참조형 변수 /* 아래 String은 new를 사용하지 않으므로 기본자료형으로 생각할 수 있지만 참조형 변수이므로 헷갈리지 말자 엄격하게 쓰려면 new로 사용해야 하지만 너무 많이 사용하므로 저렇게 해놓은듯 */ String str = "hello"; String str = new String("hello"); 2) Reference Type : ㄱ) 클래스형 ㄴ) 인터페이스형 ㄷ) 배열 }<file_sep>/javascript/inside_javascript/chapter03 데이터 타입과 연산자/3_1.js /* ****************************************** 3-1 예제 ********************************************** */ // 숫자 타입 var intNum = 10; var floatNum = 0.1; // 문자열 타입 var singleQuoteStr = 'single quote strign'; var doubleQuoteStr = "double quote string"; var singleChar = 'a'; // 불린 타입 var boolVar = true; // undefined 타입 var emptyVar; // null 타입 var nullVar = null; console.log( typeof inNum, typeof floatNum, typeof singleQuoteStr, typeof doubleQuoteStr, typeof boolVar, typeof nullVar, typeof emptyVar ); /* ****************************************** 3-5 예제 ********************************************** */ // Object()를 이용해서 foo 빈 객체 생성 var foo = new Object(); // foo 객체 프로퍼티 생성 foo.name = 'foo'; foo.age = 30; foo.gender = 'male'; console.log(typeof foo); //출력값 object console.log(foo); //출력값 { name:'foo', age:30, gender:'male'} /* ****************************************** 3-6 예제 ********************************************** */ //객체 리터럴 방식으로 foo 객체 생성 var foo = { name:'foo', age:30, gender:'male' }; console.log(typeof foo); //출력값 object console.log(foo); //출력값 { name:'foo', age:30, gender:'male'} /* ****************************************** 3-7 예제 ********************************************** */ // 객체 리터럴 방식을 통한 foo 객체 생성 var foo = { name : 'foo', major : 'computer science' }; // 객체 프로퍼티 읽기 console.log(foo.name); // foo console.log(foo['name']); // foo console.log(foo.nickname); // undefined // 객체 프로퍼티 갱신 foo.major = 'electronics engineering'; console.log(foo.major); //electronics engineering console.log(foo['major']); //electronics engineering // 객체 프로퍼티 동적 생성 foo.age = 30; console.log(foo.age); // 30 // 대괄호 표기법만을 사용해야 할 경우 foo['full-name'] = 'foo bar'; console.log(foo['full-name']); // foo bar console.log(foo.full-name); // NaN console.log(foo.full); // undefined console.log(name); // undefined /* ****************************************** 3-8 예제 ********************************************** */ // 객체 리터럴을 통한 foo 객체 생성 var foo = { name: 'foo', age: 30, major: 'computer science' }; // for in문을 이용한 객체 프로퍼티 출력 var prop; for (prop in foo) { console.log(prop, foo[prop]); } /* ****************************************** 3-9 예제 ********************************************** */ // 객체를 리터럴 방식으로 생성 //여기서 objA 변수는 객체 자체를 저장하고 있는 것이 아니라 생성된 객체를 가리키는 참조값을 저장하고 있다. var objA = { val : 40 }; // objB에도 objA와 같은 객체의 참조값이 저장된다. var objB = objA; console.log(objA.val); // 40 console.log(objB.val); // 40 objB.val = 50; console.log(objA.val); // 50 console.log(objB.val); /* ****************************************** 3-10 예제 ********************************************** */ var a = 100; var b = 100; var objA = { value: 100 }; var objB = { value: 100 }; var objC = objB; console.log(a == b); // true console.log(objA == objB); // false console.log(objB == objC); // true /* ****************************************** 3-11 예제 ********************************************** */ var a = 100; var objA = { value: 100 }; function changeArg(num, obj) { num = 200; obj.value = 200; console.log(num); console.log(obj); } changeArg(a, objA); console.log(a); console.log(objA); /* ****************************************** 3-12 예제 ********************************************** */ var foo = { name: 'foo', age: 30 }; console.log(foo.toString()); console.dir(foo); /* ****************************************** 3-13 예제 ********************************************** */ // 배열 리터럴을 통한 5개 원소를 가진 배열 생성 var colorArr = ['orange', 'yellow', 'blue', 'green', 'red']; console.log(colorArr[0]); // orange console.log(colorArr[1]); // yellow console.log(colorArr[4]); // red /* ****************************************** 3-14 예제 ********************************************** */ // 빈 배열 var emptyArr = []; console.log(emptyArr[0]); // undefined // 배열 요소 동적 생성 emptyArr[0] = 100; emptyArr[3] = 'eight' emptyArr[7] = true; console.log(emptyArr); // [100, undefined × 2, "eight", undefined × 3, true] console.log(emptyArr.length); // 8 /* ****************************************** 3-16 예제 ********************************************** */ var arr = [0, 1, 2]; console.log(arr.length); // 3 arr.length = 5; console.log(arr); // [0, 1, 2] arr.length = 2; console.log(arr); // [0, 1] console.log(arr[2]); // undefined /* ****************************************** 3-19 예제 ********************************************** */ var emptyArray = []; // 배열 리터럴을 통한 빈 배열 생성 var emptyObj = {}; // 객체 리터럴을 통한 빈 객체 생성 console.dir(emptyArray.__proto__); // 배열의 프로토타입(Array.prototype) 출력 console.dir(emptyObj.__proto__); // 객체의 프로토타입(Object.prototype) 출력 /* ****************************************** 3-20 예제 ********************************************** */ // 배열 생성 var arr = ['zero', 'one', 'two']; console.log(arr.length); // 3 // 프로퍼티 동적 추가 arr.color = 'blue'; arr.name = 'number_array'; console.log(arr.length); // 3 // 배열 원소 추가 arr[3] = 'red'; console.log(arr.length); // 4 // 배열 객체 출력 console.dir(arr); /* ****************************************** 3-21 예제 ********************************************** */ // 배열 생성 var arr = ['zero', 'one', 'two']; // 프로퍼티 동적 추가 arr.color = 'blue'; arr.name = 'number_array'; // 배열 원소 추가 arr[3] = 'red'; for (var prop in arr) { console.log(prop, arr[prop]); } for (var i=0; i<arr.length; i++) { console.log(i, arr[i]); } /* ****************************************** 3-22 예제 ********************************************** */ var arr = ['zero', 'one', 'two', 'three']; delete arr[2]; console.log(arr); // ["zero", "one", undefined × 1 , "three"] console.log(arr.length); // 4 /* ****************************************** 3-23 예제 ********************************************** */ var arr = ['zero', 'one', 'two', 'three']; arr.splice(2, 1); console.log(arr); // ["zero", "one", "three"] console.log(arr.length); // 3 /* ****************************************** 3-24 예제 ********************************************** */ var foo = new Array(3); console.log(foo); // [undefined, undefined, undefined] console.log(foo.length); // 3 var bar = new Array(1, 2, 3); console.log(bar); // [1, 2, 3] console.log(bar.length); // 3 /* ****************************************** 3-25 예제 ********************************************** */ var arr = ['bar']; var obj = { name : 'foo', length : 1 }; arr.push('baz'); console.log(arr); // ['bar', 'baz'] obj.push('baz'); // Uncaught TypeError: Object #<Object> has no method 'push' /* ****************************************** 3-26 예제 ********************************************** */ var arr = ['bar']; var obj = { name : 'foo', length : 1}; arr.push('baz'); console.log(arr); // [‘bar’, ‘baz’] Array.prototype.push.apply(obj, ['baz']); console.log(obj); // { '1': 'baz', name: 'foo', length: 2 } /* ****************************************** 3-29 예제 ********************************************** */ console.log(1 == '1'); // true console.log(1 === '1'); // false /* ****************************************** 3-30 예제 ********************************************** */ console.log(!!0); // false console.log(!!1); // true console.log(!!'string'); // true console.log(!!''); console.log(!!true); console.log(!!false); console.log(!!null); console.log(!!undefined); // false console.log(!!{}); // true console.log(!![1,2,3]); // true /* ****************************************** 3-31 예제 ********************************************** */ /* ****************************************** 3-32 예제 ********************************************** */ /* ****************************************** 3-33 예제 ********************************************** */ <file_sep>/java/god_of_java/Vol.2/03. 가장 많이 쓰는 패키지는 자바랭/README.md ## 3장. 가장 많이 쓴느 패키지는 자바랭 ### java.lang 패키지는 특별하죠 - 자바의 패키지 중에서 유일하게 java.lang 패키지에 있는 클래스들은 import를 안해도 사용할 수 있다. > java.lang 패키지에서 제공하는 인터페이스, 클래스, 예외 클래스 등은 다음과 같이 분류할 수 있다. - 언어 관련 기본 - 문자열 관련 - 기본 자료형 및 숫자 관련 - 쓰레드 관련 - 예외 관련 - 런타임 관련 > p.101 표 참조 ### 숫자를 처리하는 클래스들 - 자바에서 간단한 계산을 할 때에는 대부분 기본 자료형을 사용한다. - 기본자료형은 자바의 `힙heap` 이라는 영역에 저장되지 않고, `스택stack`이라는 영역에 저장되어 관리된다. 따라서 계산할 때 보다 빠른 처리가 가능하다 > 이에 관한 더욱 자세한 내용은 [구글 "java stack primitive types" 검색 바로가기](https://www.google.co.kr/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=java%20stack%20primitive%20types) 그런데, 이러한 기본 자료형의 숫자를 객체로 처리해야 할 필요가 있을 수도 있다. 따라서, 자바에는 다음과 같이 기본 자료형으로 선언되어 있는 타입의 클래스들이 선언되어 있다. - Byte - Short - Integer - Long - Float - Double - Character - Boolean > 보다시피 Chracter, Integer 클래스를 제외하고 나머지는 각 기본자료형의 이름에서 첫문자만 대문자로 바뀌었다. - Character와 Boolean을 제외한 숫자를 처리하는 클래스들은 감싼(Wrapper)클래스라고 불리며, 모두 `Number`라는 `abstract 클래스`를 `확장(extends)`한다. - 그리고, 겉으로 보기에는 참조 자료형이지만, 기본 자료형 처럼 사용할 수 있다. - 그 이유는 자바 컴파일러에서 자동으로 형 변환을 해주기 때문이다. > Charcter 클래스를 제외하고 전부 공통적인 메소드를 제공한다. > 바로 parse타입이름() 메소드와 valueOf()라는 메소드다. 이 두가지 메소드는 모두 static메소드다. > ( 즉 객체생성없이 바로 사용이 가능하다는 말 ) > 둘다 String과 같은 문자열을 숫자 타입으로 변환한다는 공통점이 있지만, > person타입이름() 메소드는 기본 자료형을 리턴하고, valueOf()메소드는 "참조 자료형"을 리턴한다. ```java public class JavaLang { public static void main(String[] args) { JavaLang sample = new JavaLang(); sample.numberTypeCheck(); } public void numberTypeCheck() { String value1 = "3"; String value2 = "5"; // 3과 5라는 String값을 parseByte() 메소드를 사용하여 byte로 변환 byte byte1 = Byte.parseByte(value1); byte byte2 = Byte.parseByte(value2); System.out.println(byte1 + byte2); Integer refInt1 = Integer.valueOf(value1); Integer refInt2 = Integer.valueOf(value2); System.out.println(refInt1 + refInt2 + "7"); } public void numberTypeCheck2(){ Integer refInt1; refInt1=100; System.out.println(refInt1.doubleValue()); } } ``` > 왜 혼동되게 이러한 숫자를 처리하는 참조 자료형을 만들었을까? - 매개 변수를 참조자료형으로만 받는 메소드를 처리하기 위해서 - 제네리과 같이 기본자료형을 사용하지 않는 기능을 사용하기 위해서 - MIN_VALUE(최소값)나 MAX_VALUE(최대값)와 같이 클래스에 선언된 상수 값을 사용하기 위해서 - 문자열을 숫자로, 숫자를 문자열로 쉽게 변환한고, 2,8,10,16 진수 변환을 쉽게 처리하기 위해서 상수값과 메소드 기본자료형을 참조 자료형으로 만든 클래스들은 boolean클래스를 제외하고 모두 `MIN_VALUE`와 `MAX_VALUE`라는 상수를 갖고 있다. 해당 타입이 나타낼 수 있는 갑의 범위를 확인하려면 static으로 선언되어 있는 이 상수들을 다음과 같이 사용하면 된다. ```java public void numberMinMaxCheck() { long startTime = System.currentTimeMillis(); long startNanoTime = System.nanoTime(); System.out.println("Byte min=" + Byte.MIN_VALUE + " max=" + Byte.MAX_VALUE); System.out.println("Short min=" + Short.MIN_VALUE + " max=" + Short.MAX_VALUE); System.out.println("Integer min=" + Integer.MIN_VALUE + " max=" + Integer.MAX_VALUE); System.out.println("Long min=" + Long.MIN_VALUE + " max=" + Long.MAX_VALUE); System.out.println("Float min=" + Float.MIN_VALUE + " max=" + Float.MAX_VALUE); System.out.println("Double min=" + Double.MIN_VALUE + " max=" + Double.MAX_VALUE); System.out.println("Character min=" + (int) Character.MIN_VALUE + " max=" + (int) Character.MAX_VALUE); } ``` > 출력결과 ```java Byte min=-128 max=127 Short min=-32768 max=32767 Integer min=-2147483648 max=2147483647 Long min=-9223372036854775808 max=9223372036854775807 Float min=1.4E-45 max=3.4028235E38 Double min=4.9E-324 max=1.7976931348623157E308 Character min=0 max=65535 ``` > 값을 알아보기 힘든 Long타입을 2진수나 16진수로 보고 싶으면 Integer클래스에서 제공하는 > `toBinaryString()`메소드 등을 사용하자 ```java System.out.println("Integer BINARY min=" + Integer.toBinaryString(Integer.MIN_VALUE)); System.out.println("Integer BINARY max=" + Integer.toBinaryString(Integer.MAX_VALUE)); System.out.println("Integer HEX min=" + Integer.toHexString(Integer.MIN_VALUE)); System.out.println("Integer HEX max=" + Integer.toHexString(Integer.MAX_VALUE)); ``` > 만약 돈 계산과 같이 중요한 연산을 수행할 때, 정수형은 BigIntefer, 소수형은 BigDecimal을 사용해야 정확한 계산이 가능하다. > 이 두 클래스들은 모두 java.lang.Number 클래스의 상속을 받았으며, java.math 패키지에 선언되어 있다. ### 각종 정보를 확인하기 위한 System 클래스 - 이 클래스의 가장 큰 특징은 생성자가 없다는 것이다. System클래스에 3개의 `static` 변수가 선언되어 있다. - `static PrintStream` - `err` : 에러 및 오류를 출력할 때 사용 - `static InputStream` - `in` : 입력값을 처리할 때 사용 - `static PrintStream` - `out` : 출력값은 처리할 때 사용 > 익숙한 구문을 통해 분석해보자 ```java System.out.println(); ``` - System : 클래스이름 - out : static으로 선언된 변수이름 > `out`은 `PrintStream` 타입이다. 그러므로 `println()`이라는 메소드는 `PrintStream 클래스`에 선언되어 있으며, static 메소드다 처음에 그냥 생각하기로는 System 클래스는 출력만을 위한 클래스라고 생각할 수 도 있다. 그러나 실제 System클래스에 선언되어 있는 메소드들을 살펴보면 출력과 관련된 메소드들은 없다. System 클래스는 이름 그대로 시스템에 대한 정보를 확인하는 클래스이며, 이 클래스에서 제공되는 메소드를 분류해보면 다음과 같이 다양한 역할을 한다는 것을 알 수 있다. - 시스템 속성(Property)값 관리 - 시스템 환경(Environment)값 조회 - GC 수행 - JVM 종료 - 현재시간조회 - 기타 관리용 메소드들 > 이 중 절대로 수행해서는 안 되는 메소드의 분류가 2개있다. > 바로 GC 수행과 JVM종료 관련 메소드다. #### 시스템 속성(Property)값 관리 - `Properties`는 java.util 패키지에 속하며, `Hashtable`의 상속을 받은 클래스다. - 우리의 필요 여부와 상관없지 자바 프로그램을 실행하면 지금 `Properties` 객체가 생성되며, 그 값은 언제, 어디서든지 같은 JVM내에서는 꺼내서 사용할 수 있다. ```java public void systemPropertiesCheck() { System.out.println("java.version=" + System.getProperty("java.version")); } ``` > 출력결과 ```java java.version=1.7.0_80 ``` #### 시스템 환경(Environment)값 조회 - 이전에 살펴본 Properties라는 것은 추가할 수도 있고, 변경도 할 수 있다. - 하지만 환경 값이라는 enc라는 것은 변경하지 못하고 읽기만 할 수 있다. - 이 값들은 대부분 OS나 장비와 관련된 것들이다. ```java System.out.println("JAVA_HOME=" + System.getenv("JAVA_HOME")); ``` > 출력결과 ```java JAVA_HOME=C:\Program Files\Java\jdk1.7.0_80 ``` #### GC 수행 - `static void gm()` - `static void runFinalization()` - 앞서 위 두개의 메소드는 사용하면 안된다고 했었다. > 그 이유는 자바는 메모리 처리를 개발자가 별도로 하지 않는다. > 따라서 `System.gc()`라는 메소드를 호출하면 가비지 컬렉션을 명시적으로 처리하도록 할 수 있다. > 또한 Obejct 클래스에 선언되어 있는 finalize()메소드를 명시적으로 수행하도록 하는 runFinalization()메소드가 있다. 이 두개의 메소드들을 우리가 호출하지 않아도 알아서 `JVM`이 더 이상 필요 없는 객체를 처리하는 GC작업과 finalization 작업을 실행한다. 만약 명시적으로 이 두 메소드를 호출하는 코드를 집어 넣으면, 시스템은 하려던 일들을 멈추고 이 작업을 실행한다. #### JVM 종료 - `static void exit(int status)`이 메소드 역시 절~~~~대 호출되면 안 되는 것중 하나다. - 안드로이드 앱이나, 웹 애플리케이션에서 이 메소드를 사용하면 해당 애플리케이션의 JVM 이 죽어버린다. #### 현재 시간 조회 - `static long currentTimeMillis()` - 현재 시간을 밀리초 단위로 리턴 - `static long nanoTime()` - 현재 시간을 나노초 단위로 리턴 --- ### System.out을 살펴보자 - 객체를 출력할 때에는 toString()을 사용하는 것보다는 valueOf()메소드를 사용하는 것이 훨씬 안전하다 > print() 메소드와 println()메소드에서는 단순히 toString()메소드 결과를 출력하지 않기 때문이다 > String의 valueOf()라는 static 메소드를 호출하여 결과를 받은 후 출력한다. ### 수학적인 계산을 위해서 꼭 필요한 Math 클래스 - 자바에는 Math라는 수학을 계산하는 클래스를 제공한다. - Math만이 아니라 StricMath 라는 클래스도 자바랭 패키지에 있다. (어떤 OS나 어떤 시스템 아키텍처에서 수행되든간에 동일한 값을 리턴해야 한다는 기준에 의해 만들어진 클래스다) > Math 클래스에 있는 상수나 메소드는 모두 static으로 선언되어 있기 때문에 별도의 객체를 생성할 필요가 없다. - (double) E : 자연 로그 알고리즘에 기반하여 지수인 e에 근사한 값을 제공한다. - (double) PI : 파이값 ##### 절대값 및 부호 관련 - abs() : 절대값 계산 - signum() : 부호확인 (양수는 1.0, 음수는 -1.0, 0은 0을 리턴) ##### 최대 /최소값 관련 - min() - max() ```java public void mathCheck1() { double number1 = 45; double number2 = -45; System.out.println("Math.abs(45)=" + Math.abs(number1)); System.out.println("Math.abs(-45)=" + Math.abs(number2)); System.out.println("Math.signum(45)=" + Math.signum(number1)); System.out.println("Math.signum(-45)=" + Math.signum(number2)); System.out.println("Math.min(45,-45)=" + Math.min(number1, number2)); System.out.println("Math.max(45,-45)=" + Math.max(number1, number2)); } ``` ##### 올림 / 버림 관련 - round() : 반올림 float->int, double->long - rint() : 반올림 double->double - ceil) : 올림 - floor() : 버림 ```java public void mathCheck2() { double[] numbers = new double[] { 3.15, 3.62, -3.15, -3.62 }; for (double number : numbers) { System.out.println(number); System.out.print("Math.round()=" + Math.round(number)); System.out.print(" Math.rint()=" + Math.rint(number)); System.out.print(" Math.ceil()=" + Math.ceil(number)); System.out.print(" Math.floor()=" + Math.floor(number)); System.out.println(); } } ``` > round()를 제외한 나머지는 double 타입 그대로 리턴한다. > 만약 double 형 반올림 결과가 필요하다면 round()가 아닌 rint()를 사용하면 된다. ##### 제곱과 제곱근 관련 - sqrt() : 매개변수의 제곱근을 구한다. - cbrt() : 매개 변수의 세제곱근을 구한다. - pow() : 첫번째 매개 변수의 두번째 매개 변수만큼의 제곱값을 구한다. ```java public void mathCheck3() { System.out.println("Math.sqrt(1)=" + Math.sqrt(1)); System.out.println("Math.sqrt(2)=" + Math.sqrt(2)); System.out.println("Math.cbrt(8)=" + Math.cbrt(8)); System.out.println("Math.cbrt(27)=" + Math.cbrt(27)); System.out.println("Math.pow(2,2)=" + Math.pow(2, 2)); System.out.println("Math.scalb(2,4)=" + Math.scalb(2, 4)); System.out.println("Math.hypot(3,4)=" + Math.hypot(3, 4)); System.out.println("Math.sqrt(Math.pow(3,2)+Math.pow(4,2))=" + Math.sqrt(Math.pow(3, 2) + Math.pow(4, 2))); } ``` ##### 삼각함수 관련 - toRadians() : 각도를 레디안 값으로 변환 - toDegress() : 레디안 값을 각도로 변환 - sin() : 사인 값 - cos() : 코사인 값 - tan() : 탄젠트 값 > 삼각함수의 매개변수로 넘어가는 값은 모두 레디안 값으로 제공되어야만 한다 > 따라서 360도 기준으로 되어있는 가도 값을 계산할때는 toRadians()메소드를 사용하여 레디안으로 변환후 값을 구하자 ```java public void mathCheck4() { double number1 = 45; double number2 = 90; double radian45 = Math.toRadians(number1); double radian90 = Math.toRadians(number2); System.out.println("Radian value of 45 degree is " + radian45); System.out.println("Radian value of 90 degree is " + radian90); System.out.println("Math.sin(45 degree)=" + Math.sin(radian45)); System.out.println("Math.sin(90 degree)=" + Math.sin(radian90)); System.out.println("Math.cos(45 degree)=" + Math.cos(radian45)); System.out.println("Math.cos(90 degree)=" + Math.cos(radian90)); System.out.println("Math.tan(45 degree)=" + Math.tan(radian45)); System.out.println("Math.tan(90 degree)=" + Math.tan(radian90)); } ``` --- ### 직접해 봅시다 ```java public class NumberObject { public static void main(String[] args) { NumberObject no=new NumberObject(); //no.parseLong("r1024"); //no.parseLong("1024"); no.printOtherBase(1024); } public long parseLong(String data){ long longdata=-1; try{ longdata=Long.parseLong(data); System.out.println(longdata); } catch(NumberFormatException ne){ System.out.println(data+" is not a number"); } catch(Exception e){ } return longdata; } public void printOtherBase(long value){ System.out.println("Original:"+value); System.out.println("Binary:"+Long.toBinaryString(value)); System.out.println("Hex:"+Long.toHexString(value)); System.out.println("Octal:"+Long.toOctalString(value)); } } ``` --- ### 정리해 봅시다 1. java.lang 패키지는 별도로 import하지 않아도 된다. 2. 자바의 메모리가 부족하여 발생하는 에러는 OutOfMemoryError이다. 이 에러에 대한 보다 자세한 설명은 "자바 개발자와 시스템 운영자를 위한 트러블 슈팅 이야기"를 참조하기 바란다. 3. 자신의 메소드를 자기가 다시 부르는 재귀 호출 메소드와 같은 것을 잘못 구현하면 StackOverflowError가 발생한다. 4. java.lang 패키지에 선언되어 있는 어노테이션은 다음과 같다. - Deprecated : 더 이상 사용하지 않는 다는 것을 명시 - Override : Override 명시 - SuppressWarnings : 경고 무시 5. 기본 자료형을 참조자료형으로 만든 클래스들의 MIN_VALUE(최소값)와 MAX_VALUE(최대값) 를 사용하면, 각 타입의 최대 최소값을 확인할 수 있다. 6. Integer클래스의 toBinaryString() 메소드를 호출하면 매개변수의 값을 2진법으로 나타낸다. 7. Integer클래스의 toHexString() 메소드를 호출하면 매개변수의 값을 2진법으로 나타낸다. 8. Properties는 JVM에서 사용하는 속성 값을 제공하며, Environmemt는 시스템(장비)에서 사용하는 환경 값을 제공한다. 9. System.out과 System.err는 모두 java.io.PrintStream 클래스를 의미한다. 10. System.currentTimeMillis() 메소드를 호출하면 현재 시간을 밀리초(1/1000)단위로 제공한다. 이 시간은 1970년 1월 1일 00:00 부터 현재까지의 시간이다. 11. System.nanoTime() 메소드는 나노초 단위로 결과를 제공하며, 이 메소드에서 제공하는 시간은 오직 소요 시간을 측정하기 위해서 사용된다. 12. System.out.print() 메소드는 데이터를 출력후 줄바꿈을 하지 않으며, System.out.println()메소드는 데이터를 출력후 줄바꿈을 수행한다. 13. System.out.println() 메소드에서 출력을 할 때에는 String 클래스에 선언된 valueOf()메소드가 수행된다. toString()메소드가 수행되는 것이 아니다. 14. 숫자 계산을 위해서 Math라는 클래스가 존재한다. 15. Math 클래스에 있는 상수와 메소드는 모두 static 으로 선언되어 있기 때문에 별도의 객체를 선언할 필요가 없다. 16. 숫자의 절대값은 Math 클래스의 abs() 메소드를 사용하면 된다. 17. 반올림을 하는 Math 클래스의 메소드는 round()와 rint() 이다. 18. Math클래스에서 Radian으로 변환하는 메소드는 toRadians()메소드이며, Degree로 변환하는 메소드는 toDegrees() 메소드이다. 19. Math 클래스의 pow() 메소드는 제곱값을 구하는 데 사용한다. 5의 4제곱은 Math.pow(5,4)과 같이 사용하면 된다. <file_sep>/php/04. 조건문.md ## 조건문 ** << 목록 >> ** 1 . Boolean 2 . 조건문 3 . 조건문의 문법 : if / else / else if 4 . 변수와 비교연산자 그리고 조건문 5 . 조건문의 중첩 6 . 논리연산자 7 . boolean의 대체제 --------------- ##### Boolean * 비교연산의 결과로 **참**이나 **거짓**을 얻을 수 있다고 배웠다. * 여기서 참과 거짓은 '숫자와 문자'에서 배운 숫자와 문자처럼 언어에서 제공하는 **데이터 형**이다. * 이를 불린(Boolean)이라고 부르고, 불린으로 올 수 있는 값은 true와 false 두가지 밖에 없다. * 불린은 조건문에서 핵심적인 역할을 담당한다. --------------- ##### 조건문 * 조건문은 **주어진 조건**에 따라서 에플리케이션을 다르게 동작하도록 하는 것이다. * --------------- ##### 조건문의 문법 ###### if * 조건문은 if로 시작한다. if 뒤에 괄호가 있고, 괄호 안에 조건이 위치한다. * 조건이 될 수 있는 값은 Boolean이다. * Boolean의 값이 true라면 조건을 감싸고 있는 괄호 다음의 중괄호 구간이 실행된다. <br> ** << 조건에 true 1 >> ** ```php <?php if(true) { echo 'result : true'; } ?> ───────────── 출력 ──────────────── result : true ``` 위의 예제는 if의 조건문이 true이므로 if의 문장을 실행하여 "result : true"를 출력한 것이다. <br> ** << 조건이 false 1 >> ** ```php <?php if(false) { echo 'result : true'; } ?> ───────────── 출력 ──────────────── ``` 위의 예제는 if의 조건문이 false 이므로 if의 문장을 실행하지 않았기때문에 출력값이 없다. <br> ** << 조건이 true 2 >> ** ```php <?php if(true){ echo 1; echo 2; echo 3; echo 4; } echo 5; ?> ───────────── 출력 ──────────────── 12345 ``` <br> ** << 조건이 false 2 >> ** ```php <?php if(false){ echo 1; echo 2; echo 3; echo 4; } echo 5; ?> ───────────── 출력 ──────────────── 5 ``` ###### else if만으로는 좀 더 복잡한 상황을 처리하는데 부족하다. ```php <?php if(true) { echo 1; } else { echo 2; } ?> ───────────── 출력 ──────────────── 1 ``` ```php <?php if(false) { echo 1; } else { echo 2; } ?> ───────────── 출력 ──────────────── 2 ``` else 뒤에 따라오는 중괄호는 주어진 조건이 false일 때 실행될 로직이 위치한다. 참일 때와 거짓일 때 각각 다른 동작을 하도록 하는 기능이다. <br> ###### else if else if 만으로는 좀 더 복잡한 상황을 처리하는데 부족하다. ```php <?php if(false) { echo 1; } else if(true) { echo 2; } else if(true) { echo 3; } else { echo 4; } ?> ───────────── 출력 ──────────────── 2 ``` ```php <?php if(false) { echo 1; } else if(false) { echo 2; } else if(true) { echo 3; } else { echo 4; } ?> ───────────── 출력 ──────────────── 3 ``` ```php <?php if(false) { echo 1; } else if(false) { echo 2; } else if(false) { echo 3; } else { echo 4; } ?> ───────────── 출력 ──────────────── 4 ``` else if는 좀 더 다양한 케이스의 조건을 검사할 수 있는 기회를 제공한다. else if의 특징은 if나 else와는 다르게 여러개가 올 수 있다는 점이다. else if의 모든 조건이 false라면 else가 실행된다. else는 생략이 가능하다. --------------- ##### 변수와 비교연산자 그리고 조건문 * 앞에서 배운 변수와 비교연산자 그리고 조건문을 결합해서 간단한 형태의 로그인 에플리케이션을 구현해보자. 1. 우선 아이디를 입력할 수 있는 HTML폼을 만든다. 2. HTML폼에서 전송한 데이터를 처리할 PHP 에플리케이션을 만든다. <br> << get방식을 이용하여 id 입력값 전달하는 html >> ```xml <html> <body> <form method='get' action='11.php'> <input type='text' name='id'> <input type='submit'> </form> </body> </html> ``` <br> << php에서 받은 값을 처리 >> ```php <?php if($_GET['id'] === 'egoing') { echo 'right'; } else { echo 'wrong'; } ?> ``` html에서 넘어온 id값이 'egoing'과 일치한다면 'right'를 출력하고, 일치하지 않다면 'wrong'을 출력한다. --------------- ##### 조건문의 중첩 * 위의 예제에서 아이디와 비밀번호를 모두 검증해야 한다면 어떻게 하면 될까 ? 다음 예제를 보자 <br> << post방식을 이용하여 id 입력값 전달하는 html >> ```xml <html> <body> <form method='post' action='13.php'> id : <input type='text' name='id'> password : <input type='text' name='password'> <input type='submit'> </form> </body> </html> ``` <br> << html로부터 전달받은 값을 처리 >> ```php <?php if($_POST['id'] === 'egoing') { // id가 'egoing'이라면 if($_POST['password'] === '<PASSWORD>'){ // password가 <PASSWORD>이라면 echo 'right'; // 'right' 출력 } else { // password가 <PASSWORD>이 아니면 echo 'password wrong'; // password wrong 출력 } } else { // id가 'egoing'이 아니면 echo 'id wrong'; // id wrong 출력 } ?> ``` --------------- ##### 논리연산자 논리연산자는 조건문을 더 간결하고 다양한 방법으로 구사할 수 있도록 도와준다. <br> ###### and * and는 좌항과 우항이 모두 참(true)일때 참이 된다. &&을 사용해도 된다. * 다음의 예제를 보자 . 결과는 1이다. and의 좌우항이 모두 true인 것은 첫번째 조건문 밖에 없기 때문이다. ```php <?php if (true and true) { echo 1; } if (true and false) { echo 2; } if (false and true) { echo 3; } if (false and false) { echo 4; } ?> ───────────── 출력 ──────────────── 1 ``` <br> 논리 연산자를 이용한 사례를 살펴보자. 다음 예제는 논리 연산자를 이용해서 이전 예제를 개선한 것이다. << post방식을 이용하여 id 입력값 전달하는 html >> ```xml <html> <body> <form method='post' action='13.php'> id : <input type='text' name='id'> password : <input type='text' name='password'> <input type='submit'> </form> </body> </html> ``` <br> << html로부터 전달받은 값을 처리 >> ```php <?php if( $_POST['id'] === 'egoing' && $_POST['password'] === '<PASSWORD>' ) { // id가 'egoing'이라면 echo 'right'; // 'right' 출력 } else { // id가 'egoing'이 아니거나 password가 <PASSWORD>이 아니면 echo 'id wrong'; // id wrong 출력 } ?> ``` <br> ###### or or는 or의 좌우항 중에 하나라도 true라면 true가 되는 논리연산자이다. 다음의 예는 1,2,3을 출력한다. 마지막 조건문의 or는 좌항과 우항이 모두 false이기 때문에 false가 된다. ```php <?php if (true or true) { echo 1; } if (true or false) { echo 2; } if (false or true) { echo 3; } if (false or false) { echo 4; } ?> ───────────── 출력 ──────────────── 123 ``` <br> 논리 연산자를 이용한 사례를 살펴보자. 다음 예제는 논리 연산자를 이용해서 이전 예제를 개선한 것이다. << post방식을 이용하여 id 입력값 전달하는 html >> ```xml <html> <body> <form method='post' action='13.php'> id : <input type='text' name='id'> <input type='submit'> </form> </body> </html> ``` <br> << html로부터 전달받은 값을 처리 >> ```php <?php // id 가 egoing 이거나 09876 이거나 111111이면 if( $_POST['id'] === 'egoing' or $_POST['id']='09876' or $_POST['id'] === '111111' ) { // 'right' 출력 echo 'right'; // id가 위의 조건에 하나도 맞지 않다면 } else { // id wrong 출력 echo 'id wrong'; } ?> ``` <br> 다음은 post방식을 이용하여 id 와 password값을 전달하는 html이다. ```xml <html> <body> <form method='post' action='13.php'> id : <input type='text' name='id'> password : <input type='text' name='<PASSWORD>'> <input type='submit'> </form> </body> </html> ``` <br> << html로부터 전달받은 값을 처리 >> ```php <?php // id 가 egoing 이거나 09876 이거나 111111이고, password가 <PASSWORD>이면 if( ( $_POST['id'] === 'egoing' or $_POST['id']='09876' or $_POST['id'] === '111111' ) and $_POST['password'] === '<PASSWORD>' ){ // 'right' 출력 echo 'right'; // id가 위의 조건에 하나도 맞지 않고, password가 <PASSWORD>가 아니면 } else { // id wrong 출력 echo 'id wrong'; } ?> ``` ##### ! !는 not ,즉 부정의 의미로, Boolean의 값을 역전시킨다. true를 false로 , false를 true로 만든다. 아래의 결과는 4다. not을 사용하는 것이 편리할 때가 있다. ```php <?php if(!true and !true) { echo 1; } if(!true and !false) { echo 2; } if(!false and !true) { echo 3; } if(!false and !false) { echo 4; } ?> ───────────── 출력 ──────────────── 4 ``` <br> ##### boolean의 대체제 ###### 0 1 조건문에 사용되는 데이터형이 꼭 불린만 되는것은 아니다. 관습적인 이유로 0은 false, 0이 아닌 숫자는 true를 대체할 수 있다. ```php <?php if(1 and 1) { echo 1; } if(1 and 0) { echo 2; } if(0 and 1) { echo 3; } if(0 and 0) { echo 4; } ?> ``` `숫자0 외에 값이 없는 배열, 빈문자열, NULL, 문자0 등도 0으로 간주한다.`<file_sep>/게시판만들기/struts1 게시판 만들기/WEB-INF/classes/my/bbs2/controller/action/BbsAction.java package my.bbs2.controller.action; import javax.servlet.http.*; import org.apache.struts.action.*; import org.apache.struts.actions.*; import my.bbs2.*; import my.bbs2.controller.form.BbsEditForm; import org.apache.commons.beanutils.*; import java.util.*; public class BbsAction extends DispatchAction{ /** 1. 글쓰기 양식 불러오기. */ public ActionForward write(ActionMapping map, ActionForm form,HttpServletRequest req, HttpServletResponse res)throws Exception{ System.out.println("method : "+req.getParameter("method")); ActionForward af = map.findForward("fw-bbs-write"); return af; } /** DispatchAction으로는 구현할 수 없다. DispatchAction은 GET방식 파일 업로드는 POST방식 따라서 별도의 Action으로 제어 ---> BbsWriteOkAction */ public ActionForward writeOk(ActionMapping map, ActionForm form,HttpServletRequest req, HttpServletResponse res) throws Exception{ return null; } /** 2. 글쓰기 목록 가져오기. */ public ActionForward list(ActionMapping map, ActionForm form,HttpServletRequest req, HttpServletResponse res) throws Exception{ System.out.println("method : "+req.getParameter("method")); //현재 페이지 cp값 String cpStr = req.getParameter("cp"); if(cpStr == null){ cpStr = "1"; } cpStr = cpStr.trim(); HttpSession session = req.getSession(); String psStr = req.getParameter("ps"); if(psStr == null){ psStr = (String)session.getAttribute("ps"); if(psStr == null){ psStr = "5"; } } psStr = psStr.trim(); session.setAttribute("ps", psStr); int cpage = Integer.parseInt(cpStr); int pageSize = Integer.parseInt(psStr); BbsManager mgr = BbsManager.getInstance(); java.util.ArrayList<BbsDTO> arr = mgr.listAll(cpage, pageSize); int totalGulCount = mgr.getTotalGulCount(); req.setAttribute("bbslist", arr); req.setAttribute("tgc", new Integer(totalGulCount)); req.setAttribute("cp", cpStr); req.setAttribute("ps", psStr); return map.findForward("fw-bbs-list"); } /** 3. 글내용 가져오기.. */ public ActionForward content(ActionMapping map, ActionForm form,HttpServletRequest req, HttpServletResponse res)throws Exception{ String method = req.getParameter("method"); System.out.println("method : "+method); String idxStr = req.getParameter("idx"); String cpStr = req.getParameter("cp"); HttpSession session = req.getSession(); if(cpStr == null){ cpStr = (String)session.getAttribute("cp"); if(cpStr ==null){ ActionForward af = new ActionForward("/bbs-list.do?method=list",true); return af; } } cpStr = cpStr.trim(); session.setAttribute("cp", cpStr); if(idxStr == null){ idxStr = (String)session.getAttribute("idx"); if(idxStr==null){ return new ActionForward("/bbs-list.do?method=list",true); } } idxStr = idxStr.trim(); session.setAttribute("idx",idxStr); BbsManager mgr = BbsManager.getInstance(); BbsDTO dto = mgr.viewContent(idxStr); mgr.getReadnum(idxStr); ArrayList<ReplyDTO> reply = mgr.replyList(idxStr); if(dto == null || reply == null){ System.out.println("[content]:dto 또는 reply 가 널"); }else { req.setAttribute("gul",dto); req.setAttribute("reply", reply); } return map.findForward("fw-bbs-content"); } /** 3. 글내용 가져오기.. */ public ActionForward contentDown(ActionMapping map, ActionForm form,HttpServletRequest req, HttpServletResponse res)throws Exception{ String method = req.getParameter("method"); System.out.println("method : "+method); String idxStr = req.getParameter("idx"); String cpStr = req.getParameter("cp"); HttpSession session = req.getSession(); if(cpStr == null){ cpStr = (String)session.getAttribute("cp"); if(cpStr ==null){ ActionForward af = new ActionForward("/bbs-list.do?method=list",true); return af; } } cpStr = cpStr.trim(); session.setAttribute("cp", cpStr); if(idxStr == null){ idxStr = (String)session.getAttribute("idx"); if(idxStr==null){ return new ActionForward("/bbs-list.do?method=content",true); } } idxStr = idxStr.trim(); session.setAttribute("idx",idxStr); BbsManager mgr = BbsManager.getInstance(); BbsDTO dto = mgr.viewContent(idxStr); ArrayList<ReplyDTO> reply = mgr.replyList(idxStr); if(dto == null || reply == null){ System.out.println("[content]:dto 또는 reply 가 널"); }else { req.setAttribute("downs",dto); req.setAttribute("reply", reply); } return map.findForward("fw-bbs-content-down"); } /** 3_2. 꼬리글 달기.. */ public ActionForward replyOk(ActionMapping map, ActionForm form,HttpServletRequest req, HttpServletResponse res)throws Exception{ String method = req.getParameter("method"); System.out.println("method : "+method); String writer = req.getParameter("reply_writer"); String content = req.getParameter("reply_content"); String pwd = req.getParameter("reply_pwd"); if(writer!=null)writer = writer.trim(); if(content!=null)content = content.trim(); if(pwd!=null)pwd = pwd.trim(); HttpSession ses = req.getSession(); String idxStr = (String)ses.getAttribute("idx"); if(idxStr == null){ String path = "bbs-list.do?method=list"; return new ActionForward(path,true); } idxStr = idxStr.trim(); BbsManager mgr = BbsManager.getInstance(); int result = mgr.replySave(idxStr, writer, content, pwd); String path = "/bbs-content.do?method=content"; return new ActionForward(path,true); } /** 3_2. 꼬리글 삭제.. */ public ActionForward replyDelOk(ActionMapping map, ActionForm form,HttpServletRequest req, HttpServletResponse res)throws Exception{ System.out.println("method : "+req.getParameter("method")); String no = req.getParameter("no"); String pwd = req.getParameter("delPwd"); BbsManager mgr= BbsManager.getInstance(); int result = mgr.replyDelPwd(no, pwd); String msg="",url=""; if(result >0){ msg = "꼬리글 삭제 성공"; url = "bbs-content.do?method=content"; }else{ msg = "꼬리글 삭제 실패"; url = "javascript:history.go(-1)"; } req.setAttribute("bbs-msg", msg); req.setAttribute("bbs-url", url); return map.findForward("gb-bbs-msg"); } /** 4. 본 문장 삭제.. * bbs-delete.do--->ForwardAction--->bbs_delete.jsp * bbs-deleteOk.do--->BbsAction(deleteOk()) * ---> gb-bbs-msg로 forward * */ public ActionForward deleteOk(ActionMapping map, ActionForm form,HttpServletRequest req, HttpServletResponse res)throws Exception{ System.out.println("method : "+req.getParameter("method")); String idxStr = (String)req.getAttribute("idx"); HttpSession ses = req.getSession(); if(idxStr == null){ idxStr = (String)ses.getAttribute("idx"); if(idxStr==null){ String path ="bbs-list.do?method=list"; return new ActionForward(path, true); } } idxStr = idxStr.trim(); String pwd = req.getParameter("pwd"); BbsManager mgr = BbsManager.getInstance(); int result = mgr.deleteOk(idxStr, pwd); String msg="", url=""; if(result>0){ msg="삭제 성공"; url="bbs-list.do?method=list"; }else{ msg="글 삭제 실패"; url="javascript:history.go(-1)"; } req.setAttribute("bbs-msg", msg); req.setAttribute("bbs-url", url); return map.findForward("gb-bbs-msg"); } /** 5. 답변글 달기 * */ public ActionForward rewrite(ActionMapping map, ActionForm form,HttpServletRequest req, HttpServletResponse res)throws Exception{ System.out.println("method : "+req.getParameter("method")); HttpSession ses = req.getSession(); String idxStr = (String)ses.getAttribute("idx"); if(idxStr==null){ String path = "bbs-list.do?method=list"; return new ActionForward(path,true); }else{ return map.findForward("fw-bbs-rewrite"); } } /** * 5. 답글 달기 성공 * */ public ActionForward rewriteOk(ActionMapping map, ActionForm form,HttpServletRequest req, HttpServletResponse res)throws Exception{ System.out.println("method : "+req.getParameter("method")); return null; } /** * 6 글 내용 수정 * */ public ActionForward edit(ActionMapping map, ActionForm form,HttpServletRequest req, HttpServletResponse res)throws Exception{ String method = req.getParameter("method"); System.out.println("method : "+method); HttpSession ses = req.getSession(); String idxStr = (String)ses.getAttribute("idx"); if(idxStr == null){ String path = "/bbs-list.do?method=list"; return new ActionForward(path,true); } BbsManager mgr = BbsManager.getInstance(); BbsDTO dto = mgr.edit(idxStr); req.setAttribute("gul", dto); return map.findForward("fw-bbs-edit"); } /** 6_1 글 내용 수정 완료 - editOk * */ public ActionForward editOk(ActionMapping map, ActionForm form,HttpServletRequest req, HttpServletResponse res)throws Exception{ String method = req.getParameter("method"); System.out.println("method: "+method); BbsEditForm bf = (BbsEditForm)form; BbsManager mgr = BbsManager.getInstance(); int result = mgr.editOk(bf); String msg="", url=""; if(result > 0){ msg = "수정 성공"; url = "bbs-content.do?method=content"; }else{ msg = "수정 실패"; url = "javscript:history.go(-1)"; } req.setAttribute("bbs-msg", msg); req.setAttribute("bbs-url", url); return map.findForward("gb-bbs-msg"); } } <file_sep>/guide/server/Zeus&Webtob/jeus&webtob 연동.MD # JUSE&WEBTOB 연동 ---------------- ##### 1.개요 제우스6.0 웹투비4.1 윈도우설치 기준으로 작성하였습니다. 참고 URL : [egloos.zum.com/windydh/v/4618738](http://egloos.zum.com/windydh/v/4618738) --------------- ##### 2. http.m ```css *DOMAIN webtob1 *NODE HKKIM-PC WEBTOBDIR="C:/TmaxSoft/JEUS6.0/webserver", SHMKEY = 54000, DOCROOT="C:/TmaxSoft/WebtoB4.1/docs", PORT = "8080", HTH = 1, NODENAME = "$(NODENAME)", ERRORDOCUMENT = "503", #Options="IgnoreExpect100Continue", LOGGING = "log1", ERRORLOG = "log2", SYSLOG = "syslog", JSVPORT = 9900 *SVRGROUP htmlg NODENAME = "HKKIM-PC", SVRTYPE = HTML cgig NODENAME = "HKKIM-PC", SVRTYPE = CGI ssig NODENAME = "HKKIM-PC", SVRTYPE = SSI jsvg NODENAME = "HKKIM-PC", SVRTYPE = JSV *SERVER html SVGNAME = htmlg, MinProc = 2, MaxProc = 10, ASQCount = 1 cgi SVGNAME = cgig, MinProc = 2, MaxProc = 10, ASQCount = 1 ssi SVGNAME = ssig, MinProc = 2, MaxProc = 10, ASQCount = 1 MyGroup SVGNAME = jsvg, MinProc = 2, MaxProc = 10 *URI uri1 Uri = "/cgi-bin/", Svrtype = CGI uri2 Uri = "/examples/", SvrType=JSV, SvrName=MyGroup *ALIAS alias1 URI = "/cgi-bin/", RealPath = "C:/TmaxSoft/WebtoB4.1/cgi-bin/" *LOGGING syslog Format = "SYSLOG", FileName = "C:/TmaxSoft/WebtoB4.1/log/system.log_%M%%D%%Y%", Option = "sync" log1 Format = "DEFAULT", FileName = "C:/TmaxSoft/WebtoB4.1/log/access.log_%M%%D%%Y%", Option = "sync" log2 Format = "ERROR", FileName = "C:/TmaxSoft/WebtoB4.1/log/error.log_%M%%D%%Y%", Option = "sync" *ERRORDOCUMENT 503 status = 503, url = "/503.html" *EXT htm MimeType = "text/html", SvrType = HTML jsp Mimetype ="application/jsp", Svrtype=JSV, SvrName=MyGroup ``` ###### *NODE영역의 WEBTOBDIR 와 DOCROOT 경로를 was, web에 맞게 설정해줍니다. ---------------- ##### 3.실행 jeus, webtob 서버를 각각 실행시킨 후에 연동되는지 확인해 봅니다. ---------------- <file_sep>/게시판만들기/struts1 게시판 만들기/WEB-INF/classes/guide/resources/application.properties error.invalidIdName = Error1{0} error.invalidPwd = Error2 {0}<file_sep>/php/02. 비교.md ## 비교 << 목록 >> 1 . 연산자 2 . 비교연산자 --------------- ##### 연산자 * 연산자란 값에 대해서 어떤 작업을 컴퓨터에게 지시하기 위한 기호이다. ```php <?php $a = 1; ?> ``` 위의 예제에서 = 은 우항의 값인 1을 좌항의 변수 a 에 대입하는 "대입연산자"이다. --------------- ##### 비교연산자 * 프로그래밍에서 비교란 주어진 값들이 큰지, 작은지, 같은지, 다른지를 구분하는 것을 말한다. 이때 비교연산자를 사용하는데 비교 연산자의 결과는 true, false 중에 하나다. true는 비교 결과가 참이라는 얘기고, false는 비교 결과가 거짓이라는 뜻이다. * ` == ` * 좌항과 우항을 비교해서 서로 `값`이 같다면 true, 다르면 false가된다. ```php <?php echo "1==2 : "; var_dump(1==2); echo "<br />"; echo "1==1 : "; var_dump(1==1); echo "<br />"; echo "'one'=='two' : "; var_dump('one'=='two'); echo "<br />"; echo "'one'=='one' : "; var_dump('one'=='one'); echo "<br />"; ?> ───────────── 출력 ──────────────── 1==2 : bool(false) 1==1 : bool(true) 'one'=='two' : bool(false) 'one'=='one' : bool(true) ``` * `!=` * `!`는 부정을 의미한다. '같다'의 부정은 '같지 않다'이다. 이것을 기호로는 `!=`로 표시한다. ```php <?php echo "1!=2 : "; var_dump(1!=2); echo "<br />"; echo "1!=1 : "; var_dump(1!=1); echo "<br />"; echo "'one'!='two' : "; var_dump('one'!='two'); echo "<br />"; echo "'one'!='one' : "; var_dump('one'!='one'); echo "<br />"; ?> ───────────── 출력 ──────────────── 1!=2 : bool(true) 1!=1 : bool(false) 'one'!='two' : bool(true) 'one'!='one' : bool(false) ``` * ` > ` * `>`는 좌항이 우항보다 크다면 참, 그렇지 않다면 거짓임을 알려주는 연산자다. * `<`는 우항이 좌항보다 크다면 참, 그렇지 않다면 거짓임을 알려주는 연산자다. ```PHP <?php echo "10>20 : "; var_dump(10>20); echo "<br />"; echo "10>2 : "; var_dump(10>2); echo "<br />"; echo "10>10 : "; var_dump(10>20); echo "<br />"; ?> ───────────── 출력 ──────────────── 10>20 : bool(false) 10>2 : bool(true) 10>10 : bool(false) ``` * ` >= ` * `>=`는 "좌항이 우항보다 크거나 같다"의 의미. * `<=`는 "우항이 좌항보다 크거나 같다"의 의미. ```PHP <?php echo "10>=20 : "; var_dump(10>=20); echo "<br />"; echo "10>=2 : "; var_dump(10>=2); echo "<br />"; echo "10>=10 : "; var_dump(10>=20); echo "<br />"; ?> ───────────── 출력 ──────────────── 10>=20 : bool(false) 10>=2 : bool(true) 10>=10 : bool(false) ``` * ` === ` * `===` 는 "좌항과 우항이 정확하게 같다"의 의미. * ` == ` 와의 차이점은 `==`이 형변환의 결과를 비교하지만, ` === ` 는 양쪽항이 데이터 형식까지 정확하게 동일해야 같은 것으로 인정한다는 점이다. * `<=`는 "우항이 좌항보다 크거나 같다"의 의미이다 ```PHP <?php echo "10>=20 : "; var_dump(10>=20); echo "<br />"; echo "10>=2 : "; var_dump(10>=2); echo "<br />"; echo "10>=10 : "; var_dump(10>=20); echo "<br />"; ?> ───────────── 출력 ──────────────── 10>=20 : bool(false) 10>=2 : bool(true) 10>=10 : bool(false) ``` <file_sep>/java/toby_spring/Vol.2/1장/README.md ## 1장 IoC 컨테이너와 DI ### 1.1 IoC 컨테이너 : 빈 팩토리와 애플리케이션 컨텍스트 스프링 애플리케이션에서는 오브젝트의 생성과 관계설정, 사용, 제거 등의 작업을 애플리케이션 코드 대신 독립된 컨테이너가 담당한다. 이를 컨테이너가 코드 대신 오브젝트에 대한 제어권을 갖고 있다고 해서 IoC라고 부른다. 그래서 스프링 컨테이너를 IoC컨테이너라고도 한다. 스프링에선 IoC를 담당하는 컨테이너를 `빈 팩토리` 또는 `애플리케이션 컨텍스트`라고 부르기도 한다. 1. 빈 팩토리 : 주로 오브젝트의 생성과 오브젝트 사이의 런타임 관계를 설정하는 DI관점으로 볼때 사용된다. 2. 애플리케이션 컨텍스트 : DI를 위한 빈 팩토리에 엔터프라이즈 개발을 위해 필요한 여러가지 컨테이너 기능을 추가한 조금더 확장된 의미로 사용된다. > 스프링의 IoC 컨테이너는 일반적으로 애플리케이션 컨텍스트를 말한다. - 스프링의 빈 팩토리와 애플리케이션 컨텍스트는 각각 기능을 대표하는 `BeanFactory`와 `Applicationcontext`라는 두 개의 인터페이스로 정의되어 있다. - Applicationcontext 인터페이스는 BeanFactory 인터페이스를 상속한 서브인터페이스다. - 스프링 애플리케이션은 최소한 하나 이상의 IoC컨테이너, 즉 애플리케이션 컨텍스트 오브젝트를 갖고 있다. #### 1.1.1 IoC 컨테이너를 이용해 애플리케이션 만들기 가장 간단하게 IoC 컨테이너를 만드는 방법은 다음과 같이 ApplicationContext 구현 클래스의 인스턴스를 만드는 것이다. ```java StaticApplicationContext ac = new StaticApplicationContext(); ``` 이렇게 만들어진 컨테이너가 본격적인 IoC 컨테이너로서 동작하려면 두 가지가 필요하다. - `POJO 클래스` - 설정 메타정보. ##### POJO 클래스 먼저 애플리케이션의 핵심코드를 담고 있는 POJO 클래스를 준비해야 한다. 각각의 POJO는 특정 기술과 스펙에서 독립적일뿐더러 의존관계에 있는 다른 POJO와 느슨한 결합을 갖도록 만들어야 한다. 간단히 두 개의 POJO클래스를 만들어보자. - 지정된 사람에게 인사를 할 수 있는 Hello라는 클래스 - 메시지를 받아서 이를 출력하는 Printer 인터페이스를 구현한 StringPrinter 클래스 이 두개의 POJO 클래스는 Printer라는 인터페이스를 사이에 두고 느슨하게 연결되어 있다. 구체적으로 서로의 이름과 존재를 알 필요도 없다. 단지 서로 관계를 맺고 사용될 때 필요한 최소한의 인터페이스 정보만 공유하면된다. 그 역할을 `Printer 인터페이스`가 담당한다. Hello는 Printer 인터페이스를 사용하고, StringPrinter 는 Printer 인터페이스를 구현하도록 만든다. Hello는 Printer라는 인터페이스를 구현한 클래스의 오브젝트라면 어떤 것이든 사용 가능하다. Printer 구현 클래스를 변경하더라도 Hello 코드의 수정은 필요 없다. 단지 런타임 시에 오브젝트를 연결해주는 IoC 컨테이너의 도움만 있으면 된다. > POJO 코드를 설계할 때는 일단 유연한 변경 가능성을 고려해서 만든다. > 물론 여기서는 hHello 와 StringPrinter를 사용하기로 작정했다. > 하지만 클래스 모델링 때나 클래스 코드를 작성할 대는 이런 의도는 아직 드러나지 않는다. > 단지 유연한 확장성을 고려하고 자신의 기능에 충실한 POJO를 작성한다. 이렇게 만들어진 POJO 코드를 살펴보자 > 인사기능을 가진 Hello 클래스 ```java public class Hello { String name; Printer printer; public String sayHello(){ //프로퍼티로 DI받은 이름을 이용해 간단한 인사문구 만들기 return "Hello " + name; } public void print(){ this.printer.print(sayHello()); } public void setName(String name){ this.name=name; } public void setPrinter(Printer printer){ this.printer=printer; } } ``` 위의 Hello 클래스는 코드로만 보자면 Printer라는 인터페이스에만 의존한다. 실제로 런타임 시에 어떤 구체적인 클래스의 오브젝트를 사용하게 될지는 알지도 못하고, 사실 관심도 없다. > 간단히 메시지를 받아서 출력하는 기능을 정의한 Printer 인터페이스 ```java public interface Printer{ void print(String message); } ``` 이 `Printer` 인터페이스를 구현한 클래스는 얼마든지 만들 수 있다. > `StringBuffer`에 메시지를 넣는 방식으로 메시지를 출력하는 StringPrinter 클래스 ```java public class StringBuffer implements Printer { private StringBuffer buffer = new StringBuffer(); public void print(String message) { this.buffer.append(message); } public String toString(){ return this.buffer.toString(); } } ``` > 메시지를 받아서 표준출력 스트림으로 출력하는 ( 콘솔화면에 출력하는) ConsolePrinter 클래스 ```java public class ConsolePrinter implements Printer { public void print(String message) { System.out.println(message); } } ``` 이렇게 각자 기능에 충실하게 독립적으로 설계된 POJO 클래스를 만들고, 결합도가 낮은 유연한 관계를 가질 수 있도록 인터페이스를 이용해 연결해주는 것 까지가 IoC컨테이너가 사용할 POJO를 준비하는 첫 단계다. ##### 설정 메타정보 두 번째 필요한 것은 앞으로 만든 POJO 클래스들 중에 애플리케이션에서 사용할 것을 선정하고 이를 IoC컨테이너가 제어할 수 있도록 적절한 메타정보를 만들어 제공하는 작업이다. `IoC 컨테이너`의 가장 기초적인 역할은 오브젝트를 생성하고 이를 관리하는 것이다. 스프링 컨테이너가 관리하는 이런 오브젝트는 `빈~bean~`이라고 부른다. `IoC 컨테이너`가 필요로 하는 설정 메타 정보는 바로 이 빈을 어떻게 만들고 어떻게 동작하게 할 것인가에 관한 정보다. 스프링의 설정 메타정보는 XML 파일이 아니다. 스프링에 대한 대표적인 오해 중의 하나는 스프링의 설정정보는 XML로 되어 있다는 것이다. 스프링이 XML에 담긴 내용을 읽어서 설정 메타정보로 활용하는 건 사실이지만, 그렇다고 해서 스프링이 XML로 된 설정 메타정보를 가졌다는 말은 틀렸다. 스프링의 설정 메타정보는 `BeanDefinition 인터페이스`로 표현되는 순수한 추상 정보다. 스프링 IoC 컨테이너, 즉 애플리케이션 컨텍스트는 바로 이 `BeanDifinition`으로 만들어진 메타정보를 담은 오브젝트를 사용해 IoC와 DI작업을 수행한다. - xml - 소스코드 어노테이션 - 자바코드 - 프로퍼티 파일 이든 파일포맷이나 형식에 제한되지 않고 `BeanDifinition`으로 정의되는 스프링의 설정 메타정보의 내용을 표현한 것이 있다면 무엇이든 사용 가능하다. `BeanDifinition` 인터페이스로 정의되는, IoC 컨테이너가 사용하는 빈 메타정보는 대략 다음과 같다. - 빈 아이디, 이름, 별칭 : 빈 오브젝트를 구분할 수 있는 식별자 - 클래스 또는 클래스 이름 : 빈으로 만들 POJO 클래스 또는 서비스 클래스 정보 - 스코프 : 싱글톤, 프로토타입과 같은 빈의 생성 방식과 존재 범위 - 프로퍼티 값 또는 참조 : DI에 사용할 프로퍼티 이름과 값 또는 참조하는 빈의 이름 - 생성자 파라미터 값 또는 참조 : DI에 사용할 생성자 파라미터 이름과 값 또는 참조할 빈의 이름 - 지연된 로딩 여부, 우선 빈 여부, 자동와이어링 여부, 부모 빈 정보, 빈팩토리 이름등 > 결국 스프링 애플리케이션이란 POJO 클래스와 설정 메타 정보를 이용해 IoC컨테이너가 만들어주는 오브젝트의 조합이라고 할 수 있다. 일반적으로 설정 메타정보는 XML 파일이나 어노테이션 같은 외부 리소스를 전용 리더기가 읽어서 BeanDifinition 타입의 오브젝트로 만들어 사용한다. 하기 코드는 Hello 클래스를 IoC컨테이너에 빈으로 등록하는 학습 테스트 코드다. 빈 메타정보의 항목들은 대부분 디폴트 값이 있다. 싱글톤으로 관리되는 빈 오브젝트를 등록할 때 반드시 제공해줘야 하는 정보는 빈 이름과 POJO 클래스 뿐이다. ```java // IoC 컨테이너 생성, 생성과 동시에 컨테이너로 동작한다. StaticApplicationContext ac = new StaticApplicationContext(); // Hello 클래스를 hello1이라는 이름의 싱글톤 빈으로 컨테이너에 등록한다. ac.registerSingleton("hello1",Hello.class); // IoC 컨테이너가 등록한 빈을 생성했는지 확인하기 위해 빈을 용청하고 Null인지 아닌지 확인한다. Hello hello1 = ac.getBean("hello1", Hello.class); assertThat(hello1, is(notNullValue())); ``` 위에서 사용한 `StaticApplicationContext` 는 코드에 의해 설정 메타정보를 등록하는 기능을 제공하는 애플리케이션 컨텍스트로 테스트용으로 사용하기에 적당하다. 여기서 주의할 점은 IoC컨테이너가 관리하는 빈은 오브젝트 단위지 클래스 단위가 아니라는 점이다. 또한, 보통은 클래스당 하나의 오브젝트를 만들지만, 경우에 따라서 하나의 클래스를 여러 개의 빈으로 등록하기도 하는데 이는 빈마다 다른 설정을 지정해두고 사용하기 위해서다. 예를 들어 사용할 DB가 여러 개라면 같은 SimpleDriverDataSource 클래스로 된 빈을 여러 개 등록하고 각각 다른 DB설정을 지정해서 사용할 경우다. 위 코드는 `StaticApplicationContext` 가 디폴트 메타정보를 사용해서 싱글톤 빈을 등록해주는 registerSingleton()메소드를 사용했는데 이번에는 직접 `BeanDifinition` 타입의 설정 메타정보를 만들어서 IoC 컨테이너에 등록하는 방법을 사용해보자. `RootBeanDifinition`은 가장 기본적인 `BeanDifinition` 인터페이스의 구현 클래스다. 다으과 같이 `RootBeanDifinition` 오브젝트를 만들어서 빈에 대한 설정정보를 넣어주고 IoC컨테이너에 등록할 수 있다. ```java // 빈 메타정보를 담은 오브젝트를 만든다. // 빈 클래스를 Hello로 지정한다. // <bean class="springbook.learning....Hello" /> 에 해당하는 메타정보다 BeanDefinition helloDef = new RootBeanDefinition(Hello.class); // 빈의 name 프로퍼티에 들어갈 값을 지정한다. // <property name="name" value="Spring" /> 에 해당한다. helloDef.getPropertyValues().addPropertyValue("name", "String"); // 앞에서 생성한 메타정보를 hello2라는 이름을 가진 빈으로 해서 등록한다. // <bean id="hello2" ... /> 에 해당한다. ac.registerBeanDefinition("hello2", helloDef); ``` IoC 컨테이너는 빈 설정 메타정보를 담은 BeanDefinition 을 이용해 오브젝트를 생성하고 DI 작업을 진행한 뒤에 빈으로 사용할 수 있도록 등록해준다. 이때 BeanDefinition의 클래스, 프로퍼티, 빈 아이디 등의 정보가 활용된다. 하기 코드는 `hello2` 빈을 컨테이너에서 가져와서 이를 검증하는 코드다. 빈은 오브젝트 단위로 등록되고 만들어지기 때문에 같은 클래스 타입이더라도 두 개를 등록하면 서로 다른 빈 오브젝트가 생성되는 것도 확인할 수 있다. ```java // BeanDifinition 으로 등록된 빈이 컨테이너에 의해 만들어지고 프로퍼티 설정이 됐는지 확인한다. Hello hello2 = ac.getBean("hello2", Hello.class); assertThat(hello2.sayHello(), is("Hello Spring")); // 처음 등록한 빈과 두번째 등록한 빈이 모두 동일한 Hello 클래스지만 별개의 오브젝트로 생성됐다. assertThat(hello1, is(not(hello2))); assertThat(ac.getBeanFactory().getBeanDefinitionCount(), is(2)); ``` 위 코드 마지막 줄에서 볼 수 있듯이, IoC 컨테이너에서 등록된 빈 설정 메타정보를 가져올수도 있다. 빈에 DI 되는 프로퍼티는 스트링이나 숫자 등의 값과 다른 빈 오브젝트를 가리키는 레퍼런스로 구분할 수 있다. 레퍼런스로 지정된 프로퍼티는 다른 빈 오브젝트를 주입해서 오브젝트 사이의 관계를 만들어내느 데 사용된다. Hello 클래스와 StringPrinter 클래스는 Printer라는 인터페이스를 사이에 두고 아주 느슨하고 간접적인 관계를 맺고 있을 뿐이다. Hello 오브젝트와 StringPrinter 오브젝트 사이의 관계는 설정 메타정보를 참고해서 런타임 시에 IoC 컨테이너가 주입해준다. > 설정 메타정보 책 55~59p 참고 #### IoC 컨테이너의 종류와 사용 방법 ApplicationContext 인터페이스를 바르게 구현했다면 어떤 클래스든 스프링의 IoC컨테이너로 사용할 수 있다. 물론 스프링을 사용하는 개발자가 직접 이 인터페이스를 구현할 일은 없다. 왜냐하면 이미 스프링에는 다양한 용도로 쓸 수 있는 십여 개의 ApplicationContext 구현 클래스가 존재한다. 또한 스프링 애플리케이션에서 직접 코드를 통해 ApplicationContext 오브젝트를 생성하는 경우는 거의 없다. 대부분 간단한 설정으로 통해 자동으로 만들어지는 방법을 사용하기 때문이다. > 스프링이 제공하는 ApplicationContext 구현 클래스에는 어떤 종류가 있고 어떻게 사용되는지 좀 더 살펴보자 ##### StaticApplicationContext - 코드를 통해 빈 메타정보를 등록하기 위해 사용 - 사실상 스프링의 기능에 대한 학습 테스트를 만들경우가 아니라면 실제로 사용되지 않는다. ##### GenericApplicationContext - 가장 일반적인 애플리케이션 컨텍스트 구현클래스다. - 실전에서 사용될 수 있는 모든 기능을 갖추고 있는 애플리케이션 컨텍스트다. - 컨테이너의 주요 기능을 DI를 통해 확장할 수 있도록 설계되어 있다. - XML 파일과 같은 외부의 리소스에 있는 빈 설정 메타정보를 리더를 통해 읽어들여서 메타정보로 전환해서 사용한다. 특정 포캣의 빈 설정 메타정보를 읽어서 이를 애플리케이션 컨텍스트가 사용할 수 있는 BeanDefinition 정보로 변환하는 기능을 가진 오브젝트는 BeanDefinitionReader 인터페이스를 구현해서 만들고, 빈 설정정보 리더라고 불린다. XMl로 작성된 빈 설정정보를 읽어서 컨테이너에게 전달하는 대표적인 빈 설정정보 리더는 `XmlBeanDefinitionReader`다. 이 리더를 `GenericpplicationContext`가 이용하도록 해서 hello빈과 printer 빈을 등록하고 사용하게 만들어보자 > XML로 만든 빈 설정 메타정보 ```java <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="hello" class="springbook.learningtest.spring.Hello" > <property name="name" value="Spring" /> <property name="printer" value="printer" /> </bean> <bean id="printer" class="springbook.learningtest.spring.StringPrinter" /> </beans> ``` 빈 메타정보의 내용은 앞에서 코드로 만들었던 것과 동일하다. 단지 `<bean>`태그를 사용해 XML문서로 표현했을 뿐인다. XML로 만든 빈 설정 메타정보를 사용하는 `GenericApplicationContext`에 대한 테스트를 다으과 같이 작성한다. > `GenericApplicationContext` 의 사용 방법에 대한 학습 테스트 ```java @Test public void genericApplicationContext() { GenericApplicationContext ac = new GenericApplicationContext(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(ac); reader.loadBeanDefinitions("springbook/learningtest/spring/ioc/genericApplicationContext.xml"); ac.refresh(); Hello hello = ac.getBean("hello", Hello.class); hello.print(); assertThat(ac.getBean("printer").toString(), is("Hello Spring")); } ``` `XmlBeanDefinitionReader`는 스프링의 리소스 로더를 이용해 XML 내용을 읽어온다. 따라서 다양한 리소스 타입의 XML문서를 사용할 수 있다. 리소스 대신 스트링을 넘기면 기본적으로 클래스패스 리소스로 인식한다. 또한 프로퍼티 파일에서 빈설정 메타정보를 가져오는 `PropertiesBenDifinitionReader`도 제공한다. 대표적으로 `XML파일`, `자바 소스코드 애노테이션`, `자바클래스` 세 가지 방식으로 빈 설정 메타정보를 작성할 수 있다. 물론 이 세가지로 제한되진 않는다. 필요하다면 얼마든지 유연하게 확장할 수 있고, 이를 보면 스프링이 지지하는 객체지향적인 설계의 핵심 가치를 스프링 컨테이너에도 충실하게 적용하고 있음을 알 수 있다. ##### GenericXmlApplicationContext - 코드에서 `GenericApplicationContext`를 사용하는 경우에는 번거롭게 `XmlBeanDefinitionReader`를 직접 만들지 말고, 이 두 개의 클래스가 결합된 `GenericXmlApplicationReader` 를 사용하면 편리하다. - 이걸 사용하면 XML 파일을 읽어들이고 refresh()를 통해 초기화하는 것까지 한 줄로 끝낼 수 있다. - XML 파일로 설정을 만들고 애플리케이션 컨텍스트에서 XML을 읽어서 사용하는 코드를 시험 삼아 만들어볼 필요가 있다면 사용하기에 적당하다. ##### WebApplictionContext - 스프링 애플리케이션에서 가장 많이 사용되는 애플리케이션 컨텍스트다 - `ApplicationContext`를 확장한 인터페이스다 - 이름 그대로 웹 환경에서 사용할 때 필요한 기능이 추가된 애플리케이션 컨텍스트다. - 스프링 애플리케이션은 대부분 서블릿 기반의 독립 웹 애플리케이션(WAR)으로 만들어지기 때문이다. > - 가장 많이 사용되는 건, XML 설정파일을 사용하도록 만들어진 `XmlWebApplicationContext`다. 물론 XML 외의 설정정보 리소스도 사용할 수 있다. - 애노테이션을 이용한 설정 리소스만 사용한다면 `AnnotationConfigWebApplicationContext`를 쓰면 된다. 디폴트는 `XmlWebApplicationContext` > WebApplicationContext의 사용 방법을 이해하려면 스프링의IoC 컨테이너를 적용했을 때 애플리케이션을 기동시키는 방법에 대해 살펴볼 필요가 있다. 1. 스프링 IoC컨테이너는 빈 설정 메타정보를 이용해 빈 오브젝트를 만들고 DI 작업을 수행한다. 2. 하지만 그것만으로는 애플리케이션이 동작하지 않는다. 마치 자바 애플리케이션의 `main()`메소드처럼 어디에선가 특정 빈 오브젝트의 메소드를 호출함으로써 애플리케이션을 동작 시켜야 한다. 보통 이런 기동 역할을 맡은 빈을 사용하려면 IoC컨테이너에서 요청해서 빈 오브젝트를 가져와야 한다. 그래서 간단히 스프링 애플리케이션을 만들고 IoC 컨테이너를 직접 셋업했다면 다음과 같은 코드가 반드시 등장한다. ```java ApplicationContext ac=... Hello hello = ac.getBean("hello", Hello.class); hello.print(); ``` > 적어도 한 번은 IoC 컨테이너에게 요청해서 빈 오브젝트를 가져와야 한다. > 이때는 필히 getBean()이라는 메소드를 사용해야 한다. 그러나 그 이후로는 다시 getBean()으로 빈 오브젝트를 가져올 필요가 없다. 빈오브젝트들끼리 DI로 서로 연결되어 있으ㅡ로 의존관계를 타고 필요한 오브젝트가 호출되면서 애플리케이션이 동작할 것이다. 즉 IoC 컨테이너의 역할은 이렇게 초기에 빈 오브젝트를 생성하고 DI 한 후에 최초로 애플리케이션을 기동할 빈 하나를 제공해주는 것까지다. 그런데 테스트나 독립형 애플리케이션이라면 모르겠지만, 웹 애플리케이션은 동작하는 방식이 근본적으로 다르다. 웹에서는 main()메소드를 호출할 방법이 없고, 사용자도 여럿이며 동시에 웹 애플리케이션을 사용한다. 그래서 웹 환경에서는 main()메소드 대신 서블릿 컨테이너가 브라우저로부터 오는 HTTP 요청을 받아서 해당 요청에 매핑되어 있는 서블릿을 실행해주는 방식으로 동작한다. 서블릿이 일종의 main()메소드와 같은 역할을 하는 셈이다. > 그렇다면 웹 애플리케이션에서 스프링 애플리케이션을 기동시키는 방법은 무엇일까? 일단 main()메소드 역할을 하는 서블릿을 만들어두고, 미리 애플리케이션 컨텍스트를 생성해둔 다음, 요청이 서블릿으로 들어올 때마다 getBean()으로 필요한 빈을 가져와 정해진 메소드를 실행해주면 된다. > 쉽게 main()메소드에서 했던 작업을 웹 애플리케이션과 그에 소속된 서블릿이 대신해 준다고 생각하자. 브라우저와 같은 클라이언트로부터 들어오는 `요청` -> `서블릿 컨테이너`(받아서 서블릿을 동작시켜줌) -> `서블릿` `서블릿` -> 웹 애플리케이션이 시작 될 때 미리 만들어둔 웹 애플리케이션 컨텍스트에게 빈을 요청해서 받아둔다. 그리고 미리 지정된 메소드를 호출함으로써 스프링 컨테이너가 DI 방식으로 구성해둔 애플리케이션의 기능이 시작되는 것이다. 다행히도 스프링은 이런 웹 환경에서 애플리케이션 컨텍스트를 생성하고 설정 메타 정보로 초기화해주고, 클라이언트로부터 들어오는 요청마다 적절한 빈을 찾아서 이를 실행해주는 기능을 가진 `DispatcherServlet`이라는 이름의 서블릿을 제공한다. 스프링이 제공해준 서블릿을 `web.xml`에 등록하는 것만으로 웹 환경에서 스프링 컨테이너가 만들어지고 애플리케이션을 실행하는 데 필요한 대부분의 준비는 끝이다. > 일단 `웹 애플리케이션`에서 만들어지는 `스프링 IoC 컨테이너`는 `WebApplicationContext 인터페이스`를 구현한 것임을 기억해두자 > `WebApplicationContext`의 특징은 자신이 만들어지고 동작하는 환경인 웹 모듈에 대한 정보에 접근할 수 있다는 점이다. #### IoC 컨테이너 계층구조 빈을 담아둘 IoC 컨테이너는 애플리케이션마다 하나씩이면 충분하다. 하지만 한 개 이상의 IoC 컨테이너를 만들어 두고 사용해야 할 경우가 있는데 바로 트리모양의 계층구조를 만들때다. ##### 부모 컨텍스트를 이용한 계층 구조 효과 모든 애플리케이션 컨텍스트는 부모 애플리케이션 컨텍스트를 가질 수 있다. 이를 이용하면 트리구조의 컨텍스트 계층을 만들 수 있다. - 계층구조 안의 모든 컨텍스트는 각자 독립적으로 자신이 관리하는 빈을 갖고 있긴 하지만 DI를 위해 빈을 찾을 때는 부모 애플리케이션 컨텍스트의 빈까지 모두 검색한다. - 먼저 자신이 관리하는 빈 중에서 필요한 빈을 찾아보고, 없으면 부모 컨텍스트에게 빈을 찾아달라고 요청한다. - 부모 컨텍스트에서도 원하는 빈을 찾을 수 없다면, 부모 컨텐스트의 부모 컨텍스트에게 다시 요청한다. 이렇게 계층구조를 따라서 가장 위에 존재하는 루트 컨텍스트까지 요청이 전달된다. - 이때 부모 컨텍스트에게만 빈 검색을 요청하지 자식 컨텍스트에게는 요청하지 않는다. 그런 이유로 같은 레벨에 있는 형제 컨텍스트의 빈도 찾을 수 없다. > 검색순서는 항상 자신이 먼저이고, 그런 다음 직계 부모의 순서다. 미리 만들어진 애플리케이션 컨텍스트의 설정을 그대로 가져다가 사용하면서 그중 일부 빈만 변경하고 싶다면, 애플리케이션 컨텍스트를 두개 만들어서 하위 컨텍스트에서 바꾸고 싶은 빈들을 다시 설정해줘도 된다. > 이렇게 기존 설정을 수정하지 않고 사용하지만 일부 빈 구성을 바꾸고 싶은 경우, 애플리케이션 컨텍스트의 계층구조를 만드는 방법이 편리하다. **계층 구조**를 이용하는 또 한가지 이유는 여러 애플리케이션 컨텍스트가 공유하는 설정을 만들기 위해서다. 각자 용도와 성격 달라서 웹 모듈을 여러 개로 분리하긴 했지만 핵심 로직을 담은 코드는 공유하고 싶을 때 이런 식으로 구성한다. 마찬가지로 애플리케이션 안에 성격이 다른 설정을 분리해서 두 개 이상의 컨텍스트를 구성하면서 각 컨텍스트가 공유하고 싶은 게 있을 때 **계층구조**를 이용한다. > 이런 컨텍스트 계층구조의 특성을 이해하지 못한 채로 설정을 만들고 사용하면 뜻하지 않은 에러를 만나거나 원하는 대로 동작하지 않는 문제가 발생할 수도 있으니 주의하자 ##### 컨텍스트 계층구조 테스트 컨텍스트 계층구조에 대해 간단히 학습 테스트를 만들어서 그 동작방식을 확인해보자. > 부모(루트)컨텍스트가 사용하는 설정파일`parentContext.xml` ```xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="printer" class="springbook.learningtest.spring.StringPrinter" /> <bean id="hello" class="springbook.learningtest.spring.Hello"> <property name="name" value="Parent" /> <property name="printer" ref="printer" /> </bean> </beans> ``` > 자식 컨텍스트가 사용하는 설정파일`childContext.xml` ```xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="hello" class="springbook.learningtest.spring.Hello"> <property name="name" value="Child" /> <property name="printer" ref="printer" /> </bean> </beans> ``` parentContext.xml 은 그 자체적으로 완전한 빈 설정정보를 갖고 있다. 그에 반해 childContext.xml에는 hello 빈의 printer 프로퍼티가 참조하고 있는 printer라는 이름의 빈이 존재하지 않는다. 이는 childeContext.xml은 parentContext.xml을 이용하는 컨텍스트를 부모 컨텍스트로 이용할 것을 전제로 만들어지기 때문에 아무런 문제가 없다. 즉 `자식컨텍스트`의 설정은 `부모컨텍스트`에 의존적이라고 할 수 있다. 동시에 `자식컨텍스트`를 통해 정의된 빈은 `부모컨텍스트`를 통해 정의된 같은 종류의 빈 설정을 오버라이드 한다. 따라서 childContext.xml은 parentContext.xml보다 우선한다고 할 수 있다. > 이 두개의 설정을 부모/자식 관계의 컨텍스트 계층으로 만들어보면서 컨텍스트 계층구조의 동작방식을 확인해보자 `parentContext.xml`을 사용하는 부모 컨텍스트를 다음과 같이 만들어보자 ```java ApplicationContext parent = new GenericXmlApplicationContext(basePath+"parentContext.xml"); // basePath 는 현재 클래스의 패키지 정보를 클래스패스 형식으로 만들어서 미리 저장해둔 것이다. ``` 이 부모 컨텍스틑 더이상 상위에 부모 컨텍스트가 존재하지 않는 루트 컨텍스트이므로 반드시 **스스로 완전한 빈 의존관계를 보장해야 한다.** > 다음은 `childContext.xml`을 사용하는 자식 컨텍스트를 만들어보자 ```java GenericApplicationContext child = new GenericApplicationContext(parent); ``` 앞에서 만든 `parent`를 부모 컨텍스트로 지정해줬다. 이렇게 해서 `child`라는 이름의 애플리케이션 컨텍스트는 parent 컨텍스트를 부모 컨텍스트로 갖게 된다. > 다음은 자식컨텍스트가 사용할 설정정보를 읽어들이고 초기화해보자 설정 메타정보를 읽고 `refresh()` 해주면 컨텍스트를 초기화하면서 DI를 진행한다. 이때 child 컨텍스트에서 필요한 빈이 존재하지 않을 경우 부모컨텍스트에게 빈 검색을 요청하게 된다. ```java XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(child); reader.loadBeanDefinitions(basePath+"childContext.xml"); child.refresh(); // 리더를 사용해서 설정을 읽은 경우에는 반드시 refresh()를 통해 초기화해야 한다. ``` 이제 parent와 child에 담긴 두개의 컨텍스트는 부모/자식 관계로 연결되어 있다. 이때 자식 컨텍스트인 child 에게 printer라는 이름의 빈을 요청하면 어떻게 될까? 이름이 printer인 빈은 childContext.xml안에는 존재하지 않는다. 그래서 부모인 parent 컨텍스트에서 검색을 시도한다. > 다음과 같이 확인해보자 ```java Printer printer = child.getBean("printer", Printer.class); assertThat(printer, is(notNullValue())); ``` #### 웹 애플리케이션의 IoC컨테이너 구성 ##### 웹 애플리케이션의 컨텍스트 구성방법 웹 애플리케이션의 애플리케이션 컨텍스트를 구성하는 방법으로는 다음 세 가지를 고려해볼 수 있다. 첫 번째 방법은 컨텍스트 계층구조를 만드는 것이고, 나머지 두 가지 방법은 컨텍스트를 하나만 사용하는 방법이다. 첫 번째와 세 번째 방법은 스프링 웹 기능을 사용하는 경우고, 두 번째 방법은 스프링 웹기술을 사용하지 않을때 적용가능한 방법이다. 1. `서블릿 컨텍스트`와 `루트 애플리케이션 컨텍스트` 계층구조 2. `루트 애플리케이션 컨텍스트` 단일구조 3. `서블릿 컨텍스트` 단일구조 ###### 1) 서블릿 컨텍스트와 루트 애플리케이션 컨텍스트 계층구조 - 가장 많이 사용되는 기본적인 구성 방법이다. - 스프링 웹 기술을 사용하는 경우 웹 관련 빈들은 서블릿의 컨텍스트의 두고, 나머지는 루트 애플리케이션...에 등록 - 루트 컨텍스트는 모든 서블릿 레벨 컨텍스트의 부모 컨텍스트가 된다. ###### 2) 루트 애플리케이션 컨텍스트 단일구조 - 서드파티 웹 프레임워크나 서비스 엔진만을 사용해서 프레젠테이션 계층을 만든다면 스프링 서블릿을 둘 이유가 없다. - 따라서 서블릿의 애플리케이션컨텍스트도 사용하지 않는다. - 이때는 루트애플리케이션 컨텍스트만 등록해주면 된다. ###### 3) 서블릿 컨텍스트 단일구조 - 스프링 웹 기술을 사용하면서 스프링 외의 프레임워크나 서비스 엔진에서 스프링의 빈을 이용할 생각이 아니라면 루트 애플리케이션 컨텍스트를 생략할 수도 있다. - 대신 서블릿 컨텍스트에 모든 빈을 다 등록하면 된다. - 게층구조를 사용하면서 발생할 수 있는 혼란을 근본적으로 피하고 단순한 설정을 선호한다면 이 방법을 선택할 수 있다. ##### 루트 애플리케이션 컨텍스트 등록 - 루트 웹 애플리케이션 컨텍스트를 등록하는 가장 간단한 방법은 서블릿의 `이벤트 리스너`를 이용하는 것이다. 스프링은 웹 애플리케이션의 시작과 종료 시 발생하는 이벤트를 처리하는 리스너인 `ServletContextListener` 를 이용한다. `ServletContextListener` 인터페이스를 구현한 리스너는 웹 애플리케이션 전체에 적용 가능한 DB연결 기능이나 로깅 같은 서비스를 만드는 데 유용하게 쓰인다. 웹 애플리케이션 시작 -> 루트 애플리케이션 생성 후 초기화 웹 애플리케이션 종료 -> 컨텍스트 종료 > 스프링인 위와 같은 기능을 가진 리스너인 `ContextLoaderListener`를 제공한다. > 사용법은 web.xml 파일안에 아래처럼 리스너 선언을 넣어주기만 하면 된다. ```xml <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> ``` 이 리스너가 만들어주는 컨텍스트는 어떤 종류이고 어떤 설정파일을 사용할까? 별다른 파라미터를 지정하지 않으면, 디폴트로 설정된 다음의 값이 적용된다. - 애플리케이션 컨텍스트 클래스 : XmlWebApplicationContext - XML 설정파일 위치 : /WEB-INF/applicationContext.xml 디폴트 XML설정파일 위치는 다음과 같이 파라미터를 선언해주면 된다 ```xml <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/spring/root-context.xml /WEB-INF/applicationContext.xml </param-value> </context-param> ``` ContextLoaderListener 가 자동으로 생성하는 컨텍스트의 클래스는 기본적으로 `XmlApplicationContext`다 이를 다른 구현 클래스로 변경하고 싶으면 `contextClass`파라미터를 이용해 지정해주면 된다. 단. 여기에 사용될 컨텍스트는 반드시 `WebApplictionContext` 인터페이스를 구현해야 한다. `XmlApplicationContext`외에 자주 사용하는 `AnnotationConfigApplicationContext`를 사용해 루트애플리케이션 컨텍스트를 생성하는 코드를 살펴보자 ```xml <context-param> <param-name>contextClass</param-name> <param-value> org.springframework.web.context.support.AnnotationConfigWebApplicationContext </param-value> </context-param> ``` `AnnotationConfigApplicationContext`를 컨텍스트 클래스로 사용할 때는 `contextConfigLocation`파라미터를 반드시 선언해줘야 한다. ##### 서블릿 애플리케이션 컨텍스트 등록 스프링의 웹 기능을 지원하는 프론트 컨트롤러 서블릿은 `DispatcherServlet` 이다. - web.xml 에 등록해서 사용할 수 있는 평범한 서블릿이다. - 이름을 달리해서 여러개의 디스패쳐서블릿을 등록할 수도 있다. 사용법은 아래와 같다 ```xml <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> ``` > 만약 applictionContext.xml 과 웹 계층을 위한 spring-servlet.xml을 서블릿 컨텍스트가 모두 사용하게 한다면 > 다음과 같이 한다. ( 이때 루트 컨텍스트의 등록은 생략할 수 있다. ) ```xml <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/application.xml /WEB-INF/spring-servlet.xml </param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> ``` --- ### IoC/DI를 위한 빈 설정 메타정보 작성 IoC 컨테이너의 가장 기본적인 열할은 코드를 대신해서 애플리케이션을 구성하는 오브젝트를 생성하고 관리하는 것이다. POJO로 만들어진 애플리케이션 클래스와 서비스 오브젝트들이 그 대상이다. > 그렇다면 컨테이너는 어떻게 자신이 만들 오브젝트가 무엇인지 알 수 있을까? 컨테이너는 빈 설정 메타정보를 통해 빈의 클래스와 이름을 제공받는다. 파일 혹은 어노테이션 같은 리소스로부터 읽혀서 BeanDefinition 타입의 오브젝트로 변환되고, 이 정보를 IoC 컨테이너가 활용하는 것이다. #### 빈 설정 메타정보 BeanDefinition에는 IoC 컨테이너가 빈을 만들 때 필요한 핵심 정보다 담겨있고, 몇 가지 필수항목을 제외하면 컨테이너에 미리 설정된 디폴트 값이 그대로 적용된다. 또한 여러 개의 빈을 만드는 데 재사용될 수도 있다. 설정 메타정보가 같지만 이름이 다른 여러 개의 빈 오브젝트를 만들 수 있기때문이다. 따라서 BeanDefinition에는 빈의 이름이나 아이디를 나타내는 정보는 포함되지 않는다. 대신 IoC 컨테이너에 이 BeanDefinition 정보가 등록될 때 이름을 부여해줄 수 있다. ##### 빈 설정 메타정보 항목 > p.84 표1-1 참조 #### 빈 등록 방법 빈 등록은 빈 메타정보를 작성해서 컨테이너에게 건네주면 된다. 보통 XML문서, 프로퍼티 파일, 소스코드 어노테이션과 같은 외부 리소스로 빈 메타정보를 작성하고 이를 적절한 리더나 변환기를 통해 애플리케이션 컨텍스트가 사용할 수 있는 정보로 변환해주는 방법을 사용한다. 스프링에자 자주 사용되는 빈의 등록방법은 크게 다섯가지가 있다. ###### 1) XML : `<bean>` 태그 - 가장 단순하면서도 가장 강력한 설정 방법 - 스프링 빈 메타정보의 거의 모든 항목을 지정할 수 있으므로 세밀한 제어가 가능하다. - 기본적으로 id와 class 라는 두 개의 애트리뷰트가 필요하며, id는 생략가능하다. - 다른 빈의 `<property>`태그 안에 정의할 수도 있으며, 이때는 `<bean>`의 아이디나 이름을 지정하지 않는다. 또한 이렇게 다른 빈의 설정안에 정의되는 빈을 **내부 빈** 이라고 한다. ##### 2) XML : 네임스페이스와 전용태그 `<bean>` 태그 외에도 다양한 스키마에 정의된 전용 태그를 사용해 빈을 등록하는 방법이 있다. 스프링의 빈은 크게 애플리케이션의 핵시코드를 담은 컴포넌트와 서비스 또는 컨테이너 설정을 위한 빈으로 구분 할 수 있다. 이 두가지가 모두 `<bean>` 이라는 태그로 등록되 돼서 구별이 쉽지 않은데, 이를위해 네임스페이스와 태그를 가진 설정 방법을 제공한다. > 예를 들어 aop에 사용되는 포인트컷 `<bean>`은 아래와 같이 사용가능하다. ```xml <bean id="mypointcut" class="org.spring......AspectJExpressionPoiintcut"> ... </bean> <aop:pointcut id="mypointcut" expression="execution**..*ServiceImpl.upgrade*(..))" ``` ##### 3) 자동인식을 이용한 빈등록 : 스트레오타입 어노테이션과 빈 스캐너 모든 빈을 XML에 일일히 선언하는 것이 귀찮게 느껴질 수도 있다. 특히 규모가 커지고 빈의 개수가 많아지만 당연한 일이다. 바로 이럴때 사용할수 있는 방법이다. - 빈으로 사용될 클래스에 어노테이션을 부여해주면 이런 클래스를 자동으로 찾아서 빈으로 등록해주게 할 수 있다. 이런 방식을 `빈 스캐닝(scanning)`을 통한 자동인식 빈 등록 기능이라고 하고, 이런 스캐닝 작업을 담당하는 오브젝트를 `빈 스캐너(scanner)`라고 한다. 빈 스캐너는 지정된 클래스패스 아래에 있는 모든 패키지의 클래스를 대상으로 필터를 적용해서 빈등록을 위한 클래스들을 선별해낸다. 디폴트 필터인 `@Component` 을 포함해 디폴트 필터에 적용되는 어노테이션을 `스테레오타입` 어노테이션이라고 부른다 ```java import org.springframework.stereotype.Component; @Component public clss AnnotatedHello{ ... } ``` - 위 소스의 클래스는 빈 스캐너가 감지해서 자동으로 빈으로 등록해주는 후보가 된다. - 하나의 빈이 등록되려면 최소한 아이디와 클래스 이름이 메타정보로 제공돼야 한다. 빈 스캐너가 클래스를 감지하는 것이니 클래스 이름으 간단히 가져올 수있다. 그런데 빈의 아이디는 어디서 찾을 수 있을까? > 빈 스캐너는 기본적으로 클래스 이름을 빈의 아이디로 사용한다. > 정확히는 클래스 이름의 첫 글자만 소문자로 바꾼 것을 사용한다. 즉 위 코드의 클래스 이름은 `AnnotatedHello` 이니 빈의 아이디는 자동으로 `annotatedHello` 가 된다. `AnnotationConfigApplicationContext`는 빈 스캐너를 내장하고 있는 애플리케이션 컨텍스트 구현 클래스다. 이 클래스의 오브젝트를 생성하면서 생성자에 빈 스캔 대상 패키지를 지정해주면 `스테레오타입 어노테이션`이 붙은 클래스를 모두 찾아 빈으로 등록해준다. 이렇게 어노테이션을 부여하고 자동스캔으로 빈을 등록하면 확실히 XML 에 설정하는것에 비하면 간단하긴 한다. 반면에 애플리케이션에 등록될 빈이 어떤 것들이 있고, 그 정의는 어떻게 되는지를 한눈에 파악할 수 없다는 단점이 있으며, 구성을 파악하기 어렵다. 또한, 이처럼 빈 스캔에 의해 자동등록되는 빈은 XML처럼 상세한 메타정보 항목을 지정할 수 없고, 클래스당 한개 이상의 빈을 등록할수 없다는 제한이 있다. > 개발 중에는 생산성을 위해 빈 스캐닝 기능을 사용해서 빈을 등록하고, 개발이 어느정도 마무리되고 세밀한 관리와 제어가 필요한 운영 시점이 되면 XML 형태의 빈 선언을 적용하는 것도 좋은 전략이다. 애플리케이션 개발, 테스트, 인수 테스트, 운영과 같은 단계마다 독립된 설정정보를 두자. > 자동인식을 통한 빈 등록을 사용하려면 다음 두 가지 방법 중 하나를 쓰면된다. ###### XML을 이용한 빈 스캐너 등록 XML 설정파일 안에 context 스키ㅏ의 전용 태그를 넣어서 간단히 빈 스캐너를 등록할 수 있다. `springbook.learningtest.spring.ioc.bean` 패키지 밑의 모든 빈을 스캔하고 싶다면 XML 설정파일에 `<context:component-scan>` 태그를 넣어주기만 하면 된다. ```xml <context:component-scan base-package="springbook.learningtest.spring.ioc.bean" /> ``` ###### 빈 스캐너를 내장한 애플리케이션 컨텍스트 사용 XML에 빈 스캐너를 지정하는 대신 아ㅖ 빈 스캐너를 내장한 컨텍스트를 사용하는 방법도 있다. 아래는 web.xml 안에 컨텍스트르 파라미터를 설정한 예다. ```xml <context-param> <param-name>contextClass</param-name> <param-value> org.springframework.web.context.support.AnnotationConfigWebApplicationContext </param-value> </context-param> <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/spring/root-context.xml /WEB-INF/applicationContext.xml // 하나 이상의 스캔 대상 패키지를 지정할 수도 있다. 이때는 각 패키지 사이에 공백을 넣어주면 된다. </param-value> </context-param> ``` 만약 서블릿 컨텍스트라면 서블릿 안의 `<init-param>`을 이용해 동일한 정보를 설정해 주면 된다. 빈 클래스 자동인식에는 `@Component` 외에도 다음과 같은 스테레오타입 어노테이션을 사용할 수 있다. - `@Repository` - `@Service` - `@Controller` 각 계층의 핵심 클래스에는 이 세 가지 스테레오타입 어노테이션을 사용하고, 특정 계층으로 분류하기 힘든 경우에는 `@Component`를 사용하는 것이 바람직하다. ##### 4) 자바 코드에 의한 빈 등록 : @Configuration 클래스의 @Bean apthem 의존관계 내에 있찌 않은 제3의 오브젝트를 만들어 의존관계를 가진 오브젝트를 생성하고 메소드 주입을 통해 의존관계를 만들어줬었다. 이처럼 오브젝트 생성과 의존관계 주입을 담당하는 오브젝트를 `오브젝트 팩토리`라고 불렀고, `오브젝트 팩토리`의 기능을 일반화해서 컨테이너로 만든 것이 지그의 스프링 컨테이너, 즉 빈 팩토리라고 볼 수 있다. XML처럼 간략한 표현이 간으한 문서를 이용해서 메타정보를 작성해두고, 컨테이너가 이를 참고해서 오브젝트를 생성하고 DI 해주도록 만드는 것이 효과적이다. 하지만 때로는 오브젝트 팩토리를 직접 구현했을 때처럼 자바 코드를 통해 오브젝트를 생성하고 DI해주는게 유용할 때가 있다. 스프링은 코드를 이용해서 오브젝트를 생성하고 DI를 진행하는 방식으로 만들어진 오브젝트를 빈으로 쓸 수 있는 방법을 제공한다. 바로 `자바코드에 의한 빈 등록기능`이다. - 팩토리 빈과 달리 하나의 클래스 안에 여러 개의 빈을 정의할 수 있다. - 어노테이션을 이용해 빈 오브젝트의 메타정보를 추가하는 일도 가능하다. - XML을 통해 명시적으로 등록하지 않아도 된다. > 사용방법 - `@Configuration` 어노테이션을 클래스위에 건다. - `@Bean`을 빈으로 등록할 메소드에 건다. XML문서와 대비해서 생각해보면 `<beans>` = `@Configuration` / `<bean>` = `@Bean` ```java @Configurtion public class AnnotatedHelloConfig{ @Bean public AnnotatedHello annotatedHello(){ // 메소드 이름이 등록되는 빈의 이름이다. 여기서는 annotatedHello return new AnnotatedHello(); // 자바코드를 이용해 빈 오브젝트를 만들고, 초기화한 후에 리턴해준다. // 컨테이너는 이 리턴 오브젝트를 빈으로 활용한다. } } ``` `AnnotationConfigApplicationContext`를 이용하면, 생성자 파라미터로 `@Configuration`이 부여된 클래스를 넣어주면 된다 이때 설정을 담은 자바 코드에 해당하는 클래스 자체도(AnnotatedHelloConfig) 하나의 빈으로 등록된다 > `@Bean`이 붙은 메소드에서 스프링 컨테이너가 얻을 수 있는 정보는 빈클래스의 종류와 빈의 이름뿐이다. > 자연히 나머지 설정 메타정보는 디폴트 값이 되고, 이에 따라 스코프는 디폴트값인 `싱글톤`으로 만들어진다. 메소드 이름과 리턴 타입에서 얻을 수 있는 기초 메타정보 외에도 부가적인 어노테이션을 이용해 다양한 빈 메타정보 항목을 추가할 수도 있다. > 자바 코드를 이용한 빈 등록은 단순한 빈 스캔닝을 통한 자동인식으로는 등록하기 힘든 기술 서비스 빈의 등록이나 컨테이너 설정용 빈을 XML 없이 등록하려고 할 때 유용하게 쓸 수 있다. ###### 자바 코드에 의한 설정이 XML과 같은 외부 설정파일을 이용하는 것보다 유용한 점을 몇가지 살펴보자. - 컴파일러나 IDE를 통한 타입 검증이 가능하다. - 자동완성과 같은 IDE 지원 기능을 최대한 이용할 수 있다. - 이해하기 쉽다. - 복잡한 빈 설정이나 초기화 작업을 손쉽게 적용할 수 있다. ##### 5) 자바 코드에 의한 빈 등록 : 일반 빈 클래스의 @Bean 메소드 자바 코드에 의한 빈 등록은 기본적으로 `@Configuration` 어노테이션이 붙은 설정 전용 클래스를 이용한다. 그런데 @Configuration이 붙은 클래스가 아닌 일반 POJO 클래스에도 @Bean을 사용할 수 있다. 일반 클래스에서 @Bean을 사용할 경우 싱글톤으로 불러와지지 않기때문에 위험하다 그래서 항상 private으로 선언해두고, 클래스 내부에서도 DI를 통해 찹조해야지 메소드를 직접 호출하면 안된다. ##### 빈 등록 메타정보 구성 전략 지금까지 다섯 가지 대표적인 빈 등록 방법을 간단히 살펴봤다. 다섯 가지 방법 모두 장단점이 있고 사용하기 적절한 조건이 있다. 또한 빈 등록 방법은 꼭 한가지만 사용해야되는 것도 아니다. 즉 두가지 이상의 방법을 섞어서 사용할 수도 있다는 말이다. 대표적인 설정 방법들을 한번 살펴보자 > 1) XML 단독사용 - 컨텍스트에서 생성되는 모든 빈을 XML에서 확인할 수 있다는 장점이 있다. - 빈의 개수가 많아지면 XML파일을 관리하기 번거로워 진다. - 모든 설정정보를 자바 코드에서 분리하고 순수한 POJO 코드를 유지하고 싶다면 가장 좋은 선택이다 - BeanDefinition을 코드에서 직접 만드는 방법을 제외하면 모든 종류의 빈 설정 메타정보 항목을 지정할 수 있는 유일한 방법이다 > 2) XML과 빈 스캐닝 혼용 - 두가지를 혼용하는 방법 - 애플리케이션 3계층의 핵심 로직을 담고 있는 빈 클래스는 그다지 복잡한 빈 메타정보를 필요로 하지 않는다. 대부분 싱글톤이며 클래스당 하나만 만들어지므로 빈 스캐닝에 의한 자동인식 대상으로 적절하다. - 그외 자동인식 방식이 불편한 기술서비스, 기반서비스, 컨테이너 설정 등은 XML로 등록하여 사용한다. - 빈 스캐닝과 XML 각 방법의 장점을 잘 살려서 사용하면 된다. - 단 이때는 컨텍스트 계층구조 내에서 같은 클래스의 빈이 중복등록될 수 있으니 주의하자. - XML을 사용하는 애플리케이션 컨텍스트를 기본으로 하고, 다음과 같이 빈 스캐너를 context 스키마의 `<context:component-scan>`태그를 이용해 등록해주면 된다. ```xml <context:component-scan base-packge="com.mycompany.app" /> ``` - `component-scan`을 사용하면 자바 코드에 의한 설정 방식을 하께 적용할 수도 있다. - `@Configurtion`이 붙은 클래스를 빈 스캔의 대상으로 만들거나 직접 `<bean>`태그로 등록해주면 된다. > 3) XML 없이 빈 스캐닝 단독 사용 - 아예 모든 빈의 등록을 XML 없이 자동스캔만으로 가져가는 방식 - 이때 자바 코드에 의한 빈 등록 방법이 반드시 필요하다. - 주요한 컨테이너 설정과 기반 서비스를 위한 설정은 모두 자바 코드에 의한 빈 설정 방식을 사용해야 한다. (스프링 3.0부터 가능) #### 빈 의존관계 설정 방법 빈 오브젝트 사이의 DI를 위한 의존관계 메타정보를 작성하는 방법을 알아보자. 1. DI 할 대상을 선정하는 방법으로 분류 - 명시적으로 구체적인 빈을 지정하는 방법 > DI할 빈의 아이디를 직접 지정 - 규칙에 따라 자동으로 선정하는 방법 > 주로 타입 비교를 통해서 호환되는 타입의 빈을 DI후보로 삼는방법 `자동와이어링`이라 부른다. 2. 메타정보 작성 방법으로 분류 - XML `<bean>`태그 - 스키마를 가진 전용 태그 - 어노테이션 - 자바코드에 의한 직접적인 DI 이 네가지 방법은 다시 명시적으로 빈을 지정하는 방식과 자동 선정 방식으로 구분할 수 있다. 결과적으로 총 8가지의 빈 의존관계 주입 방법이 있다고 보면 된다. > 빈 의존관계 메타정보 작성 방법을 살펴보자 ##### XML : `<property>`, `<constructor-arg>` - `<bean>`을 이용해 빈을 등록했다면 프로퍼티와 생성자 두 가지 방식으로 DI를 지정할 수 있다. - 프로퍼티 : 자바빈 규약을 따르는 수정자 메소드 사용 - 생성자 : 빈 클래스의 생성자를 이용하는 방법 두 가지 방법 모두 파라미터로 의존 오브젝트 또는 값을 주입해준다. ##### <property> : 수정자 주입 - 수정자를 통해 의존관계에 빈을 주입하려면 `<property>` 태그를 사용할 수 있다. - DI의 가장 대표적인 방법 - 하나의 프로퍼티가 하나의 빈 또는 값을 DI 하는 데 사용될 수 있다 - `ref` 애트리뷰트를 사용하면 빈 이름을 이용해 주입할 빈을 찾는다. - `value` 애트리뷰트는 단순 값 또는 빈이 아닌 오브젝트를 주입할 때 사용한다. - `value` 애트리뷰트로 넣을 수 있는 값의 타입에는 제한이 없다. ##### `<constructor-arg>` - 생성자를 통한 빈 또는 값의 주입에 사용된다. - 생성자의 파라미터를 이용하기 때문에 한 번에 여러 개의 오브젝트를 주입할 수 있다. - 생성자 파라미터는 수정자 메소드처러 간단히 이름을 이용하는 대신 파라미터의 순서나 타입을 명시하는 방법이 필요하다. (특히 같은 타입이 여럿 있는 경우 주의해야 한다.) ##### XML : 자동와이어링 - XML 문서의 양을 대폭 줄여줄수 있는 획기적인 방법 - 명시적으로 프로퍼티나 생성자 파라미터를 지정하지 않고 미리 정해진 규칙을 이용해 자동으로 DI 설정을 컨테이너가 추가하도록 만드는것 - 자동으로 관계가 맺어져야 할 빈을 찾아서 연결해준다는 의미로 자동와이어링이라고 부른다. - 이름을 사용하는 자동와이어링과 타입을 사용하는 자동와이어링 두 가지가 있다. 1) byName : 빈 이름 자동와이어링 많은 경우 프로퍼티의 이름과 프로퍼티에 DI할 빈의 이름이 비슷하거나 같다. 보통 빈의 이르은 클래스 이르이나 구현한 대표적인 인터페이스 이름을 따른다. `<property>`를 사용해 명시적으로 DI 설정을 해주는 XML을 살펴보면 다음과 같이 프로퍼티 이름과 빈 아이디에 같은 이름이 반복적으로 나타나는 모습을 쉽게 찾을 수 있다. ```xml <bean id="hello"...> <property name="printer" ref="printer" /> </bean> <bean id="printer" class="..StringPrinter" > ``` 빈 이름 자동와이어링은 위와같이 이름이 같은 관례를 이용하는 방법으로 hello 빈의 `<bean>` 태그에 다음과 같이 `autowire` 모드를 지정하면 `<property name="printer" ...>`를 생략할 수 있다. ```xml <bean id="hello" class="...Hello" autowire="byName"> <property name="printer" value="Spring" /> </bean> <bean id="printer" class="..StringPrinter" > ``` > 이때 `<beans>`의 디폴트 자동와이어링 옵션을 줄 수 도 있다. ```xml <beans default-autowire="byName"> <bean>....</bean> </beans> ``` > 이처럼 이름에 의한 자동와이어링 방식을 사용하는 경우는 대부분 디폴트 자동와이어링 기법을 사용한다. > 한 두개의 빈만 자동와이어링을 사용할 경우 별 장점이 없기 때문이다. 2) byType : 타입에 의한 자동와이어링 타입에 의한 자동와이어링은 프로퍼티의 타입과 각 빈의 타입을 비교해서 자동으로 연결해주는 방법이다. 이름을 이용하는 자동와이어링 방식은 명명 규칙을 엄격하게 지켜야만 한다. 예를 들자면 이전에 만들어진 클래스를 재사용하거나 규모가 큰 프로젝트라 모든 개발자가 규칙에 따라 정확하게 이름을 부여하기가 어렵다면 이르대신 타입에 의한 자동와이어링을 사용할 수 있다. > 타입에 의한 기법도 `<beans default-autowire="byType"> 으로 사용할 수 있다. 이 방식에 장점만 있는건 아니고 단점도 있는데, 같은 빈이 두 개 이상 존재하는 경우에는 적용되지 못한다. 또한 성능에 문제가 있다. (상대적으로 이름에 의한 와이어링보다 느리다) ##### 1) 어노테이션 : @Resource XML 대신 어노테이션을 이용해 빈의 의존관계를 정의할 수 있는 방법은 두 가지가 있다. 먼저 `@Resource`는 `<property>` 선언과 비슷하게 주입할 빈을 아이디로 지정하는 방법이다. 이때 자바클래스의 수정자뿐만 아니라 필드에도 붙일 수 있다. (1) 수정자 메소드 수정자~setter~는 가장 대표적인 DI방법이다. 수정자 메소드를 이용해 오브젝트 외부에서 내부로 다른 오브젝트의 레퍼런스 또는 값을 전달할 수 있는 주입 경로가 된다. ```java public class Hello{ private Printer printer; ... @Resource(name="printer") public void setPrinter(Printer printer){ this.printer=printer; } } ``` 수정자 메소드의 `@Resource`는 XML의 `<property>`태그에 대응된다고 볼 수 있다. > 참고할점은 프로퍼티의 이름은 따로 정해준게 없다는건데. 이는 자바빈의 수정자메소드의 관례를 따라서 메소드 이름으로부터 프로퍼티 이름을 끌어낼 수 있기 때문이다. > 이렇게 이름이나 타입과 같은 소스코드의 메타정보를 활용할 수 있다는 게 어노테이션 방식의 장점이다. @Resource와 같은 어노테이션으로 된 의존관계 정보를 이용해 DI가 이뤄지게 하려면 다음 세가지 방법 중 하나를 선택해야 한다. - XML의 `<context:annotation-config />` - XML의 `<context:component-scan />` - AnnotationConfigApplicationContext 또는 AnnotationConfigWebApplicationContext `<context:annotation-config />` 에 의해 등록되는 빈 후처리기는 AOP의 자동 프록시 생성기처럼 새로운 빈을 등록해주지는 않는다. 대신 이미 등록된 빈의 메타정보에 프로퍼티 항목을 추가해주는 작업을 한다. `<context:component-scan />` 은 빈 등록도 자동으로 이뤄지기 때문에 `<bean>`은 모두 제거해도 된다. 대신 빈 스캐닝을 위해 Hello와 StringPrinter클래스에 `@Component~를 붙여줘야 한다. 빈 스캐닝은 항상 어노테이션 의존관계 설정을 지 원한다고 기억하면 된다. (2) 필드 `@Resource`는 필드에도 붙을 수 있다. 다음과 같이 지정하면 이 필드의 정보를 참고해서 프로퍼티를 추가해준다. ```java @Component public class Hello{ @Resource(name="printer") private Printer printer; // setPrinter() 메소드 없음 } ``` 이처럼 필드에 붙어 있을 때는 그에 대응되는 수정자가 없어도 상관없다. 이때 필드의 접근자는 `public`이 아니어도 상관없다. 위에서 볼 수 있듯이 private 필드에 setPrinter()메소드가 없어도 문제없다. 스프링이 알아서 필드에 바로 DI해주기 때문이다. > 이런 방법을 `필드주입(field injection)`이라고 한다. 필드 주입은 원한다면 수정자를 넣어도 되고 제거해도 상관없다. 수정자가 없는 필드 주입 `@Resource`의 대표적인 적용 예는 DAO에 DataSource를 DI 하는 경우다. 또한 아래처럼 참조하는 빈의 이름을 생략할수도 있는데 ```java @Resource private Printer printer; ``` 이는 name 엘리먼트를 생략하면 DI할 빈의 이름이 프로퍼티나 필드 이름과 같다고 가정한다. 즉 위의 경우는 name="printer" 라고 한 것이나 마찬가지다. 이처럼 자동으로 프로퍼티 이름과 참조할 빈 이름을 결정해준다는 면에서 XML에서 사용하는 이름을 이용한 자동와이어링과 비슷하게 보이기도 하는데 ++몇 가지 차이점이 있다.++ XML의 자동와이어링은 각 프로퍼티에 주입할 만한 후보 빈이 없을 경우에 무시하고 넘어간다. 즉 Hello클래스에 setPrinter() 메소드가 있지만, 그에 대응되는 printer라는 이름의 빈이 없는 경우에도 에러가 나지 않는다. 단지 빈 전체 프로퍼티 중에서 DI 가능한 것만 찾아내서 주입해주는 상당히 느슨한 방법이다. 반면에 @Resource는 자동와이어링 처럼 프로퍼티 정보를 코드와 관례를 이용해서 생성해내지만 DI 적용 여보를 프로퍼티마다 세밀하게 제어할 수 있다는 점에서 다르다. @Resource가 붙어 있으면 반드시 참조할 빈이 존재해야 한다. 만약 DI할 빈을 찾을 수 없다면 예외가 발생한다. @Resource는 기본적으로 참조할 빈의 이름을 이용해서 빈을 찾는다. <file_sep>/java/god_of_java/Vol.2/06. 자바랭 다음으로 많이 쓴느애들은 컬렉션-Part2(Set과 Queue)/README.md ## 6장. 자바랭 다음으로 많이 쓰는 애들은 컬렉션-Part2(Set과 Queue) ### Set이 왜 필요하지? - Set은 순서에 상관없이, 어떤 데이터가 존재하는지를 확인하기 위한 용도로 많이 사용된다. - 다시 말해서 중복되는 것을 방지하고, 원하는 값이 포함되어 있는지를 확인하는 것이 주 용도다 - 어떤 값이 존재하는지, 없는지 여부몬 중요할 때 Set을 사용하면 된다. 자바에서 Set인터페이스를 구현한 주요 클래스는 HashSet, TreeSet, LinkedHashSet이 있다. - HashSet : 순서가 전혀 필요 없는 데이터를 해시 테이블에 저장한다. Set중에 가장 성능이 좋다. - TreeSet : 저장된 데이터의 값에 따라서 정렬되는 셋이다. red-black 이라는 트리 타입으로 값이 저장되며, HashSet보다 약간 성능이 느리다 - LinkedHashSet : 연결된 목록 타입으로 구현된 해시 테이블에 데이터를 저장한다. 저장된 순서에 따라서 값이 정렬된다. 대신 성능이 이 셋 중에서 가장 나쁘다. > 이러한 성능 차이가 발생하는 이유는 데이터 정렬 때문이다. HashSet은 별도의 정렬작업이 없어 제일 빠르다. > 하지만 몇백 만 건을 처리하지 않는 이상 성능차이를 체감하기는 힘들 것이다. 해시 테이블은 다음장에서 자세히 살펴보도록 하고, red-black 트리는 각 노드의 색을 붉은 색 혹은 검은색으로 구분하여 데이터를 빠르고, 쉽게 찾을 수 있는 구조의 이진 트리를 말한다. > [red-black 트리 참고 위키디피아 바로가기](http://ko.wikipedia.org/wiki/레드-블랙_트리) ### HashSet에 대해서 파헤쳐 보자 먼저 상속관계부터 보자 ```java java.lang.Object java.util.AbstractCollection<E> java.util.AbstractSet<E> java.util.HashSet<E> ``` - `AbstractSet` 을 확장했으며 이 클래스(AbstractSet)는 3개의 메소드만 구현이 되어있다. - Object 클래스에 선언되어 있는 메소드는 `equals()`, `hashCode()`, `removeAll()` 세가지다 - Set은 무엇보다도 데이터가 중복되는 것을 허용하지 않으므로, 데이터가 같은지를 확인하는 작업은 Set의 핵심이다. - `equals()`메소드는 `hashCode()`메소드와 떨어질 수 없는 불가분의 관계다. - `equals()`메소드와 `hashCode()`메소드를 구현하는 부분은 Set에서 매우 중요하다. ### HashSet의 생성자들도 여러종류가 있다. - HashSet 클래스에는 다음과 같이 4개의 생성자가 존재한다. > 로드팩터~loadfactor~라는 것은 뭘까? 로드팩터는 (데이터의개수)/(저장공간)을 의미한다. 로드 팩터라는 값이 클수록 공간은 넉넉해지지만, 데이터를 찾는 시간은 증가한다. 따라서, 초기 공간 개수와 로드팩터는 데이터의 크기를 고려하여 산정하는 것이 좋다. 왜냐하면, 초기크기가 (데이터의 개수)/(로드팩터)보다 클 경우에는 데이터를 쉽게 찾기 위한 해시 재정리 작업이 발생하지 않기 때문이다. 따라서, 대량의 데이터를 여기에 담아 처리할 때에는 초기 크기와 로드팩터의 값을 조절해 가면서 가장 적당한 크기를 찾아야 한다. ### HashSet의 주요 메소드를 살펴보자 - 선언되어 있는 메소드는 그리 많지 않다. - 부모 클래스인 AbstractSet과 AbstracCollectioin에 선언 및 구현되어 있는 메소드를 그대로 사용하는 경우가 많다. ```java import java.util.HashSet; public class SetSample { public static void main(String[] args) { SetSample sample=new SetSample(); String[] cars = new String[] { "Tico", "Sonata", "BMW", "Benz", "Lexus", "Zeep", "Grandeure", "Morning", "Mini Cooper", "i30", "BMW", "Lexus", "Carnibal", "SM5", "SM7", "SM3", "Tico" }; System.out.println(sample.getCarKinds(cars)); } public int getCarKinds(String[] cars){ if(cars==null) return 0; if(cars.length==1) return 1; HashSet<String> carSet=new HashSet<String>(); for(String car:cars){ carSet.add(car); } return carSet.size(); } } ``` > 출력결과 ```java 14 ``` > 이렇게 HashSet과 같은 set을 사용하면 여러 중복되는 값들을 걸러내는 데 매우 유용하다. > 그러면 HashSet에 저장되어 있는 값을 어떻게 꺼낼까? 가장 편한 방법은 for루프를 사용하는것이다. ```java public int getCarKinds(String[] cars){ if(cars==null) return 0; if(cars.length==1) return 1; HashSet<String> carSet=new HashSet<String>(); for(String car:cars){ carSet.add(car); } printCarSet(carSet); return carSet.size(); } public void printCarSet(HashSet<String> carSet){ for(String temp:carSet){ System.out.print(temp+" "); } System.out.println(); } ``` > 출력결과 ```java Carnibal Sonata Lexus BMW Tico Mini Cooper Zeep Benz Morning i30 SM7 Grandeure SM5 SM3 14 ``` > 결과를 보면 저장한 순서대로가 아닌 뒤죽박죽으로 출력된다. 순서가 중요하지 않을때 사용해야 한다. --- ### Queue는 왜 필요할까? 앞 장에서 간단히 소개만 된 `LinkedList`라는 클래스가 있다. - LinkedList는 자료구조에 대해서 배울때 중요한 항목중 하나이기 때문에 꼭 기억하고 있어야만 한다. - 앞에있는 애와 뒤에 있는 애만 기억한다. (열차를 연상해서 기억하자) > 그럼 배열과 차이점은 뭘까? 배열의 중간에 있는 데이터가 지속적으로 삭제되고, 추가될 경우에는 LinkedList가 배열보다 메모리 공간 측면에서 훨씬 유리하다. - LinkedList는 List인터페이스뿐만 아니라 Queue와 Deque 인터페이스도 구현하고 있다 - 즉, LinkedList 자체가 List이면서도 Queue, Deque도 된다. Queue 는 Stack클래스와 반대되는 개념인 FIFO이다(선입선출) > 그럼 큐는 왜 사용할까? 사용자의 요청을 들어온 순서대로 처리할 때 큐를 사용한다. LinkedList 클래스가 구현한 인터페이스 중에서 JDK 6에서 추가된 Deque 라는 것도 있다. - Double Ended Queue 의 약자이며, Deque 는 Queue 인터페이스를 확장하였기 때문에, Queue 의 기능을 전부 포함한다. - 대신 맨앞에 값을 넣거나 빼는 작업, 맨뒤에 값을 넣거나 빼는 작업을 수행한느데 용이하도록 되어있다 ### LinkedList를 파헤쳐보자 > LinkedList 의 상속관계 ```java java.lang.Object java.util.AbstractCollection<E> java.util.AbstractList<E> java.util.AbstractSequentialList<E> java.util.LinkedList<E> ``` - 앞에서 살펴본 것처럼 LinkedList 클래스는 List도 되고 Queue도 된다. - 두 인터페이스의 기능을 모두 구현한 특이한 클래스라고 볼 수 있다. 게다가 Deque인터페이스도 구현한다. ### LinkedList의 생성자의 주요 메소드를 살펴보자 - 일반적인 배열타입의 클래스와 다르게 생성자로 객체를 생성할 때 처음부터 크기를 지정하지 않는다. - 왜냐하면 각 데이터들이 앞 뒤로 연결되는 구조이기 때문에, 미리 공간을 만들어 놓을 필요가 없는 것이다. - 따라서 다음의 두가지 생성자만 존재한다. - LinkedList() : 비어있는 LinkedList 객체를 생성한다. - LinkedList(Collection<? extends E> c) : 매개 변수로 받은 컬렉션 객체의 데이터를 LinkedList에 담는다. - 구현한 인터페이스의 종류가 매우 많은 만큼 메소드 종류도 다양하다. (중복되는 기능을 구현한 메소드들도 많다.) ```java import java.util.LinkedList; public class QueueSample { public static void main(String[] args) { QueueSample sample=new QueueSample(); sample.checkLinkedList1(); } public void checkLinkedList1(){ LinkedList<String> link=new LinkedList<String>(); link.add("A"); link.addFirst("B"); System.out.println(link); link.offerFirst("C"); System.out.println(link); link.addLast("D"); System.out.println(link); link.offer("E"); System.out.println(link); link.offerLast("F"); System.out.println(link); link.push("G"); System.out.println(link); link.add(0, "H"); System.out.println(link); System.out.println("EX=" + link.set(0, "I")); System.out.println(link); } } ``` > 출력결과 ```java [B, A] [C, B, A] [C, B, A, D] [C, B, A, D, E] [C, B, A, D, E, F] [G, C, B, A, D, E, F] [H, G, C, B, A, D, E, F] EX=H [I, G, C, B, A, D, E, F] ``` > 보다시피 같은 기능을 하는 메소드들이 많다... 그렇다면 이중에서 어떤 메소드를 대표적으로 사용하는게 좋을까? 실제 자바의 LinkedList 소스를 보면 맨 앞에 추가하는 메소드는 동일한 기능을 수행하는 어떤 메소드를 호출해도 addFirst()메소드를, offer()관련 메소드를 사용하면 add()나 addLast()메소드를 호출하도록 되어있다. 따라서 되도록 add가 붙은 메소드를 사용해서 오해의 소지를 줄이자! > 특정 위치의 데이터를 꺼내는 메소드들 역시 위와 비슷한데 예를 들면 맨앞에 있는 데이터를 가져올땐 그냥 getFirst()를 사용하자 > 비슷한 이유로 삭제는 remove_가 붙은 메소드를 사용하자 #### 정리를 해보자면 `Set`은 주로 중복되는 데이터를 처리하기 위해 사용되며, `Queue`는 먼저 들어온 데이터를 먼저 처리해주는 FIFO기능을 처리하기 위해서 사용한다. 특히 `Queue`는 여러 쓰레드에서 들어오는 작업을 순차적으로 처리할 때 많이 사용된다. --- ### 정리해 봅시다. 1. Set 인터페이스는 데이터의 순서와 상관없이 데이터를 담을 때 사용한다. 2. HashSet도 ArrayList처럼 int를 매개변수로 갖는 생성자를 통하여 데이터 저장 공간을 명시적으로 지정할 수 있다. 3. HashSet에 데이터를 담는 메소드는 add()이다. 4. HashSet의 contains() 메소드를 사용하면 매개변수로 넘긴 값이 존재하는지 확인할 수 있다. 5. HashSet의 데이터를 지우는 메소드는 remove()이다. 6. FIFO는 First In First Out의 약자로 처음 들어온 값이 먼저 나간다는 것을 의미한다. 7. Deque는 Double Eneded Queue의 약자이다. 8. LinkedList는 List 인터페이스뿐만 아니라 Queue와 Deque 인터페이스도 구현하고 있다. 즉, 목록형 클래스이기도 하면서 큐의 역할도 수행할 수 있다. <file_sep>/php/07. 배열.md ## 배열 ** << 목록 >> ** 1 . 배열 2 . 배열의 생성 3 . 배열의 사용 4 . 배열의 제어 - 배열 크기 , 배열의 조작 [ 추가, 제거, 정렬 ] 5 . 연관배열 6 . 연관배열의 생성 --------------- ##### 배열 * 배열이란 다른 언어에서는 리스트라고도 하는 형태의 데이터 타입이다. * 배열은 연관된 데이터를 모아서 관리하기 위해서 사용하는 데이터 타입이다. * 변수가 하나의 데이터를 임시로 저장하기 위한 것이라면 배열은 **여러 개의 데이터를 저장하기 위한 것**이라고 할 수 있다. --------------- ##### 배열의 생성 ```php <?php $arr = [ 'a' , 'b' , 123 ]; ?> ``` * `대괄호`는 배열을 만드는 기호이다. * 대괄호 안에 데이터를 `콤마`로 구분해서 나열하면 배열이 된다. `php 5.4 이전 버전에서는 아래와 같은 문법을 사용해야 한다. 따라서 하위 호환성을 위해서는 아래의 형식을 사용하는 것이 권장된다.` ```php <?php $arr = array( 'a' , 'b' , 123 ); ?> ``` 데이터를 꺼내는 방법은 아래처럼 사용하면 된다 ```php <?php $arr = [ 'a' , 'b' , 123 ]; echo $arr[0].'<br />'; echo $arr[1].'<br />'; echo $arr[2].'<br />'; ?> ───────────── 출력 ──────────────── a b 123 ``` > 즉 배열에 담겨있는 값을 가져올 때는 대괄호 안에 숫자를 넣는다. > 이 숫자를 색인(**index**)라고 부르고 0부터 시작한다. --------------- ##### 배열의 사용 * 배열의 진가는 `반복문과 결합했을 때` 나타난다. 반복문으로 배열에 담긴 정보를 하나씩 꺼내서 처리 할 수 있기 때문이다. 다음 예제를 보자 ```php <?php function get_members() { return ['egoing','k8805','sorialgi']; } $members = get_members(); for($i = 0; $i < count($members); i++) { echo ucfirst($members[$i]).'<br />'; } ?> ``` > 결과는 아래와 같다. ``` Egoing K8805 Sorialgi ``` 위의 예제에서 주목해야 할 것은 반복문과 배열을 결합한 부분이다. 반복문을 이용해서 배열 $members의 내용을 하나씩 꺼낸 후에 **ucfirst()**를 이용하여 `이름의 첫 글자를 대문자로 변경한 후에 출력`하고 있다. `배열이란` 연관된 정보를 **하나의 그룹**으로 관리하기위해서 사용한다. 그리고 그 정보를 처리할 때는 반복문을 주로 이용한다. --------------- ##### 배열의 제어 * 배열은 복수의 데이터를 효율적으로 관리, 전달하기 위한 목적으로 고안된 데이터 타입이다. * 따라서 데이터의 추가/ 수정/ 삭제와 같은 일을 편리하게 할 수 있도록 돕는 다양한 기능을 가지고 있다. * 몇가지 중요한 기능들만 살펴보자 <br> ###### 배열 크기 `배열의 크기 구하는 메소드 : count(배열)` ```php <?php $a = [1,2,3,4,5]; echo count($a); ?> ───────────── 출력 ──────────────── 5 ``` ###### 배열의 조작 - ** 추가 ** &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`배열의 마지막에 아이템 추가 : array_push(배열, '값');` &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`하나 이상의 배열 병합 : array_merge(배열, ['값1', '값2']);` &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`배열의 시작점에 아이템 추가 : array_unshift(배열, '값');` <br> 다음은 **배열의 끝**에 아이템을 추가하는 예제이다. ```php <?php $arr = ['a','b','c','d','e']; array_push($arr, 'z'); var_dump($arr); ?> ───────────── 출력 ──────────────── array(6) { [0]=> string(1) "a" [1]=> string(1) "b" [2]=> string(1) "c" [3]=> string(1) "d" [4]=> string(1) "e" [5]=> string(1) "z" } ``` <br> 다음은 **복수의 아이템**을 배열에 추가하는 방법이다. `배열을 이용`해서 값을 집어 넣는다. `array_merge(배열, ['값1','값2'])` ```php <?php $li = ['a','b','c','d','e']; $li = array_merge($li, ['f','g']); var_dump($li); ?> ───────────── 출력 ──────────────── array(7) { [0]=> string(1) "a" [1]=> string(1) "b" [2]=> string(1) "c" [3]=> string(1) "d" [4]=> string(1) "e" [5]=> string(1) "f" [6]=> string(1) "g" } ``` <br> 다음은 **배열의 시작점**에 아이템을 추가하는 방법이다. `array_unshift(배열,값)` ```php <?php $li = ['a','b','c','d','e']; array_unshift($li,'start'); var_dump($li); ?> ───────────── 출력 ──────────────── array(6) { [0]=> string(5) "start" [1]=> string(1) "a" [2]=> string(1) "b" [3]=> string(1) "c" [4]=> string(1) "d" [5]=> string(1) "e" } ``` - ** 제거 ** &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`배열의 첫번째 아이템 제거 : array_shift(배열, '값');` &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`배열에 마지막 아이템 제거 : array_pop(배열, ['값1', '값2']);` <br> 배열의 **첫번째 요소를 제거**하는 방법이다 ```php <?php $li = ['a', 'b', 'c', 'd', 'e', 'z']; array_shift($li); var_dump($li); ?> ───────────── 출력 ──────────────── array(5) { [0]=> string(1) "b" [1]=> string(1) "c" [2]=> string(1) "d" [3]=> string(1) "e" [4]=> string(1) "z" } ``` <br> 다음은 **배열의 마지막 요소를 제거**하는 방법이다. ```php <?php $li = ['a', 'b', 'c', 'd', 'e', 'z']; array_pop($li); var_dump($li); ?> ``` <br> ##### ** 정렬 ** ` sort(배열) : 오름차순 정렬` `rsort(배열) : 내림차순 정렬` <br> 다음은 정렬하는 방법이다. ```php <?php $li = ['c','e','a','b','d']; sort($li); var_dump($li); ?> ───────────── 출력 ──────────────── array(5) { [0]=> string(1) "a" [1]=> string(1) "b" [2]=> string(1) "c" [3]=> string(1) "d" [4]=> string(1) "e" } ``` <br> 역순으로 정렬하고 싶을 때는 아래와 같이 한다. ```php <?php $li = ['c','e','a','b','d']; rsort($li); var_dump($li); ?> ───────────── 출력 ──────────────── array(5) { [0]=> string(1) "e" [1]=> string(1) "d" [2]=> string(1) "c" [3]=> string(1) "b" [4]=> string(1) "a" } ``` <br> ##### 연관배열 지금까지 살펴본 배열은 아이템에 대한 식별자로 숫자를 사용했다. 데이터가 추가되면 배열 전체에서 중복되지 않는 인덱스가 자동으로 만들어져서 그 데이터에 대한 식별자가 되는 것이다. PHP에서는 **인덱스로 문자를 사용하는 것도 가능하다**. 일반적으로 다른 언어에서는 숫자를 인덱스로 사용하는 것을 일반적으로 `배열` 혹은 indexed array 라고 하고, 문자를 인덱스로 사용하는 것을 `연관배열`이라고 부르지만, PHP에서는 이를 특별히 구분하지 않고 있기 때문에 , 하나의 배열의 키 값으로 숫자와 문자 모두를 사용할 수 있다. <br> ##### 연관배열의 생성 다음은 연관배열을 만드는 방법이다. ```php <?php $grades = array('egoing'=>10, 'k8805'=>6, 'sorialgi'=>80); // array('키'=>값, '키'=>값, '키'=>값); ?> ``` 위의 예제에서 egoing은 key가 되고 10은 value가 된다. 아래는 연관배열을 만드는 다른 방법이다. ```php <?php $grades = []; $grades['egoing']=10; $grades['k8805']=6; $grades['sorialgi']=80; var_dump($grades); ?> ───────────── 출력 ──────────────── array(3) { ["egoing"]=> int(10) ["k8805"]=> int(6) ["sorialgi"]=> int(80) } ``` <br> 다음은 특정한 key의 값을 가져오는 방법이다. ```php <?php $grades = array('egoing'=>10, 'k8805'=>6, 'sorialgi'=>80); echo $grades['sorialgi']; // $배열이름['키']; ?> ───────────── 출력 ──────────────── 80 ``` <br> 다음은 배열의 데이터를 기준으로 반복작업을 하는 방법이다. ```php <?php $grades = array('egoing'=>10, 'k8805'=>6, 'sorialgi'=>80); foreach($grades as $key => $value) { echo "key: {$key} value: {$value}<br />"; } ?> ───────────── 출력 ──────────────── key: egoing value: 10 key: k8805 value: 6 key: sorialgi value: 80 ``` ##### ** << foreach >> ** 1. 처음부터 끝까지 배열 값을 이용하고 싶을때 쓴다. 2. 문법은 as 뒤에 변수를 적어두면 루프 안에서 배열 안에 존재하는 각 요소를 꺼내서 쓸 수 있다. 3. 형태 : foreach ($array as $value) { 문장 } ```php <?php << foreach문 예제 >> $color = array("red","green","blue","yellow"); // 배열 생성 // 배열 $color[n]:n번째 요소가 $value 들어갑니다. // 예를 들어 첫 번째 실행에서는 $color[0]값인 "red"가 $value안에 들어가 있습니다. foreach($color as $value){ echo "$value<br>"; } ?> ───────────── 출력 ──────────────── red green blue yellow ``` <br> 1. 배열의 요소에 접근할 때는 배열명 뒤에 [숫자]를 사용한다. 2. 위의 예제에서 첫 번째 요소는 $colors[0]이고 마지막 네 번째 요소는 $colors[3]이 됩니다. -> 컴퓨터 언어에서는 0부터 시작하는 것이 기본이다. 3. 배열에서만 실행되는 함수 이다. -> 배열이 아니면 php코드 내에 오류메시지를 출력한다. 4. 배열에 담긴 요소의 숫자만큼 반복문을 실행한다.<file_sep>/php/05. 반복문.md ## 반복문 << 목록 >> 1 . 반복문 2 . 반복문의 문법 while / for 3 . 반복문의 제어 4 . break 5 . continue 6 . 반복문의 중첩 --------------- ##### 반복문 * 반복문은 프로그래밍에서 가장 중요한 요소 중의 하나다. * 반복문은 컴퓨터에게 반복적인 작업을 지시하는 방법이다. --------------- ##### 반복문의 문법 * 반복문의 문법은 몇가지가 있다. 각각의 구문은 서로 대체 가능하기 때문에 상황과 취향에 따라서 선택해서 사용하면 된다. <br> ###### while 형식은 아래와 같다. ```php while(조건) { 코드 코드 } ``` 아래의 예제를 보자 ```php <?php while(true){ echo 'coding everyday'; } ?> ───────────── 출력 ──────────────── coding everyday coding everyday coding everyday .. 무한출력 ``` > 위의 코드를 보면 while의 조건에 true가 들어있으므로 무한 루프가 된다. ```php <?php while(false){ echo 'coding everyday'; } ?> ───────────── 출력 ──────────────── ``` > 위의 코드를 살펴보면 조건에 false가 들어있으므로 coding everyday가 한번도 출력되지 않는다. <table><tr><td> while 문은 조건이 참(true)일 경우에 중괄호 구간의 구문을 반복적으로 실행한다. 조건이 false이면 반복문이 실행되지 않는다. 여기서 true와 false는 종료조건이 되는데, **반복문에서 종료조건을 잘못 지정하면 무한 반복이 되거나, 반복문이 실행되지 않는다.** </td></tr></table> <br> << 증감식과 반복문 >> ```php <?php # i의 값으로 0을 할당한다. $i = 0; # 종료조건으로 i의 값이 5보다 작다면 true, 같거나 크다면 false while($i < 5) { echo 'coding everyday'; # 반복문이 실행될 때마다 i의 값을 1씩 증가시킨다. 그 결과 i의 값이 5가 되면 종료 조건이 false가 되어 반복문이 종료된다. $i += 1; } ?> ``` --------------- ###### for 형식은 아래와 같다. ```php for(초기화; 조건식; 증감식){ 코드; } ``` 다음 예제를 보자 ```php <?php for($i = 0; $i<5; $i++) { echo "coding everyday ".$1."<br />"; } ?> ───────────── 출력 ──────────────── coding everyday 0 coding everyday 1 coding everyday 2 coding everyday 3 coding everyday 4 ``` 위의 예제에서 for문의 초기화 구문은 $i=0이다. `초기화 구문`은 반복문이 실행될 때 **1회에 한해서 최초로 실행**되는 구문이다. 그렇기 때문에 반복문이 처음 실행될 때는 $i의 값이 0이다. 그 다음에는 반복 실행 조건인 조건식 $i<5;가 실행된다. 현재 $i의 값은 0 이기 때문에 결과는 true이다. **반복 실행 조건이 true이면** 중괄호 사이의 구간이 실행된다. 그 결과, 화면에는 coding everybody 0 이 출력된다. 그 후에는 반복 실행 구문이 실행된다. 이것은 반복되다가 $i가 4일때 중괄호 구간의 실행이 끝나면 $i++에 의해서 $i의 값이 5가 된다. 그 결과 $i<5는 false가 되고, 반복문이 종료되게 된다. <br> --------------- ##### 반복문의 제어 ###### break 반복작업을 중간에 중단시키고 싶다면 어떻게 해야할까? break를 사용하면 된다. 아래의 예제는 위에서 살펴본 예제를 일부 변형한 것이다. ```php <?php for($i=0; $i<10; $i++) { if($i === 5){ break; } echo "coding everybody {$i}<br />"; } ───────────── 출력 ──────────────── coding everybody 0 coding everybody 1 coding everybody 2 coding everybody 3 coding everybody 4 ?> ``` > 종료조건에 다르면 10행이 출력돼야 하는데 5행만 출력되었다. > 2행의 if($i === 5)에 의해서 $i의 값이 5일 때 break문이 실행되면서 반복문이 완전히 종료된 것이다. <br> ###### continue 그럼 실행을 즉시 중단 하면서 반복은 지속되게 하려면 어떻게 해야할까? 다음의 예제를 보자 ```php <?php for($i = 0; $i < 10; $i++){ if($i === 5){ continue; } echo "coding everybody {$i}<br />"; } ?> ───────────── 출력 ──────────────── coding everybody 0 coding everybody 1 coding everybody 2 coding everybody 3 coding everybody 4 coding everybody 6 coding everybody 7 coding everybody 8 coding everybody 9 ``` > 위의 코드를 보면 출력에 숫자5가 빠져있다. > 왜냐하면 i의 값이 5가 되었을때 실행이 중단 됐기 때문에 continue 이후의 구문이 실행되지 않았기 때문이다. --------------- ##### 반복문의 중첩 반복문 안에는 다시 반복문이 나타날 수 있다. 다음 예제는 00, 01, 02, ... , 99 까지를 화면에 출력한다. ```php <?php for($i = 0; $i < 10; $i++) { for($j = 0; $j < 10; $j++) { echo "coding everybody {$i}{$j}<br />"; } } ?> ───────────── 출력 ──────────────── coding everybody 00 coding everybody 01 coding everybody 02 coding everybody 03 coding everybody 04 .... .... coding everybody 98 coding everybody 99 ``` 단순히 글자를 반복적으로 출력하기 위해서 반복문을 사용한다고 생각 할 수도 있다. 하지만 반복문의 진가는 배열과 결합했을 때 나타난다. <file_sep>/java/toby_spring/README.md # 토비의 스프링 ## Vol.1 스프링의 이해와 원리 ### 1장 오브젝트와 의존관계 ### 2장 테스트 ### 3장 템플릿 ### 4장 예외 ### 5장 서비스 추상화 ### 6장 AOP ### 7장 스프링 핵심 기술의 응용 ### 8장 스프링이란 무엇인가? ### 9장 스프링 프로젝트 시작하기 ## Vol.2 스프링의 기술과 선택 ### 1장 IoC 컨테이너와 DI ### 2장 데이터 엑세스 기술 ### 3장 스프링 웹 기술과 스프링 MVC ### 4장 스프링 @MVC ### 5장 AOP와 LTW ### 6장 테스트 컨텍스트 프레임워크 ### 7장 스프링의 기타 기술과 효과적인 학습 방법 <file_sep>/java/god_of_java/Vol.1/12. 인터페이스와 추상클래스, enum/README.md ## 12장. 인터페이스와 추상클래스, enum ### 1. 메소드 내용이 없는 interface 자바에서 `.class` 파일을 만들 수 있는 것에는 클래스만 있는 것이 아니다. `interface`와 `abstract`클래스라는 것이 있다. 인터페이스와 abstract 클래스에 대해서 제대로 이해하려면 시스템을 만드는 절차가 어떻게 되는지 알아야 한다. 1.분석 2.설계 3.개발 및 테스트 4.시스템 릴리즈 > DAO~dataAccessObject~ 패턴 이 패턴은 데이터를 저장하는 저장소에서 원하는 값을 요청하고 응답을 받는다. 인터페이스와 abstract클래스를 사용하는 이유 1. 설계시 선언해 두면 개발할 때 기능을 구현하는 데에만 집중 할 수 있다. 2. 개발자의 역량에 따른 메소드의 이름과 매개변수 선언의 격차를 줄일 수 있다. 3. 공통적인 인터페이스와 abstract 클래스를 선언해 놓으면, 선언과 구현을 구분할 수 있다. > 인터페이스는 다음과 같이 정의한다. ```java package c.impl; import c.inheritance.MemberDTO; public interface MemberManagerInterface { public boolean addMember(MemberDTO member); public boolean removeMember(String name, String phone); public boolean updateMember(MemberDTO member); } ``` > 이렇게 만든 인터페이스를 어떻게 활용할까? ```java package c.impl; import c.inheritance.MemberDTO; public class MemberManager implements MemberManagerInterface { } ``` > `implements`라는 예약어를 쓴후 인터페이스들을 나열한다. 단 이렇게만 하고 컴파일을 하면 에러가 난다. > 에러내용을 번역해보면 "작성한 클래스는 abstract클래스도 아니고 abstract메소드도 구현하지 않았다." 정도이다 인터페이스를 구현할 경우 반드시 인터페이스에 정의된 메소드들의 몸통을 만들어 주어야만 한다. > 즉 최소한 인터페이스에 구현된 addMember, removeMember, updateMember 세가지의 메소드는 작성하는 클래스에 만들어줘야 한다는 뜻이다. - > 정리하자면, 설계 단계에서 인터페이스만 만들어 놓고, 개발 단계에서 실제 작업을 수행하는 메소드를 > 만들면 설계 단계의 산출물과 개발 단계의 산출물이 보다 효율적으로 관리될 수 있다. 또한 이런 용도 외에도 외부에 노출되는 것을 정의해 놓고자 할 때 사용된다. > 그럼 인터페이스는 어떻게 사용할까? ```java MemberManagerInterface manager = new MemberManagerInterface(); ``` > 위소스는 컴파일 에러가 난다. 다음과 같이 변경하자 ```java MemberManagerInterface manager = new MemberManager(); ``` > 겉으로 보기에 manager 타입은 MemberManagerInterface이다. > 그리고 MemberManager 클래스에는 인터페이스에 선언되어 있는 모든 메소드들이 구현되어 있다. > 따라서, 실제 manager 타입은 MemberManager가 되기때문에 manager에 선언된 메소드들을 실행하면 MemberManager에 있는 메소드들이 실행된다. ### 2. 일부 완성되어 있는 abstract 클래스 단어의 뜻을 찾아보면 "추상적인"의 의미다. - abstract 클래스는 자바에서 마음대로 초기화하고 실행할 수 없다. - abstract 클래스를 구현해 놓은 클래스로 초기화 및 실행이 가능하다. > interface와 비교해보자 ```java public interface MemberManagerInterface { public boolean addMember(MemberDTO member); public boolean removeMember(String name, String phone); public boolean updateMember(MemberDTO member); } ``` ```java public abstract class MemberManagerAbstract { public abstract boolean addMember(MemberDTO member); public abstract boolean removeMember(String name, String phone); public abstract boolean updateMember(MemberDTO member); public void printLog(String data){ System.out.println("Data="+data); } } ``` > abstract 클래스는 선언시 class라는 예약어 앞에 abstract라는 예약어를 사용한 것을 알 수 있다. > 또한, 몸통이 없는 메소드 선언문에도 abstract라는 예약어가 명시되어 있다. > 이와 같이 abstract 클래스는 abstract로 선언한 메소드가 하나라도 있을 때 선언한다. > 게다가 인터페이스와 달리 구현되어 있는 메소드가 있어도 상관없다. - abstract 클래스는 클래스 선언시 abstract라는 예약어가 클래스 앞에 추가되면 된다. - abstract 클래스 안에는 abstract로 선언된 메소드가 0개 이상 있으면 된다. - abstract로 선언된 메소드가 하나라도 있으면 그 클래스는 반드시 abstract으로 선언되어야만 한다. - abstract클래스는 몸통이 있는 메소드가 0개 이상 있어도 전혀 상관 없으며, `static`,`final`메소드가 있어도 된다( 인터페이스에는 `static` 이나 `final`메소드가 선언되어 있으면 안된다.) 이러한 abstract클래스는 인터페이스처럼 implements라는 예약어를 사용하여 구현할 수 없다. 왜냐하면 인터페이스가 아니라 클래스이기 때문이다. > 그러면 어떤 예약어를 상요하여 이 abstract 클래스를 구현한다고 선언할까? 바로 `extends`라는 예약어를 사용한다. > abstract 클래스를 구현하는 예는 다음과 같다. ```java public class MemberManager2 extends MemberManagerAbstract{ public boolean addMember(MemberDTO member) { return false; } public boolean removeMember(String name, String phone) { return false; } public boolean updateMember(MemberDTO member) { return false; } } ``` > 왜 배우기 힘들게 이런 abstract 클래스를 만들었을까? > 인터페이스를 선언하다 보니, 어떤 메소드는 미리 만들어 놓아도 전혀 문제가 없는 경우가 발생한다. > 그렇다고 해당 클래스를 만들기는 좀 애매하고, 특히 아주 공통적인 기능을 미리 구현해 놓으면 많은 도움이 된다. 이럴때 사용하는 것이 바로 abstract 클래스다. --- ### 3. 나는 내 자식들에게 하나도 안물려 줄꺼여 상속과 관련하여 알아두어야 하는 예약어가 하나 더 있다. 바로 `final`이라는 예약어다. `final`은 클래스, 메소드, 변수에 선언할 수 있다. 1) 클래스에 `final`을 선언할 때에는.. `final`을 접근 제어자와 class 예약어 사이에 추가할 수 있다. ```java public final class FinalClass{ } ``` > 위와 같이 작성하면 상속을 해줄 수가 없다. 즉 자식 클래스를 만들수 없다. 2) 메소드를 `final`로 선언하는 이유는... 메소드를 `final`로 선언하면 더이상 `Overriding`을 할 수가 없다. ```java public final void printLog(String data){ } ``` > final 클래스는 종종 사용하지만 final 메소드는 사용할 일이 거의 없을 것이다. 3) 변수에서 `final`을 쓰는 것은? 클래스나 메소드에 `final`을 사용하면 더 이상 상속을 못 받게 하고, 더이상 `Overriding`할 수 없게 하는것이다. 하지만, 변수에 `final`을 사용하는 것은 개념이 조금 다르다. 변수에 final을 사용하면 그 변수는 "더 이상 바꿀 수 없다" 라는 말이다. 그래서, 인스턴스 변수나 static으로 선언된 클래스 변수는 선언과 함께 값을 지정해야만 한다. > 사용시 주의사항을 코드를 통해 살펴보자 ```java public class ....생략{ final int instanceVariable; } ``` > 위소스는 컴파일 에러가 발생한다 `final`로 선언되어 있을경우는 다음과 같이 변수생성과 동시에 초기화를 해야한다 ```java public class ....생략{ final int instanceVariable=1; } ``` > 그렇다면 매개변수나 지역변수는 어떻까? ```java public void method(final int parameter){ final int localVariable; } ``` > 매개 변수나 지역변수를 `final`로 선언하는 경우에는 반드시 선언할 때 초기화할 필요는 없다. > 왜냐하면, 매개변수는 이미 초기화가 되어서 넘어왔고, 지역변수는 메소드를 선언하는 중괄호 내에서만 참조되므로 다른 곳에서 변경할 일이 없다. 따라서 컴파일은 전혀 문제없이 된다. > 단!! 다음과 같이 사용해서는 안된다. ```java public void method(final int parameter){ final int localVariable; localVariable=2; localVariable=3; parameter=4; } ``` > 지역변수를 2로 선언할 때에는 아무런 문제가 없다 , 하지만 바로 다음줄에 3으로 변경했다. 이렇게 사용시엔 컴파일 에러가 발생한다 매개변수 역시 `final`로 선언되어 있기 때문에 다시 값을 할당하면 안된다. > 즉 fianl로 선언한 변수에 값을 재할당 하면 컴파일 에러가 발생한다. 절대 변하지 않을수 (가령 1월과 12월은 31일까지 있다...) > 헷갈릴수 있는 부분 객체가 `final`로 선언되어 있을 경우는 어떨까? - > 당연히 해당 final 객체는 한 클래스에서 두번 이상 생성할 수 없다 하지만 그객체 안에 있는 객체들은 그러한 제약이 없다 왜냐하면 객체 안에 있는 name,email 등은 final 변수가 아니기 때문이다. 즉 해당 클래스가 final이라고 해서, 그 안에 있는 인스턴스 변수나 클래스 변수가 final은 아니라는 부분은 꼭 기억해 두자. ### 4. enum 클래스라는 상수의 집합도 있다. 상수 : 고정된 값 만약 어떤 클래스가 상수만으로 만들어져 있을 경우에는 반드시 class로 선언할 필요는 없다. 이럴때 class라고 선언하는 부분에 enum이라고 선언하면 "이 객체는 상수의 집합이다."라는 것을 명시적으로 나타낸다 - enum 클래스는 어떻게 보면 타입이지만, 클래스의 일종이다 - 한글로 "열거형" 클래스라고 불러도 무방하다. - enum 클래스에 있는 상수들은 지금까지 살펴본 변수들과 다르게 별도로 타입을 지정할 필요도, 값을 지정할 필요도 없다 - 해당 상수들의 이름만 콤마로 구분하여 나열해 주면 된다. > enum 클래스는 어떻게 사용할까? 가장 효과적으로 사용하는 방법은 switch문에서 사용하는 것이다. ```java public int getOverTimeAmount(OverTimeValues value) { int amount = 0; System.out.println(value); switch (value) { case THREE_HOUR: amount = 18000; break; case FIVE_HOUR: amount = 30000; break; case WEEKEND_FOUR_HOUR: amount = 40000; break; case WEEKEND_EIGHT_HOUR: amount = 60000; break; } return amount; } ``` > 그럼 `OverTimeValues` 라는 enum 타입을 어떻게 위 메소드에 전달할까? ```java public static void main(String args[]) { OverTimeManager manager = new OverTimeManager(); int myAmount = manager.getOverTimeAmount(OverTimeValues.THREE_HOUR); System.out.println(myAmount); } ``` `enum클래스이름.상수이름` 방식으로 지정함으로써 클래스의 객체 생성이 완료된다고 생각하면 된다. - enum클래스는 생성자를 만들 수 있지만, 생성자를 통하여 객체를 생성할 수는 없다. > 그럼 `switch` 문이 아닌 enum클래스 선언시 각 상수의 값을 지정할 수는 없을까? 값을 지정하는 것은 가능하다. 단, 값을 동적으로 할당하는 것은 불가능하다. - enum클래스도 생성자를 사용할 수는 있지만, 생성자의 선언부에 `public`이라고 하지 않고 - 접근지정자가 없거나(package-private)와 private만 사용가능하다. - 보통 클래스와 마찬가지로 메소드를 선언해서 사용할 수 있다. ### 4. enum 클래스의 부모는 무조건 java.lang.Enum - enum클래스는 개발자들이 Object클래스 중 일부 메소드를 Overriding 하지 못하도록 막아놓았다. - hashCode()과 equals()는 사용해도 무방하다 - Object클래스의 메소드를 Overriding한 마지막 메소드는 `toString()`메소드다 #### 정리해봅시다 1. 인터페이스에 선언되어 있는 메소드는 body(몸통)이 있어도 되나요? -> 아니요 2. 인터페이스를 구현하는 클래스의 선언시 사용하는 예약어는 무엇인가요? -> implements => 클래스 선언시 class 가 들어가는 자리에 interface가 위치해야 한다. 3. 메소드의 일부만 완성되어 있는 클래스를 무엇이라고 하나요? -> abstract => abstract 클래스는 인터페이스처럼 메소드를 선언만 할 수도 있고, 일부 메소드를 구현 할 수도 있다. 4. 3번의 문제의 답에 있는 클래스에 body(몸통)이 없는 메소드를 추가하려면 어떤 예약어를 추가해야 하나요? -> extends => abstract 메소드 선언시에는 abstract 예약어를 사용해야 한다. 당연히 해당 클래스도 abstract class로 선언 되어 있어야만 한다. 5. 클래스를 final로 선언하면 어떤 제약이 발생하나요? -> 상속을 해줄 수 없다 6. 메소드를 final로 선언하면 어떤 제약이 발생하나요? -> 오버라이딩을 해줄 수 없다 7. 변수를 final로 선언하면 어떤 제약이 발생하나요? -> 값을 변경하거나 할 수 없다 8. enum 클래스 안에 정의하는 여러 개의 상수들을 나열하기 위해서 상수 사이에 사용하는 기호는 무엇인가요? -> enum 클래스의 상수들은 콤마 , 로 구분한다. 9. enum 으로 선언한 클래스는 어떤 클래스의 상속을 자동으로 받게 되나요? -> java.lang.enum 10. enum 클래스에 선언되어 있지는 않지만 컴파일시 자동으로 추가되는. 상수의 목록을 배열로 리턴하는 메소드는 무엇인가요? -> value() <file_sep>/java/god_of_java/Vol.1/03. OOP/README.md ###객체란? ```java public class Car { //생성자 public Car() { } // 차의 속도 거리 색깔등 "상태"를 나타낸다 int speed; int distance; String color; // Car 클래스의 "행위"를 나타낸다 public void speedUp() { } public void breakDown() { } } ``` > 위 Car 클래스처럼 핸드폰에 대한 클래스에 변수와 메소드를 만들어 보자 ```java public class Smartphone { int battery; String brand; String color; public void on() { } public void off() { } public static void main(String[] args) { } } ``` > 클래스와 객체는 구분해야한다. > '포르쉐'라는 차가 있더라도 개똥이의 '포르쉐'와 소똥이의 '포르쉐'는 다르다. > 주행한 거리도 다를 것이고, 색도 다를것이며, 자동차 등록번호도 다르다 > !!! > 그러면 이때 개똥이와 소똥이의 차를 나타내기 위해서는 별도의 DogCar, CowCar클래스를 만들어야 할까? > -> '포르쉐'라는 클래스를 만들고 그 클래스로 각각의 객체를 생성하면 될 것 같다. ```java Car dogCar = new Car(); Car cowCar = new Car(); ``` ```java public class CarManager { // 참고로 main()메소드의 매개변수인 '[]' 의 위치는 1차원배열일때는 아래처럼 바뀌어도 상관없다 // 그냥 헷갈리니까 일반적인 방법으로 쓰자 public static void main(String args[]) { // } } ``` ```java public class Calcurator { public int add(int num1, int num2) { return num1+num2; } public int addAll(int num1, int num2, int num3) { return num1+num2+num3; } public int subtract(int num1, int num2) { return num1-num2; } public int multiply(int num1, int num2) { return num1*num2; } public int divide(int num1, int num2) { return num1/num2; } public static void main(String[] args) { System.out.println("Calcurator class start"); // 클래스명 객채명 = new Calcurator Calcurator calc=new Calcurator(); } } ``` ```java public class CalcuratorGod { public int add(int num1, int num2) { return num1+num2; } public int addAll(int num1, int num2, int num3) { return num1+num2+num3; } public int subtract(int num1, int num2) { return num1-num2; } public int multiply(int num1, int num2) { return num1*num2; } public int divide(int num1, int num2) { return num1/num2; } public static void main(String[] args) { System.out.println("CalcuratorGod class start"); // 클래스명 객채명 = new Calcurator CalcuratorGod calc=new CalcuratorGod(); int a=10; int b=5; System.out.println("add : "+calc.add(a,b)); System.out.println("subtract : "+calc.subtract(a,b)); System.out.println("multiply : "+calc.multiply(a,b)); System.out.println("divide : "+calc.divide(a,b)); } } ``` #### 직접해 봅시다 1. 1-2장 에서 살펴본 Profile 클래스에 String 타입의 name과 int타입의 age 라는 변수를 선언해 보자. 예를 들면 name은 다음과 같이 선언하면 된다. ```java public class Profile { String name ; int age; public void setName(String str) { name = str; } public void setAge(int val) { age = val; } public void printName() { System.out.println("name 값은 : " + name); } public void printAge() { System.out.println("age 값은 : " + name); } public static void main(String[] args) { String name = "shin"; int age = 29; System.out.println("My name is " + name); System.out.println("My age is "+ age); Profile p = new Profile(); p.setName("Min"); p.setAge(20); p.printName(); p.printName(); } } ``` #### 정리해 봅시다. 1. 클래스와 객체의 차이점을 말해 주세요. -> 클래스는 설계도로 미리 정의 되어있는 변수 ..'포르쉐' -> 객체는 클래스를 이용해 생성한 인스턴스로 '개똥이의 포르쉐', '소똥이의 포르쉐' => 클래스를 통해서 객체를 생성할 수 있다. 즉, 하나의 클래스를 만들면 그 클래스의 모습을 갖는 여러 객체들을 생성 할 수 있다. 그러므로, 일반적인 경우 클래스의 메소드나 변수들을 사용하려면 객체를 생성하여 사용하여야 한다. 2. 객체를 생성하기 위해서 꼭 사용해야 하는 예약어는 뭐라고 했죠? -> new 3. 객체를 생성하기 위해서 사용하는 메소드 같이 생긴 클래스 이름에 소괄호가 있는 것을 뭐라고 하나요? -> 생성자 4. 객체의 메소드를 사용하려면 어떤 기호를 객체이름과 메소드 이름 사이에 넣어주어야 하나요? -> . => 클래스의 변수나 메소드를 호출하려면 "객체이름.변수", "객체이름.메소드이름()"와 같이 사용하면 된다. 5. 클래스의 일반 메소드를 사용하기 위해서는 어떤 것을 만들어야 하나요? -> 객체 <file_sep>/Front-End/gulp/src/js/libs/DOMHelper/tag.js /*! domhelper-tag.js */ function tag(name, parentEl) { return (document || parentEl).getElementsByTagName(name); }<file_sep>/게시판만들기/c-cgi-mysql 게시판 만들기/cgi-bin/bak_160329/common.h #include <stdio.h> #include "cgic.h" #include <string.h> #include <stdlib.h> #include <math.h> #include <malloc.h> #include "/usr/include/mysql/mysql.h" #define MAX_LEN 255 /* 문자열 배열의 최대 길이 */ #define SITE_URL "http://dev-smc.com/cgi-bin" #define server "dev-smc.com" #define user "root" #define pwd "<PASSWORD>" #define database "main" char seq[MAX_LEN], name[MAX_LEN], title[MAX_LEN], content[MAX_LEN]; char seq_val[MAX_LEN], name_val[MAX_LEN], title_val[MAX_LEN], content_val[MAX_LEN]; char email[MAX_LEN], homepage[MAX_LEN], mode[MAX_LEN]; char search_type[MAX_LEN], search[MAX_LEN], search_query[MAX_LEN]; char table[MAX_LEN], query[MAX_LEN], final_query[MAX_LEN]; char alertMsg[MAX_LEN]; char queryArr[4][MAX_LEN]; int i, j ,k; // 반복문에 사용할 int 변수 int strcheck(char *str) { /* 문자열이 NULL이거나 길이가 0인지 체크 */ if (str == NULL) return 0; if (strlen(str) == 0) return 0; return 1; } MYSQL *connection=NULL, conn; MYSQL_RES *res; // (SELECT, SHOW, DESCRIBE, EXPLAIN)등의 쿼리를 내렸을때 그 결과를 다루기 위해 사용되는 구조체이다. MYSQL_RES *final_res; // LIMIT 가 반영된 최종 쿼리 MYSQL_ROW row; // 데이터의 하나의 row 값을 가리킨다. 만약 row 값이 없다면 null 을 가르키게 된다. void mysqlQuery(MYSQL *connection, char *query){ if(mysql_query(connection, query)){ fprintf(stderr, "%s\n", mysql_error(connection)); exit(1); } } // DB 접속 및 접속실패 체크 int mysqlDbConn(){ // mysql 한글문자열 깨짐 방지 mysql_init(&conn); mysql_options(&conn, MYSQL_SET_CHARSET_NAME, "utf8"); mysql_options(&conn, MYSQL_INIT_COMMAND, "SET NAMES utf8"); connection = mysql_real_connect(&conn, server, user, pwd, database, 3306, (char *)NULL, 0); if(connection == NULL){ fprintf(stderr, "%s\n", mysql_error(&conn)); exit(1); } } // select 쿼리 void mysqlDbSelect(char search_type[MAX_LEN] , char search[MAX_LEN] ){ if(strcheck(search_type)){ sprintf(query, "SELECT * FROM bbsc WHERE %s LIKE '%c%s%c' ORDER BY seq desc", search_type, '%', search, '%'); if( mysql_query(connection, query) ){ fprintf(stderr, "%s\n", mysql_error(&conn)); exit(1); } } else{ sprintf(query, "SELECT * FROM bbsc ORDER BY seq desc"); if( mysql_query(connection, query) ){ fprintf(stderr, "%s\n", mysql_error(&conn)); exit(1); } } } // select 쿼리 limit void mysqlDbSelectLimit(char search_type[MAX_LEN] , char search[MAX_LEN], int limit, int list){ if(strcheck(search_type)){ sprintf(final_query, "SELECT * FROM bbsc WHERE %s LIKE '%c%s%c' ORDER BY seq desc limit %d, %d", search_type, '%', search, '%', limit, list); if( mysql_query(connection, final_query) ){ fprintf(stderr, "%s\n", mysql_error(&conn)); exit(1); } } else{ sprintf(final_query, "SELECT * FROM bbsc ORDER BY seq desc limit %d, %d", limit, list); if(mysql_query(connection, final_query)){ fprintf(stderr, "%s\n", mysql_error(&conn)); exit(1); } } } void mysqlSelectOne(char seq[MAX_LEN]){ sprintf(query, "SELECT * FROM bbsc WHERE seq='%s'", seq); if(mysql_query(connection, query) ){ fprintf(stderr, "%s\n", mysql_error(&conn)); exit(0); } } // list Html 만들어주는 함수 void listData(){ printf(" <tr>"); printf(" <td style='text-align:center' >%s</td>\n", row[0]); printf(" <td><a href='write.cgi?seq=%s'>%s</a></td> \n", row[0], row[1]); printf(" <td>%s</td> \n", row[2]); printf(" <tr>"); } //void updateData(char *arr[]){ void updateData(char title[MAX_LEN], char name[MAX_LEN], char content[MAX_LEN], char seq[MAX_LEN]){ sprintf(query, "UPDATE bbsc SET title='%s', name='%s', content='%s' WHERE seq='%s'", title, name, content, seq); mysqlQuery(connection, query); } void insertData(char title[MAX_LEN], char name[MAX_LEN], char content[MAX_LEN]){ sprintf(query, "INSERT INTO bbsc (title, name, content) values('%s', '%s', '%s')", title, name, content); mysqlQuery(connection, query); /* if( mysql_query(connection, query) ){ fprintf(stderr, "%s\n", mysql_error(&conn)); exit(1); } */ } void pagingData(page_num, list, block, block_start_page, block_end_page, total_block, total_page){ // 처음으로 가기 버튼 if(page_num <= 1){ printf(" <li class='disabled'> \n"); printf(" <a href='#' aria-label='Previous'> \n"); printf(" <span aria-hidden='true'>처음</span> \n"); printf(" </a> \n"); printf(" </li> \n"); }else{ printf(" <li> \n"); printf(" <a href='%s/list.cgi?page=&list=%d%s' aria-label='Previous'> \n", SITE_URL, list, search_query); printf(" <span aria-hidden='true'>처음</span> \n"); printf(" </a> \n"); printf(" </li> \n"); } // 이전 블록으로 이동 if(block <= 1){ }else{ printf(" <li> \n"); printf(" <a href='%s/list.cgi?page=%d&list=%d%s' aria-label='Previous'> \n", SITE_URL, block_start_page-1, list, search_query); printf(" <span aria-hidden='true'>이전</span> \n"); printf(" </a> \n"); printf(" </li> \n"); } // 페이징 출력 부분 for( j=block_start_page; j <= block_end_page; j++ ){ if(page_num == j) { printf("<li class='active'><a href='%s/list.cgi?page=%d&list=%d%s '>%d</a></li> \n", SITE_URL, j, list, search_query, j ); }else{ printf("<li><a href='%s/list.cgi?page=%d&list=%d%s'>%d</a></li> \n", SITE_URL, j, list, search_query, j ); } } // 다음 블록으로 이동 if( block >= total_block ){ } else{ printf(" <li> \n"); printf(" <a href='%s/list.cgi?page=%d&list=%d%s' aria-label='Next'> \n", SITE_URL, block_end_page+1, list, search_query); printf(" <span aria-hidden='true'>다음</span> \n"); printf(" </a> \n"); printf(" </li> \n"); } // 마지막으로 가기 버튼 if(page_num >= total_page){ printf(" <li class='disabled'> \n"); printf(" <a href='' aria-label='Next'> \n"); printf(" <span aria-hidden='true'>마지막</span> \n"); printf(" </a> \n"); printf(" </li> \n"); } else{ printf(" <li> \n"); printf(" <a href='%s/list.cgi?page=%d&list=%d%s' aria-label='Next'> \n", SITE_URL, total_page, list, search_query); printf(" <span aria-hidden='true'>마지막</span> \n"); printf(" </a> \n"); printf(" </li> \n"); } } <file_sep>/java/diskstaion_java_lec/04 OOP/README.md ### 객체지향 프로그래밍 OOP #### 1. 추상화 > 생략 #### 2. 캡슐화 > 비유생성 - 설탕,커피,프림 - 동전자판기 - `Data`를 캡슐화 하되 - `Data`에 접근할 때는 메소드로 접근하도록 한다. > 캡슐화방법 - 멤버 변수 앞에 `private` 접근 지정자를 붙인다. (설탕, 프림 에는 접근 불가능하도록) - 이 지정자는 자기 클래스에서만 접근 가능하다. - 멤버 변수에 값을 할당하고 값을 꺼내올 수 있는 메소드를 만든다 ##### `setter` 메소드 > 메소드의 접근 지정자는 `public`으로 주고 `setter`메소드들은 반환타입이 없되, 매개변수를 받아들이도록 ```java public void setName(String n){ name=n; } ``` ##### `getter` 메소드 > `getter`메소드 들은 반환타입이 있되 매개변수는 받아들이지 않는다. ```java public String getName(){ return name; } ``` > UML 툴 알아보기 1056~1057 강의 소스 작성하기 --- #### 3. 다형성 ( Polymorphism ) 1) 오버로딩(Overloading) - 다중정의,중복정의 2) 오버라이딩(Overriding) - 재정의 절차지향 프로그램은 아래처럼 비슷한 기능임에도 전부 다르게 줘야 했다. > 밀크커피 - `void getMilkCoffee(int cf, int s, int cr)` > 블랙커피 - `void getBlackCoffee(int cf)` > 프림커피 - `void getCreamCoffee(int cf, int cr)` 이를 `오버로딩` 개념으로 살펴보면 아래와 같이 바꿀수 있다. > `void getTea(int cf, int su, int cr)` > `void getTea(int cf)` > `void getTea(int cf, int cr)` > `void getTea(Yuja y)` 메소드 이름을 동일하게 주되, 매개변수의 데이터 타입과 갯수, 순서를 다르게 주어 구성하는 것 **오버로딩의 조건** 1. 오버로딩하려는 메소드 이름이 같아야 한다. 2. 메소드의 매개변수의 데이터 타입이 다르거나, 갯수가 다르거나, 순서가 달라야 한다. 3. 메소드의 반환타입은 신경 안써도 된다 - 같아도 되고 달라도 됨 아래는 매개변수의 데이터 **타입**이 같으므로 안된다. ```java void getTea(int cf, int cr) // int, int void getTea(int cf, int sugar) // int, int 형이 이미 선언됬으므로 불가능 ``` 아래는 반환타입이 다르지만 가능하다 ```java void getTea(int cf, int cr) // int, int String getTea(int cf, int sugar) // int, int 형이 이미 선언됬으므로 불가능 ``` 오버로딩의 종류 1. 생성자 오버로딩 2. 메소드 오버로딩 > 생성자 오버로딩 Cafe.java 파일 참조 ```java public class Cafe { public static void main(String[] args) { CoffeeMachine cm = new CoffeeMachine(); int n = cm.getTea(2,2,3); System.out.println("n: "+n); n=cm.getTea(1,2); System.out.println("n: "+n); // Yuja 클래스 꺼내오기 유자=3, 설탕2 Yuja y = new Yuja(); y.yuja=3; // 만약 캡슐화 했다면? y.setYuja(3); 물론 setYuja 메소드를 만들었다고 가정하고 y.sugar=2; cm.getTea(y); } } class CoffeeMachine { int coffee, sugar, cream; //메소드 오버로딩 public int getTea(int cf, int s, int cr) { coffee=cf; sugar=s; cream=cr; System.out.println("밀크커피." + "농도 : " + (coffee+sugar+cream)); return (coffee+sugar+cream); } public int getTea(int cf, int cr) { coffee=cf; cream=cr; int r = coffee+cream; System.out.println("프림커피." + "농도 : " + r); return r; } public String getTea(int cf, String su) { System.out.println("설탕커피." + "농도 : " + cf+su); return cf+su; } public void getTea(Yuja y) { System.out.println("유자 차가 나가요."); System.out.println("유자 농도 : "+y.yuja); System.out.println("설탕 농도 : "+y.sugar); System.out.println("====================="); System.out.println("유자차농도 : "+ (y.sugar+y.sugar)); } } class Yuja { int yuja; int sugar; } ``` 생성자 오버로딩 Ovaerloading.java, Overloading2.java, Overloading3.java 파일 참조 > this() 사용 > 한 클래스 안에 여러 개의 생성자가 오버로딩된 형태로 존재하고, 그 기능이 유사할 때, this라는 키워드를 이용해서 자기 자신의 다른 생성자를 호출할 수 있다. > ㄱ. `this()`는 생성자 안에서만 호출해야 한다. > ㄴ. `this()`를 호출할 때는 반드시 생성자의 첫번째 문장이어야 한다. > ㄷ. 또한 생성자 안에서 `this()`와 `super()`는 함께 쓸 수 없다. > ㄹ. `this()`라는 키워드는 `static`메소드 안에서는 사용할 수 없다. --- #### 4. 상속성 ( Inheritance ) > Overloading.java 파일들을 참조하여 예제 > 각 클래스들의 겹치는 항목들(name, height)와 `showInfo()`메소드같이 겹치는 항목들을 > 부모 클래스로부터 상속받도록 구현하면 재사용성의 이점과, 코드의 중복이 줄어든다. 예를 들어 `Human`이라는 클래스(부모클래스, 슈퍼클래스)를 만들어 기본적인 기능들을 구현하고 `Superman`, `Aquaman` 등의자식클래스(서브클래스)를 만들어 상속받는다. > 자바에서 상속을 받을 때는 `extends`란 키워드를 사용한다. > 단 자바는 단일 상속개념이므로 `extends`로 상속 받을 수 있는 클래스는 단 하나뿐이다. 오버라이딩 메소드 Overriding(재정의) 부모 1. 부모의 것과 동일한 메소드명 2. 매개변수도 동일하게 3. 반환타입도 동일하게 4. 접근지정자는 부모의 것과 동일하거나 더 넓은 범위의 지정자를 사용 5. Exception의 경우 부모 클래스의 메소드와 동일하거나 더 구체적인 Exception을 발생시켜야한다. ```java public class Inheritance { public static void main(String[] args) { /* 아래 소스는 부모클래스의 getInfo()메소드에 power가 없기때문에 이름과 키만 찍어주고 power는 안찍어준다 */ Superman s1 = new Superman(); s1.name="슈퍼맨1"; s1.height=190; s1.power=2000; String info = s1.getInfo(); System.out.println(info); String info2 = s1.getInfo("----슈퍼맨 정보-----"); System.out.println(info2); System.out.println("================="); Human h1 = new Human(); h1.name="사람1"; h1.height=188; String str2 = h1.getInfo(); System.out.println(str2); System.out.println("================="); Aquaman a1 = new Aquaman(); a1.name="아쿠아맨1"; a1.height=190; a1.speed=1200; String infoa = a1.getInfo(); System.out.println(infoa); a1.getInfo("-----아쿠아맨 정보-----",50); System.out.println("================="); } } // 부모 클래스 - Super Class class Human { String name; int height; public String getInfo() { String str="이름: "+name+"\n키: "+height; return str; } } class Superman extends Human { int power; // 메소드 Overriding(재정의) 부모 // 1. 부모의 것과 동일한 메소드명 // 2. 매개변수도 동일하게 // 3. 반환타입도 동일하게 // 4. 접근지정자는 부모의 것과 동일하거나 더 넓은 범위의 지정자를 사용 // 5. Exception의 경우 부모 클래스의 메소드와 동일하거나 // 더 구체적인 Exception을 발생시켜야한다. //오버라이딩 public String getInfo() { //String str="이름: "+name+"\n키: "+height+"\n힘: "+power; String str = super.getInfo()+"\n파워: "+power; return str; } //오버로딩 public String getInfo(String title) { String str = title+"\n"+this.getInfo(); return str; } } class Aquaman extends Human { int speed; public String getInfo() { //String str="이름: "+name+"\n키: "+height+"\n속도: "+speed; String str=super.getInfo()+"\n속도: "+speed; return str; } //오버로딩 public void getInfo(String title, int speed) { System.out.println(title); System.out.println(this.getInfo()); System.out.println("--- 스피드 ---"); this.speed += speed; System.out.println("속도: "+this.speed); } } ``` 상속과 생성자 관계 ```java public class Inheritance2 { public static void main(String[] args) { Student s1 = new Student("홍길동",20,"자바"); Teacher t1 = new Teacher(); Person p1 = new Person("인간",1); } } class Person { String name; int age; public Person() { this("인간",0); } public Person(String n, int a) { name=n; age=a; } } class Student extends Person { String cName; //학급 //인자생성자 public Student(String n, int a, String c) { /* 부모와 자식의 관계를 맺을 경우 자식클래스의 생성자에서 맨처음 하는 일은 부모의 기본생성자 super() 를 호출하는 일이다. 이는 컴파일러가 자동으로 호출한다. */ super(n,a); //이름, 나이는 부모생성자에서 초기화 cName=c; } } class Teacher extends Person { String subject; //과목 public Teacher() { super(null,0); } public Teacher(String n, int a, String s) { super(n,a); subject=s; } } class Staff extends Person { // 부모의 기본생성자를 불러온다. } ``` > 그 참조변수로 참조할 수 있는 범위 1. 부모로부터 물려받은 변수, 메소드[o] 2. 자식이 가지는 고유한 변수 메소드[x] 3. 자식이 오버라이딩한 메소드를 우선호출한다. (부모타입) (변수) = (new) (자식의 객체생성) ```java Parent hs = new Child(); ``` 예제코드 Polymorphism.java 참조 ```java public class Polymorphism { public static void main(String[] args) { Human h1 = new Human(); h1.name = "인간"; h1.showInfo(); Superman s1 = new Superman("슈퍼맨1",1000); s1.showInfo(); s1.showInfo("@@@@슈퍼맨타이틀@@@@"); // (부모타입) (변수) = (new) (자식의 객체생성)이 가능하다 // 부모와 자식의 상속관계일 때 가능 Human hs = new Superman("이동준",300); System.out.println("hs.name = "+hs.name); System.out.println("hs.power = "+hs.power);// 이구문이 컴파일 에러나는 이유는??? System.out.println("================="); hs.showInfo(); // 예외구문 hs.showInfo("############"); // 이번엔 컴파일 에러 } } class Human { String name; public void showInfo() { System.out.println("이름:"+name); } } class Superman extends Human { int power; public Superman(String name, int power) { this.name=name; this.power=power; } //오버라이딩 public void showInfo() { super.showInfo(); System.out.println("파워: "+power); } //오버로딩 public void showInfo(String title) { System.out.println(title); this.showInfo(); } } class Aquaman extends Human { int speed; } ``` --- <file_sep>/java/god_of_java/README.md ## 자바의 신 ### VOL.1 기초문법편 - #### 1장 프로그래밍이란 무엇인가? * Programming의 P * 자바 프로그램의 메소드는 이렇게 구성되어 있어요 * 자바의 가장 작은 단위는 클래스랍니다. * 클래스는 상태를 갖고 있어야 합니다. * 프로그램의 가장 기본은 =를 이해하는 것 * 한 줄을 의미하는 세미콜론 * 모든 프로그래밍 언어에는 예약어라는 것이 있어요 --- - #### 2장 Hello Basic Java * 자바를 배울 환경 준비하기 * HelloBasicJava 만들기 * HelloBasicJava 컴파일하고 실행하기 * main 메소드를 만들자 * System.out.println()과 System.out.print() * 주석(Comment)처리하기 * 메소드를 직접 만들어 보자 --- - #### 3장 자바를 제대로 알려면 객체가 무엇인지를 알아야 해요 * 자바는 객체지향 언어라고 해요 * 클래스와 객체는 구분하셔야 해요 * Car클래스를 구현하자 * 계산기 클래스를 만들어보자 * Calculator 객체를 생성해보자 --- - #### 4장 정보를 어디에 넣고 싶은데 * 자바에서는 네 가지의 변수가 존재해요 * 예제를 통해서 지역 변수를 확실히 익히자 * 변수 이름은 이렇게 * 크게 보면 자바에는 두 가지 자료형이 있답니다. * 기본 자료형은 8개에요 * 8비트와 byte * 다른 정수형 타입들은 어떻게 활용하나? * 소수점을 처리하고 싶어요 * char 와 boolean는 어떻게 쓰는 거지? * 기본 자료형의 기본 값은 뭘까? --- - #### 5장 계산을 하고 싶어요 - 연산자라는 게 뭐지? 벌써 조금 배웠다고? - 간단하게 계산하는 대입 연산자들 - 피연산자가 하나인 것도 있어요. 이걸 단항 연산자라고 하죠 - 자바에서 계산하는 순서를 알아두면 좋다. - 뭔가를 비교할 때는 어떻게 하지? - 논리 연산자들을 알아보자 - 아주 특이한 ?: 연산자 - 기본 자료형의 형 변환을 이용한 변신 - 타입 별 사용 가능한 연산자 알아보기 --- - #### 6장 제가 좀 조건을 따져요 - 도대체 얼마나 조건을 따지길래... - if를 조금 더 다양하게 사용해보자 - 자바의 switch와 불켜는 스위치는 별 상관 없다. - 반복문이라구요? - 가장 확실한 for루프 --- - #### 7장 여러 데이터를 하나에 넣을 수는 없을까요? - 하나에 많은 것을 담을 수 있는 배열이라는 게 있다는데.... - 배열의 기본값 - 배열을 그냥 출력해보면 어떻게 나올까? - 배열을 선언하는 또 다른 방법 - 별로 사용하지는 않지만, 알고 있어야 하는 2차원 배열 - 배열의 길이는 어떻게 알 수 있을까요? - 배열을 위한 for 루프 - 자바 실행할 때 원하는 값들을 넘겨주자 --- - #### 8장 참조 자료형에 대해서 알아봅시다. - 참조 자료형은 나머지 다에요 - 기본 생성자 - 생성자는 몇 개까지 만들 수 있을까? - 이 객체의 변수와 매개 변수를 구분하기 위한 this - 메소드 overloading - 메소드에서 값 넘겨주기 - static 메소드와 일반 메소드의 차이 - static 블록 - Pass by value, Pass by reference - 매개 변수를 지정하는 특이한 방법 --- - #### 9장 자바를 배우면 패키지와 접근 제어자는 꼭 알아야 해요 - 패키지는 그냥 폴더의 개념이 아니에요 - 패키지 이름은 이렇게 지어요 - import를 이용하여 다른 패키지에 접근하기 - 자바의 접근 제어자 - 클래스 접근 제어자 선언할 때의 유의점 --- - #### 10장 자바는 상속이라는 것이 있어요 - 자바에서 상속이란? - 상속과 생성자 - 메소드 Overriding - 참조 자료형의 형 변화 - Polymorphism - 자식 클래스에서 할 수 있는 일들을 다시 정리해보자 --- - #### 11장 모든 클래스의 부모 클래스는 Object에요 - 모든 자바 클래스의 부모인 java.lang.Object 클래스 - Object 클래스에서 제공하는 메소드들의 종류는? - Object 클래스에서 가장 많이 쓰이는 toString() 메소드 - 객체는 == 만으로 같은지 확인이 안 되므로, equals()를 사용하죠 - 객체의 고유값을 나타내는 hashCode() --- - #### 12장 인터페이스와 추상클래스, 그리고 enum - 메소드 내용이 없는 interface - 인터페이스를 직접 만들어보자 - 일부 완성되어 있는 abstract 클래스 - 나는 내 자식들에게 하나도 안 물려 줄꺼여 - enum 클래스라는 상수의 집합도 있다. - enum을 보다 제대로 사용하기 - enum 클래스의 부모는 무조건 java.lang.Enum이어야 해요 --- - #### 13장 클래스 안에 클래스가 들어갈 수도 있구나 - 클래스 안의 클래스 - Static nested 클래스의 특징 - 내부 클래스와 익명클래스 - Nested 클래스의 특징은 꼭 알아야 한다. --- - #### 14장 다 배운거 같지만, 예외라는 중요한 것이 있어요 - 자바에서 매우 중요한 예외 - try-catch는 짝이다 - try-catch를 사용하면서 처음에 적응하기 힘든 변수 선언 - finally 야 ~ 넌 무슨 일이 생겨도 반드시 실행해야 돼 - 두 개 이상의 catch - 예외의 종류는 세 가지다 - 모든 예외의 할아버지는 java.lang.Throwable 클래스다. - 난 예외를 던질 거니까 throws라고 써놓을께 - 내가 예외를 만들 수도 있다구? - 자바 에외 처리 전략 --- - #### 15장 어노테이션이라는 것도 알아야 한다 - 어노테이션이란? - 미리 정해져 있는 어노테이션들은 딱 3개뿐 - 어노테이션을 선언하기 위한 메타 어노테이션 - 어노테이션을 선언해 보자 - 어노테이션에 선언한 값은 어떻게 확인하지? - 어노테이션도 상속이 안돼요 --- - #### 16장 이제 기본 문법은 거의 다 배웠으니 정리해 봅시다 - 객체지향 개발과 관련된 용어들 - 자바의 주석문(Comment) - 패키지와 import - 자바에서 사용되는 타입의 종류 - 변수의 종류 - 계산을 쉽게 도와주는 연산자들 - 조건문들 - 반복문들 - 아무나 사용 못하게 막아주는 접근 제어자 - 선언할 때 사용할 수 있는 각종 제어자들 - 자바를 구성하는 클래스, 인터페이스, abstract클래스 - 메소드의 선언 - 자주 사용하게 되는 상속 - 예외를 처리하자 - 어노테이션을 선언할 때 사용하는 메타 어노테이션들 --- ###VOL.2 API <file_sep>/java/god_of_java/Vol.1/13. 클래스 안에 클래스가 들어갈 수도 있구나/README.md ## 13. 클래스 안에 클래스가 들어갈 수도 있구나 ### 1. 클래스 안의 클래스 자바에서는 클래스 안에 클래스가 들어갈 수 있다. 이러한 클래스를 `Nested` 클래스라고 부른다. `Nested`클래스가 존재하는 가장 큰 이유는 코드를 간단하게 표현하기 위함이다. UI처리를 할 때 사용자의 입력이나, 외부의 이벤트에 대한 처리를 하는 곳에서 가장 많이 사용된다. > `Nested`클래스는 선언한 방법에 따라 > - `Static nested`클래스와 `내부(inner)`클래스로 구분된다. > - 두 클래스의 차이는 `static`으로 선언되었는지 여부다. 내부클래스 - `로컬(지역) 내부 클래스` -> 이름이 있는 내부 클래스 - `익명 내부 클래스` -> 이름이 없는 내부 클래스 - 일반적으로 줄여서 각각 `내부클래스`와 `익명클래스`로 부른다. > `Nested`클래스를 만드는 이유 1. 한 곳에서만 상요되는 클래스를 논리적으로 묶어서 처리할 필요가 있을 때 2. 캡슐화가 필요할 때(예를 들어 A라는 클래스에 `private`변수가 있다. 이 변수에 접근하고 싶은 B라는 클래스를 선언하고, B클래스를 외부에 노출시키고 싶지 않을 경우가 여기에 속한다) 3. 소스의 가독성과 유지보수성을 높이고 싶을때 여기서 **1번**이 `Static Nested` 클래스를 사용하는 이유고, **2번**이 `내부클래스`를 사용하는 이유다 ### 2. Static nested 클래스의 특징 내부클래스는 감싸고 있는 외부 클래스의 어떤 변수도 접근할 수 있다. 심지어 private로 선언된 변수까지도 접근 가능하다. **하지만 `Static nested`클래스를 그렇게 사용하는 것은 불가능하다.** ```java public class OuterOfStatic { static class StaticNested { private int value = 0; public int getValue() { return value; } public void setValue(int value) { this.value = value; } } } ``` 감싸고 있는 파일을 컴파일하면 자동으로 내부변수도 컴파일된다. > 그러면 이 `StaticNested` 클래스의 객체는 어떻게 생성할 수 있을까? > 아래 예제처럼 `.`을 통해 접근하면 된다. ```java package c.inner; public class NestedSample { public static void main(String[] args) { NestedSample sample = new NestedSample(); sample.makeStaticNestedObject(); } public void makeStaticNestedObject() { OuterOfStatic.StaticNested staticNested = new OuterOfStatic.StaticNested(); staticNested.setValue(3); System.out.println(staticNested.getValue()); } } ``` ### 3. 내부 클래스와 익명클래스 앞절에서 살펴본 Static nested 클래스와 내부 클래스의 차이는 겉으로 보기에는 그냥 static을 쓰느냐 쓰지 않느냐의 차이만 있을 뿐이다 ```java package c.inner; public class OuterOfInner { class Inner { private int value = 0; public int getValue() { return value; } public void setValue(int value) { this.value = value; } } } ``` > `StaticNested` 와 Inner 클래스의 내부 내용은 동일하다 하지만 클래스의 객체를 생성하는 방법은 다르다. ```java public void makeInnerObject() { OuterOfInner outer = new OuterOfInner(); OuterOfInner.Inner inner = outer.new Inner(); inner.setValue(3); System.out.println(inner.getValue()); } ``` > 보다시피 같이 먼저 감싸고 있는 객체를 생성해준 후에 안쪽의 클래스객채를 생성해준걸 볼수 있다. - 주로 GUI관련 프로그램을 개발할 때 가장 많이 사용한다. - GUI 에서 내부 클래스들이 많이 사용되는 부분은 Listener(리스너)라는 것을 처리 할때다. - 버튼클릭, 키보드 입력등 모두 Event라는 것이 발생하는 이때의 작업을 정의하기 위해서 내부클래스를 만들어 사용하게 된다. - 즉 어떤 버튼이 눌럿렸을 때 수행해야하는 작업은 대부분 상이한 부분을 생각해보면 될 것 같다. - 그리고 내부 클래스를 만드는 것 보다도 더 간단한 방법은 `익명 클래스`를 만드는 것이다. ```java public class MagicButton { public MagicButton() { } private EventListener listener; public void setListener(EventListener listener) { this.listener = listener; } public void onClickProcess() { if (listener != null) { listener.onClick(); } } } ``` > EventListener.java ```java public interface EventListener { public void onClick(); } ``` > `setButtonListener()` 메소드 ```java public void setButtonListener() { MagicButton button = new MagicButton(); MagicButtonListener listener = new MagicButtonListener(); button.setListener(listener); //or button.setListener(new EventListener() { public void onClick() { System.out.println("Magic Button Clicked !!!"); } }); // 클래스 이름도 없고, 객체 이름도 없기 때문에 다른곳에서는 참조할 수 없기 때문에 // 재사용하려면 아래처럼 객체를 생성한 후 사용하면 된다. EventListener listener2=new EventListener() { public void onClick() { System.out.println("Magic Button Clicked !!!"); } }; button.setListener(listener2); button.onClickProcess(); } ``` > `MagicButtonListener()` ```java class MagicButtonListener implements EventListener { public void onClick() { System.out.println("Magic Button Clicked !!!"); } } ``` > `setListener()`메소드를 보면 `new EventListener()`로 생성자를 호출한 후 바로 중괄호를 열었다 > 그리고 그 안에 onClick()메소드를 구현한 후 중괄호를 닫았다. 이렇게 구현한 것이 바로 `익명클래스`다 그냥 내부 클래스를 만들면 되는데 왜 자바에서는 이렇게 복잡하게 익명클래스라는 것을 제공하는 것일까? - 클래스를 만들고, 그 클래스를 호출하면 그 정보는 메모리에 올라간다. - 즉 클래스를 많이 만들면 만들수록 메모리는 많이 필요해지고, 애플리케이션을 시작 할 때 더 많은 시간이 - 소요된다. 따라서 자바에서는 이렇게 간단한 방법으로 객체를 생성할 수 있도록 해 놓았다. > 결론적으로 익명클래스나 내부 클래스는 모두 다른 클래스에서 재사용할 일이 없을 때 만들어야 한다. **정리해봅시다** 1. Nested 클래스에 속하는 3가지 클래스에는 어떤 것들이 있나요? -> static, 내부클래스, 익명클래스 2. Nested 클래스를 컴파일하면 Nested클래스 파일의 이름은 어떻게 되나요? -> 외부클래스$내부클래스 3. Static Nested 클래스는 다른 Nested 클래스와 어떤 차이가 있나요? -> static이 붙어있다. => Static nested 클래스와 다른 nested 클래스의 차이점은 객체를 생성하는 방법이 다르다는 것이다. 4. StaticNested 클래스의 객체 생성은 어떻게 하나요? -> 외부클래스.내부클래스 = new 객체생성 => OuterClass클래스 내에 StaticNestedClass 이라는 static nested 클래스가 있다면, OuterClass.StaticNestedClass staticNested=new OuterClass.StaticNestedClass(); 와 같이 선언한다. 5. 일반적인 내부 클래스의 객체 생성은 어떻게 하나요? -> 외부클래스먼저 객체생성후 내부클래스를 객체생성 => OuterClass클래스 내에 NestedClass 라는 inner 클래스가 있다면, OuterClass outer=new OuterClass(); OuterClass.NestedClass nested=outer.new NestedClass(); 로 선언한다. 6. Nested 클래스를 만드는 이유는 무엇인가요? -> 코드의 중복을 피하고 가독성을 높이며 , 다른클래스에서 접근할 필요가 없을때 => Nested 클래스를 생성하는 이유는 다음과 같다. - 한 곳에서만 사용되는 클래스를 논리적으로 묶어서 처리할 필요가 있을 때 - 캡슐화가 필요할 때(예를 들어 A 라는 클래스에 private 변수가 있다. 이 변수에 접근하고 싶은 B라는 클래스를 선언하고, B 클래스를 외부에 노출시키고 싶지 않을 경우가 여기에 속한다.) - 소스의 가독성과 유지보수성을 높이고 싶을 때 7. Nested 클래스에서 감싸고 있는 클래스의 private 로 선언된 변수에 접근할 수 있나요? -> 예 => 내부 클래스와 익명 클래스는 감싸고 있는 클래스의 어떤 변수라도 참조할 수 있다. 8. 감싸고 있는 클래스에서 Nested 클래스에 선언된 private 로 선언된 변수에 접근할 수 있나요? -> 예 => 감싸고 있는 클래스에서 Static Nested 클래스의 인스턴스 변수나 내부 클래스의 인스턴스 변수로의 접근하는 것도 가능하다. <file_sep>/Front-End/gulp/src/js/libs/Event/removeEvent.js /*! removeEvent.js */ var removeEvent = (function(){ if(window.removeEventListener) { return function(el, type, fn) { el.removeEventListener(type, fn, false); }; } else if(window.detachEvent) { return function(el, type, fn) { el.detachEvent('on'+type, fn); }; } else { return function(el, type, fn) { el['on'+type] = null; }; } })();<file_sep>/java/god_of_java/Vol.1/08. 참조자료형/README.md ## 8장. 참조 자료형에 대해서 더 자세히 알아봅시다. ### 1. 참조 자료형은 나머지 다에요. - 기본자료형과 가장 큰 차이는 `new`라는 예약어를 사용해서 객체를 생성하는지 여부의 차이 - 단 `new`없이 객체를 생성할 수 있는 참조 자료형은 오직 `String` --- ### 2. 기본생성자 - 생성자를 만들지 않아도 자동으로 만들어지는 기본생성자는?? -> 대표적으로 `main()` 메소드에서 클래스의 이름으로 객체를 생성한 것이 바로 기본생성자!. > 반복학습 차원에서 다시한번 기본구조 작성해보기 (참고 없이 바로) -- ```java public class ReferenceTypes { public static void main(String[] args) { ReferenceTypes refer = new ReferenceTypes(); } } ``` > #####정리해보기 > - ReferenceTypes 클래스의 인스턴스인 reference를 만들었다. > - 등호 우측에 `new` 옆에 있는 `ReferenceTypes()` <--이게 생성자 ```java public ReferenceTypes(String data) { } public static void main(String[] args) { ReferenceTypes sample = new ReferenceTypes(); } ``` > 위처럼 컴파일 하면 아무런 매개변수가 없는 생성자는 다른 생성자가 없을경우에 기본으로 만들어지기 때문에 > 매개변수가 없는 생성자를 사용하고 싶다면 아래처럼 기본생성자를 직접 생성해줘야 해야한다. ```java public ReferenceTypes() { } public ReferenceTypes(String data) { } public static void main(String[] args) { ReferenceTypes sample = new ReferenceTypes(); } ``` ##### **자바에서 생성자는 왜 필요할까?** 생소한 개념으로 가장 헷갈렸던 부분인 만큼 확실한 숙지가 필요하다. - 자바 클래스의 객체(또는 인스턴스)를 생성하기 위해서 존재한다 - 메소드와 생성자는 선언방식이 비슷하지만. 생성자는 **리턴타입이 없고**, 메소드 이름대신 **클래스 이름과 동일**하게 이름을 지정한다. - 리턴타입이 없는 이유는 생성자의 리턴타입은 **클래스의 객체**이기 때문이며, 클래스와 이름이 동일해야 컴파일러가 "아~ 얘가 생성자구나~" 하고 알아 먹기 때문. - 추가로. 생성자를 작성할때에는 클래스의 가장 윗부분에 선언하는 것이 좋다. --- ### 3. 생성자는 몇개까지 만들 수 있을까? 제목부터가 첫날부터 지금까지 끊임없이 생성자에 대한 정의로 날 혼란스럽게 했던 문구...주의깊게 살펴보자 - 1개여도 되고 100개가 되도 상관이 없다. - 자바의 패턴중에서 `DTO`라는 것이 있다. 어떤 속성을 갖는 클래스를 만들고, 그 속성들을 쉽게 전달하기 위해서 `DTO` 라는 것을 만든다. - `DTO`는 `Data Transfer Object`의 약자로 비슷한 클래스로 `VO`라는 것도 있다. - `VO`는 `Value Object`의 약자로 `DTO`와 형태는 동일하지만, 데이터를 담아두기 위한 목적으로 사용되며,`DTO`는 데이터를 다른 서버로 전달하기 위한 것이 주 목적이다. - 어떻게 보면 `DTO`가 `VO`를 포함한다고도 볼 수 있기 때문에 대부분 `DTO`라는 명칭을 선호한다. > [자바패턴 검색 바로가기](https://www.google.co.kr/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=%EC%9E%90%EB%B0%94%20%ED%8C%A8%ED%84%B4) - 한 사람의 개인정보를 담은 `DTO`클래스가 있다고 생각해보자. > 이름, 전화번호, 이메일주소 세가지의 정보를 담고 있는 `MemberDTO`라는 클래스를 만들어보자 ```java public class MemberDTO { public String name; public String phone; public String email; } ``` > 위처럼 `DTO`를 만들어두면 무슨 장점이 있을까? 자바의 메소드를 선언할 때 리턴 타입은 한 가지만 선언할 수 있다. 이때 `DTO`를 만들어 놓으면 메소드의 리턴 타입에 `MemberDTO`로 선언하고, 그 객체를 리턴해주면 된다. ```java public MemberDTO getMemberDTO { MemberDTO dto=new MemberDTO(); return dto; } ``` > 위에 만든 클래스와 패턴까지 연계해가면서 알아보는 이유는 바로 생성자 때문이다. > 이 클래스의 객체를 생성할때는 - 그사람의 아무 정보도 모를 때 - 이름만 알때 - 이름과 전화번호만 알때 - 모든 정보를 알고 있을 때도 있다. > 이러한 각각의 상황에 따른 생성자를 `MemberDTO`에 추가하면 다음과 같이 구현할 수 있다. ```java public class MemberDTO { public String name; // public static String name; public String phone; public String email; /** * 아무 정보도 모를때 */ public MemberDTO() { } /** * 이름만 알때 * * @param name */ public MemberDTO(String name) { this.name = name; } /** * 이름과 전화번호만 알 때 * * @param name * @param phone */ public MemberDTO(String name, String phone) { this.name = name; this.phone = phone; } /** * 모든 정보를 알고 있을 * * @param name * @param phone * @param email */ public MemberDTO(String name, String phone, String email) { this.name = name; this.phone = phone; this.email = email; } } ``` > 위의 코드를 보면 매개변수가 없는 생성자를 제외하고 모두 `this`라는 예약어가 사용된 것을 볼 수 있다. > 이 예약어를 변수에 사용할 때에는 객체의 변수와 매개 변수의 이름이 동일 할 때, 인스턴스의 변수를 구분하기 위해서 사용한다. 방금 만든 네 개의 생성자를 사용하여 `MemberDTO`의 객체를 생성해보자. ```java public void makeMemberObject() { MemberDTO dto1 = new MemberDTO(); MemberDTO dto2 = new MemberDTO("Sangmin"); MemberDTO dto3 = new MemberDTO("Sangmin", "010XXXXYYYY"); MemberDTO dto4 = new MemberDTO("Sangmin", "010XXXXYYYY", "<EMAIL>"); } ``` > 이렇게 네 가지 생성자를 모두 활용하여 객체를 생성할 수 있다. > 어떻게 보면 모두 `MemberDTO`의 객체들이지만 이 네 가지 생성자로 만든 객체들은 서로 다른 속성값들을 갖고 있다. - dto1 : 아무런 속성값도 설정된 것이 없기 때문에 모든 문자열의 값이 지정되어 있지 않다. - dto2 : 이름만 지정되어 있다. - dto3 : 이름과 전화번호가 지정되어 있다. - dto4 : 모든 속성값이 지정되어 있다. --- ### 4. 이 객체의 변수와 매개변수를 구분하기 위한 ==this== `javascript`에서 사용하면서도 명확한 개념이 없었던 `this`에관한 설명 - 말그대로 "이 객체"의 의미다. - 생성자와 메소드 안에서 사용할 수 있다. > 앞장에서 살펴본 생성자 중 제일 상단에 매개변수를 하나만 받는 생성자를 다시 살펴보자 ```java public class MemberDTO { public String name; public String phone; public String email; public MemberDTO(String name) { this.name=name; } } ``` > 이 코드에 `this`라는 예약어가 없으면 어떻게 될까? (생각해보기) 컴파일러(javac)입장에서 생각해보자. 변수인 name도 있고 매개 변수로 넘어온 name도 있다. 즉 `this.name`이라고 지정해 주면, 매개 변수 안에 있는 name이 아닌 "이 객체의 name"이라고 명시적으로 표현하는게 된다! > `this`예약어는 이렇게 변수에만 지정할 수 있는 것이 아니고, 메소드에도 지정할 수 있다. > ==상속==에 관한 내용을 배운후에 살펴보자 --- ### 5. 메소드 overloading 이 장의 앞 부분에서 살펴본 것처럼 클래스의 생성자는 매개 변수들을 서로 다르게하여 선언할 수 있다. 그렇다면 메소드도 이렇게 이름은 같게 하고 매개변수들을 다르게 하여 만들 수 있을까? > 자바의 중요한 개념이라고 하니 반복숙달 차원에서 long, byte등으로 컴파일 실행 과정 ```java public void print(int data) { } public void print(String data) { } public void print(int intData, String stringData) { } public void print(String stringData, int intData) { } ``` > 위의 메소드들은 모두 이름이 동일하지만 다른 메소드로 취급된다. | 꼭 기억하세요! | |--------| | 여기에 있는 메소드들은 이름이 같지만 전부 다른 메소드로 취급된다. 즉 ==매개변수의 타입==에 따라 다르게 인식되며 3,4번째메소드처럼 순서가 다르더라도 다르게 인식된다 | > 이와같이 메소드의 이름을 같도록 하고, 매개 변수만을 다르게 하는 것을 바로 오버로딩 ~overloading~이라고한다. 개념이 헷갈린다면 그동안 많이 사용한 `System.oub.println()`메소드를 생각해보자. 이 메소드의 매개변수로, `int`만 넘겨줘도 되고, `long`만 넘겨줘도 `String`만 넘겨줘도 된다. 이게 바로 오버로딩의 잇점이다. `int`형일 경우에는 `System.out.printlnInt()`라는 메소드를 사용하고, `long`형일 경우는 `System.out.printlnLong()`라고 넘겨야한다면 얼마나 귀찮겠는가? > 쉽게 설명해서 메소드 오버로딩은 =="같은 역할은 같은 메소드 이름을 가져야 한다."== 라는 모토로 사용하는 것이라고 기억하자 --- ### 6. 메소드에서 값 넘겨주기 이번 절에서는 메소드의 수행과 종료에 대해서 알아보자. 자바에서 메소드가 종료되는 조건은 다음과 같다. - 메소드의 모든 문장이 실행되었을 때 - return 문장에 도달했을 때 - 예외를 발생~throw~했을때 지금까지는 대부분의 메소드를 선언할 때 메소드 이름 앞에 `void`라고 썻었다. 이의 사전적의미는 - 빈 공간, 공동;공허감 - ...이 하나도 없는 - 무효의, 법적 효력이 없는 라고 나온다. 즉 자바에서 "이 메소드는 아무것도 돌려주지 않습니다" 라는 의미로 생각하자 이렇게 `void`라고 선언했을 때에는 메소드의 마지막 부분까지 수행되면 메소드가 종료된다. 그러면 `void`외에 다른 것은 어떤 것을 넘겨줄 수 있을까? > 기본적으로 자바에서는 모든타입을 한 개만 리턴타입으로 넘겨줄 수 있다. > 모든 기본자료형과 참조자료형 중 하나를 리턴할 수 있다. 그러면 `int,int`의 배열 ,`String`을 리턴하는 예제를 작성해보자 ```java public int intReturn() { int returnInt = 0; return returnInt; } public int[] intArrayReturn() { int returnArray[] = new int[10]; return returnArray; } public String stringReturn() { String returnString = "Return value"; return returnString; } ``` > 리턴 타입을 명시해주지 않으면 컴파일 에러가 난다~ - 또한 return 이라는 예약어를 사용하면 그 아래에 조건문등이 아닌이상 코드가 있으면 안된다. - `MemberDTO`를 사용하여 여러개를 넘겨 줄 경우도 생각해보자. > 자세한 사항은 p.230~p.234 참조 --- ### 7. static 메소드와 일반메소드의 차이 <file_sep>/README.md # persnal_study 그동안 공부해왔던 것들 혹은 공부 할것들 정리하는 저장소 <file_sep>/guide/개발 라이브러리 가이드/C#.NET/4.리스트 코드 상세분석.MD # C#.NET 라이브러리 ----------------- ##리스트 코드 상세분석 ----------------- ##### 파라미터 선언 ```css // 객체선언 SqlConnection con; SqlDataReader dr; // 파라미터 public int functionSeq; // 기능순번 // 페이징 public int totalCount = 0; // 총 카운트 public int p; // 현재 페이지 public int startNum; // 페이지 시작 public int endNum; // 페이지 끝 public int articleNum; // 글 번호 public string pageTail; // 페이지 꼬리 public string paging; // 페이징 ``` ----------------- <file_sep>/java/god_of_java/Vol.2/08. 그 다음으로 많이 쓰는 애들은 자바 유틸/src/RandomSample.java import java.util.Random; public class RandomSample { public static void main(String[] args) { RandomSample sample=new RandomSample(); int randomCount=10; sample.generateRandomNumbers(randomCount); } public void generateRandomNumbers(int randomCount){ Random random=new Random(); for (int loop = 0; loop < randomCount; loop++) { System.out.print(random.nextInt(100)+","); } } public void parseStringWithSplit(String data){ String[] splitString=data.split("\\s"); for (String tempData : splitString) { System.out.println("["+tempData+"]"); } } } <file_sep>/java/god_of_java/Vol.1/README.md ## VOL.1 기초 문법편
23fe65bebb8207cf8cab219c53d310ad56dd76b6
[ "SQL", "HTML", "Markdown", "JavaScript", "INI", "Java", "Python", "C" ]
158
C
rampas90/persnal_study
72e85e493cc0972dc237039eaef4353644400e7b
6eb148c78d7bbf7687976bdc7d56f7317cd7896a
refs/heads/main
<repo_name>guanzhuyang/my-leetcode<file_sep>/src/com/yang/LeetCode897.java package com.yang; import java.util.ArrayList; import java.util.List; /** * @description: * * 897. 递增顺序搜索树 * * 给你一棵二叉搜索树,请你 按中序遍历 将其重新排列为一棵递增顺序搜索树,使树中最左边的节点成为树的根节点,并且每个节点没有左子节点,只有一个右子节点。 * *   * * 示例 1: * * * 输入:root = [5,3,6,2,4,null,8,1,null,null,null,7,9] * 输出:[1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9] * 示例 2: * * * 输入:root = [5,1,7] * 输出:[1,null,5,null,7] *   * * 提示: * * 树中节点数的取值范围是 [1, 100] * 0 <= Node.val <= 1000 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/increasing-order-search-tree * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * * * @author: yang * @time:2021 2021-4-25 09:37 */ public class LeetCode897 { public TreeNode increasingBST(TreeNode root) { if(root == null){ return root; } List<Integer> list = new ArrayList<>(); increasing(root , list); if(list.size() == 0){ return root; } TreeNode head = new TreeNode(list.get(0)); TreeNode p = head; for (int i = 1 ; i < list.size() ; i++) { p.right = new TreeNode(list.get(i)); p = p.right; } return head; } private void increasing(TreeNode root , List<Integer> list){ if(root == null){ return; } increasing(root.left , list); list.add(root.val); increasing(root.right , list); } } <file_sep>/src/com/yang/LeetCode872.java package com.yang; import java.util.Deque; import java.util.LinkedList; /** * @description: * * 872. 叶子相似的树 * * 请考虑一棵二叉树上所有的叶子,这些叶子的值按从左到右的顺序排列形成一个 叶值序列 。 * * * * 举个例子,如上图所示,给定一棵叶值序列为 (6, 7, 4, 9, 8) 的树。 * * 如果有两棵二叉树的叶值序列是相同,那么我们就认为它们是 叶相似 的。 * * 如果给定的两个根结点分别为 root1 和 root2 的树是叶相似的,则返回 true;否则返回 false 。 * *   * * 示例 1: * * * * 输入:root1 = [3,5,1,6,2,9,8,null,null,7,4], root2 = [3,5,1,6,7,4,2,null,null,null,null,null,null,9,8] * 输出:true * 示例 2: * * 输入:root1 = [1], root2 = [1] * 输出:true * 示例 3: * * 输入:root1 = [1], root2 = [2] * 输出:false * 示例 4: * * 输入:root1 = [1,2], root2 = [2,2] * 输出:true * 示例 5: * * * * 输入:root1 = [1,2,3], root2 = [1,3,2] * 输出:false *   * * 提示: * * 给定的两棵树可能会有 1 到 200 个结点。 * 给定的两棵树上的值介于 0 到 200 之间。 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/leaf-similar-trees * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * @author: yang * @time:2021 2021-5-10 09:21 */ public class LeetCode872 { public boolean leafSimilar(TreeNode root1, TreeNode root2) { Deque<Integer> d1 = new LinkedList<>() , d2 = new LinkedList<>(); dfs(root1 , d1); dfs(root2 , d2); if(d1.size() != d2.size()){ return false; } while (!d1.isEmpty()){ if(!d1.poll().equals(d2.poll()) ){ return false; } } return true; } private void dfs(TreeNode root , Deque<Integer> d){ if(root == null){ return; } dfs(root.left , d); dfs(root.right , d); if(root.left == null && root.right == null){ d.push(root.val); } } } <file_sep>/src/com/yang/LeetCode938.java package com.yang; /** * @description: * * 938. 二叉搜索树的范围和 * * 给定二叉搜索树的根结点 root,返回值位于范围 [low, high] 之间的所有结点的值的和。 * *   * * 示例 1: * * * 输入:root = [10,5,15,3,7,null,18], low = 7, high = 15 * 输出:32 * 示例 2: * * * 输入:root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10 * 输出:23 *   * * 提示: * * 树中节点数目在范围 [1, 2 * 104] 内 * 1 <= Node.val <= 105 * 1 <= low <= high <= 105 * 所有 Node.val 互不相同 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/range-sum-of-bst * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * * @author: yang * @time:2021 2021-4-27 10:23 */ public class LeetCode938 { int sum = 0; public int rangeSumBST(TreeNode root, int low, int high) { rangeSum(root, low, high); return sum; } private void rangeSum(TreeNode root, int low, int high){ if(root == null){ return; } if(high < root.val){ rangeSum(root.left , low , high); return; } if(low > root.val){ rangeSum(root.right , low , high); return; } if(low <= root.val && high >= root.val){ sum += root.val; rangeSum(root.left , low , root.val-1); rangeSum(root.right , root.val+1 , high); } } } <file_sep>/src/com/yang/LeetCode191.java package com.yang; /** * @description: * * 191. 位1的个数 * * 编写一个函数,输入是一个无符号整数(以二进制串的形式),返回其二进制表达式中数字位数为 '1' 的个数(也被称为汉明重量)。 * *   * * 提示: * * 请注意,在某些语言(如 Java)中,没有无符号整数类型。在这种情况下,输入和输出都将被指定为有符号整数类型,并且不应影响您的实现,因为无论整数是有符号的还是无符号的,其内部的二进制表示形式都是相同的。 * 在 Java 中,编译器使用二进制补码记法来表示有符号整数。因此,在上面的 示例 3 中,输入表示有符号整数 -3。 *   * * 示例 1: * * 输入:00000000000000000000000000001011 * 输出:3 * 解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '1'。 * 示例 2: * * 输入:00000000000000000000000010000000 * 输出:1 * 解释:输入的二进制串 00000000000000000000000010000000 中,共有一位为 '1'。 * 示例 3: * * 输入:11111111111111111111111111111101 * 输出:31 * 解释:输入的二进制串 11111111111111111111111111111101 中,共有 31 位为 '1'。 *   * * 提示: * * 输入必须是长度为 32 的 二进制串 。 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/number-of-1-bits * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * * @author: yang * @time:2021 2021-3-22 10:26 */ public class LeetCode191 { public static int hammingWeight(int n) { int t = n; int i = 0; while (t != 0){ i+= (t & 1); t = t >>> 1; } return i; } } <file_sep>/src/com/yang/LeetCode17.java package com.yang; import java.util.ArrayList; import java.util.List; /** * @description: * * 给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。 * * 给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。 * * * *   * * 示例 1: * * 输入:digits = "23" * 输出:["ad","ae","af","bd","be","bf","cd","ce","cf"] * 示例 2: * * 输入:digits = "" * 输出:[] * 示例 3: * * 输入:digits = "2" * 输出:["a","b","c"] *   * * 提示: * * 0 <= digits.length <= 4 * digits[i] 是范围 ['2', '9'] 的一个数字。 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * * * @author: yang * @time:2021 2021-6-3 14:59 */ public class LeetCode17 { char[][] CACHE = new char[][]{{'a','b','c'} , {'d','e','f'} , {'g','h','i'} , {'j','k','l'} , {'m','n','o'} , {'p','q','r' , 's'} , {'t','u','v'} , {'w','x','y','z'}}; public List<String> letterCombinations(String digits) { List<String> ans = new ArrayList<>(); if(digits == null || digits.length() == 0){ return ans; } char[] cs = digits.toCharArray(); ans.add(""); for (int i = cs.length - 1 ; i >= 0 ; i--) { List<String> cache = new ArrayList<>(); char[] c = CACHE[cs[i] - '2']; for (String an : ans) { for (char s : c) { cache.add(s + an); } } ans = cache; } return ans; } } <file_sep>/src/com/yang/LeetCode1029.java package com.yang; import java.util.Arrays; /** * @description: * * 1029. 两地调度 * * 公司计划面试 2N 人。第 i 人飞往 A 市的费用为 costs[i][0],飞往 B 市的费用为 costs[i][1]。 * * 返回将每个人都飞到某座城市的最低费用,要求每个城市都有 N 人抵达。 * *   * * 示例: * * 输入:[[10,20],[30,200],[400,50],[30,20]] * 输出:110 * 解释: * 第一个人去 A 市,费用为 10。 * 第二个人去 A 市,费用为 30。 * 第三个人去 B 市,费用为 50。 * 第四个人去 B 市,费用为 20。 * * 最低总费用为 10 + 30 + 50 + 20 = 110,每个城市都有一半的人在面试。 *   * * 提示: * * 1 <= costs.length <= 100 * costs.length 为偶数 * 1 <= costs[i][0], costs[i][1] <= 1000 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/two-city-scheduling * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * * * @author: yang * @time:2021 2021-4-24 17:52 */ public class LeetCode1029 { public int twoCitySchedCost(int[][] costs) { Arrays.sort(costs , (a,b) -> a[0] - a[1] - (b[0] - b[1])); int n = costs.length >> 1; int sum = 0; for (int i = 0 ; i < n ; i++) { sum+=costs[i][0]; } for (int i = n ; i < costs.length ; i++) { sum+=costs[i][1]; } return sum; } } <file_sep>/src/com/yang/LeetCode1589.java package com.yang; import java.util.Arrays; /** * @description: * * 1589. 所有排列中的最大和 * * * 有一个整数数组 nums ,和一个查询数组 requests ,其中 requests[i] = [starti, endi] 。第 i 个查询求 nums[starti] + nums[starti + 1] + ... + nums[endi - 1] + nums[endi] 的结果 ,starti 和 endi 数组索引都是 从 0 开始 的。 * * 你可以任意排列 nums 中的数字,请你返回所有查询结果之和的最大值。 * * 由于答案可能会很大,请你将它对 109 + 7 取余 后返回。 * *   * * 示例 1: * * 输入:nums = [1,2,3,4,5], requests = [[1,3],[0,1]] * 输出:19 * 解释:一个可行的 nums 排列为 [2,1,3,4,5],并有如下结果: * requests[0] -> nums[1] + nums[2] + nums[3] = 1 + 3 + 4 = 8 * requests[1] -> nums[0] + nums[1] = 2 + 1 = 3 * 总和为:8 + 3 = 11。 * 一个总和更大的排列为 [3,5,4,2,1],并有如下结果: * requests[0] -> nums[1] + nums[2] + nums[3] = 5 + 4 + 2 = 11 * requests[1] -> nums[0] + nums[1] = 3 + 5 = 8 * 总和为: 11 + 8 = 19,这个方案是所有排列中查询之和最大的结果。 * 示例 2: * * 输入:nums = [1,2,3,4,5,6], requests = [[0,1]] * 输出:11 * 解释:一个总和最大的排列为 [6,5,4,3,2,1] ,查询和为 [11]。 * 示例 3: * * 输入:nums = [1,2,3,4,5,10], requests = [[0,2],[1,3],[1,1]] * 输出:47 * 解释:一个和最大的排列为 [4,10,5,3,2,1] ,查询结果分别为 [19,18,10]。 *   * * 提示: * * n == nums.length * 1 <= n <= 105 * 0 <= nums[i] <= 105 * 1 <= requests.length <= 105 * requests[i].length == 2 * 0 <= starti <= endi < n * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/maximum-sum-obtained-of-any-permutation * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * @author: yang * @time:2021 2021-3-30 10:56 */ public class LeetCode1589 { public int maxSumRangeQuery(int[] nums, int[][] requests) { int a = 1000000007; int[] temp = new int[nums.length]; for (int[] request : requests) { for (int i = request[0] ; i <= request[1] ; i++) { temp[i]++; } } Arrays.sort(temp); Arrays.sort(nums); long r = 0; for (int i = temp.length - 1 ; i >= 0 ; i--) { r+=(long) temp[i]*nums[i]; } return (int) r%a; } } <file_sep>/src/com/yang/LeetCode1190.java package com.yang; import java.util.Deque; import java.util.LinkedList; /** * @description: * * 给出一个字符串 s(仅含有小写英文字母和括号)。 * * 请你按照从括号内到外的顺序,逐层反转每对匹配括号中的字符串,并返回最终的结果。 * * 注意,您的结果中 不应 包含任何括号。 * *   * * 示例 1: * * 输入:s = "(abcd)" * 输出:"dcba" * 示例 2: * * 输入:s = "(u(love)i)" * 输出:"iloveu" * 示例 3: * * 输入:s = "(ed(et(oc))el)" * 输出:"leetcode" * 示例 4: * * 输入:s = "a(bcdefghijkl(mno)p)q" * 输出:"apmnolkjihgfedcbq" *   * * 提示: * * 0 <= s.length <= 2000 * s 中只有小写英文字母和括号 * 我们确保所有括号都是成对出现的 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/reverse-substrings-between-each-pair-of-parentheses * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * * * @author: yang * @time:2021 2021-5-26 09:49 */ public class LeetCode1190 { public String reverseParentheses(String s) { Deque<Character> deque = new LinkedList<>(); StringBuilder builder = new StringBuilder(); for (char c : s.toCharArray()) { if(c == '('){ deque.push(c); }else if(c == ')'){ Character poll = deque.poll(); Deque<Character> d = new LinkedList<>(); while (poll != '('){ d.push(poll); poll = deque.poll(); } if(deque.isEmpty()){ while (!d.isEmpty()){ builder.append(d.pollLast()); } }else { while (!d.isEmpty()){ deque.push(d.pollLast()); } } }else { if(deque.isEmpty()){ builder.append(c); }else { deque.push(c); } } } while (!deque.isEmpty()){ builder.append(deque.poll()); } return builder.toString(); } public String reverseParentheses1(String s) { return null; } } <file_sep>/src/com/yang/LeetCode623.java package com.yang; import java.util.LinkedList; import java.util.Queue; /** * @description: * * 623. 在二叉树中增加一行 * * 给定一个二叉树,根节点为第1层,深度为 1。在其第 d 层追加一行值为 v 的节点。 * * 添加规则:给定一个深度值 d (正整数),针对深度为 d-1 层的每一非空节点 N,为 N 创建两个值为 v 的左子树和右子树。 * * 将 N 原先的左子树,连接为新节点 v 的左子树;将 N 原先的右子树,连接为新节点 v 的右子树。 * * 如果 d 的值为 1,深度 d - 1 不存在,则创建一个新的根节点 v,原先的整棵树将作为 v 的左子树。 * * 示例 1: * * 输入: * 二叉树如下所示: * 4 * / \ * 2 6 * / \ / * 3 1 5 * * v = 1 * * d = 2 * * 输出: * 4 * / \ * 1 1 * / \ * 2 6 * / \ / * 3 1 5 * * 示例 2: * * 输入: * 二叉树如下所示: * 4 * / * 2 * / \ * 3 1 * * v = 1 * * d = 3 * * 输出: * 4 * / * 2 * / \ * 1 1 * / \ * 3 1 * 注意: * * 输入的深度值 d 的范围是:[1,二叉树最大深度 + 1]。 * 输入的二叉树至少有一个节点。 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/add-one-row-to-tree * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * * @author: yang * @time:2021 2021-3-11 10:05 */ public class LeetCode623 { public static TreeNode addOneRow(TreeNode root, int v, int d) { Queue<TreeNode> queue = new LinkedList<>(); if(d == 1){ TreeNode node = new TreeNode(v); node.left = root; return node; } int index = 1; queue.add(root); while (!queue.isEmpty() && index < d - 1){ int size = queue.size(); for (int i = 0 ; i < size ; i++) { TreeNode poll = queue.poll(); if(poll.left != null){ queue.add(poll.left); } if(poll.right != null){ queue.add(poll.right); } } index++; } while (!queue.isEmpty()){ TreeNode poll = queue.poll(); TreeNode left = poll.left; TreeNode right = poll.right; poll.left = new TreeNode(v); poll.left.left = left; poll.right = new TreeNode(v); poll.right.right = right; } return root; } } <file_sep>/src/com/yang/LeetCode1710.java package com.yang; import java.util.Arrays; import java.util.Comparator; /** * @description: * 请你将一些箱子装在 一辆卡车 上。给你一个二维数组 boxTypes ,其中 boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi] : * * numberOfBoxesi 是类型 i 的箱子的数量。 * numberOfUnitsPerBoxi 是类型 i 每个箱子可以装载的单元数量。 * 整数 truckSize 表示卡车上可以装载 箱子 的 最大数量 。只要箱子数量不超过 truckSize ,你就可以选择任意箱子装到卡车上。 * * 返回卡车可以装载 单元 的 最大 总数。 * *   * * 示例 1: * * 输入:boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4 * 输出:8 * 解释:箱子的情况如下: * - 1 个第一类的箱子,里面含 3 个单元。 * - 2 个第二类的箱子,每个里面含 2 个单元。 * - 3 个第三类的箱子,每个里面含 1 个单元。 * 可以选择第一类和第二类的所有箱子,以及第三类的一个箱子。 * 单元总数 = (1 * 3) + (2 * 2) + (1 * 1) = 8 * 示例 2: * * 输入:boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10 * 输出:91 *   * * 提示: * * 1 <= boxTypes.length <= 1000 * 1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000 * 1 <= truckSize <= 106 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/maximum-units-on-a-truck * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * @author: yang * @time:2021 2021-3-5 14:24 */ public class LeetCode1710 { public int maximumUnits(int[][] boxTypes, int truckSize) { if(boxTypes == null || boxTypes.length == 0 || truckSize == 0){ return 0; } Arrays.sort(boxTypes , Comparator.comparingInt(a -> a[1])); int size = truckSize; int num = 0; for (int i = boxTypes.length - 1 ; i >= 0 ; i--) { if(size > boxTypes[i][0]){ num += boxTypes[i][0] * boxTypes[i][1]; size -= boxTypes[i][0]; }else { num += size * boxTypes[i][1]; break; } } return num; } } <file_sep>/src/com/yang/MapSum.java package com.yang; /** * @description: * * 实现一个 MapSum 类,支持两个方法,insert 和 sum: * * MapSum() 初始化 MapSum 对象 * void insert(String key, int val) 插入 key-val 键值对,字符串表示键 key ,整数表示值 val 。如果键 key 已经存在,那么原来的键值对将被替代成新的键值对。 * int sum(string prefix) 返回所有以该前缀 prefix 开头的键 key 的值的总和。 *   * * 示例: * * 输入: * ["MapSum", "insert", "sum", "insert", "sum"] * [[], ["apple", 3], ["ap"], ["app", 2], ["ap"]] * 输出: * [null, null, 3, null, 5] * * 解释: * MapSum mapSum = new MapSum(); * mapSum.insert("apple", 3); * mapSum.sum("ap"); // return 3 (apple = 3) * mapSum.insert("app", 2); * mapSum.sum("ap"); // return 5 (apple + app = 3 + 2 = 5) *   * * 提示: * * 1 <= key.length, prefix.length <= 50 * key 和 prefix 仅由小写英文字母组成 * 1 <= val <= 1000 * 最多调用 50 次 insert 和 sum * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/map-sum-pairs * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * * * @author: yang * @time:2021 2021-5-18 15:41 */ public class MapSum { Node node; /** Initialize your data structure here. */ public MapSum() { node = new Node(); } public void insert(String key, int val) { node.insert(key,val,0); } public int sum(String prefix) { return node.sum(prefix,0); } private class Node{ int n = 0; Node[] nodes = new Node[26]; public void insert(String key, int val , int index) { if(key.length() == index){ n=val; return; } int c = key.charAt(index) - 'a'; if(nodes[c] == null){ nodes[c] = new Node(); } nodes[c].insert(key, val, index+1); } public int sum(String prefix , int index) { if(prefix.length() == index){ return n; } int i = prefix.charAt(index) - 'a'; if (nodes[i] != null) { return nodes[i].sum(prefix, index+1); } return 0; } } } <file_sep>/src/com/yang/LeetCode1047.java package com.yang; import java.util.Arrays; import java.util.Deque; import java.util.LinkedList; /** * @description: * * 1047. 删除字符串中的所有相邻重复项 * * 给出由小写字母组成的字符串 S,重复项删除操作会选择两个相邻且相同的字母,并删除它们。 * * 在 S 上反复执行重复项删除操作,直到无法继续删除。 * * 在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。 * *   * * 示例: * * 输入:"abbaca" * 输出:"ca" * 解释: * 例如,在 "abbaca" 中,我们可以删除 "bb" 由于两字母相邻且相同,这是此时唯一可以执行删除操作的重复项。之后我们得到字符串 "aaca",其中又只有 "aa" 可以执行重复项删除操作,所以最后的字符串为 "ca"。 *   * * 提示: * * 1 <= S.length <= 20000 * S 仅由小写英文字母组成。 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/remove-all-adjacent-duplicates-in-string * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * * @author: yang * @time:2021 2021-3-9 13:49 */ public class LeetCode1047 { public static String removeDuplicates(String S) { if(S == null || S.length() < 2){ return S; } int len = S.length(); char[] cs = new char[len]; int p = 0; for (int i = 0 ; i < len ; i++) { char c = S.charAt(i); if(cs[p] == c){ cs[p] = 0; p--; }else { cs[++p] = c; } } return String.valueOf(cs , 0 , p+1); } } <file_sep>/src/com/yang/LeetCode1202.java package com.yang; import java.util.List; /** * @description: 给你一个字符串 s,以及该字符串中的一些「索引对」数组 pairs,其中 pairs[i] = [a, b] 表示字符串中的两个索引(编号从 0 开始)。 * <p>你可以 任意多次交换 在 pairs 中任意一对索引处的字符。 * <p>返回在经过若干次交换后,s 可以变成的按字典序最小的字符串。 * <p> * <p>示例 1: * <p>输入:s = "dcab", pairs = [[0,3],[1,2]] 输出:"bacd" 解释: 交换 s[0] 和 s[3], s = "bcad" 交换 s[1] 和 * s[2], s = "bacd" 示例 2: * <p>输入:s = "dcab", pairs = [[0,3],[1,2],[0,2]] 输出:"abcd" 解释: 交换 s[0] 和 s[3], s = "bcad" 交换 * s[0] 和 s[2], s = "acbd" 交换 s[1] 和 s[2], s = "abcd" 示例 3: * <p>输入:s = "cba", pairs = [[0,1],[1,2]] 输出:"abc" 解释: 交换 s[0] 和 s[1], s = "bca" 交换 s[1] 和 s[2], * s = "bac" 交换 s[0] 和 s[1], s = "abc" * <p>提示: * <p>1 <= s.length <= 10^5 0 <= pairs.length <= 10^5 0 <= pairs[i][0], pairs[i][1] < s.length * s 中只含有小写英文字母 * <p>来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/smallest-string-with-swaps * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * @author: yang * @time:2021 2021-1-11 19:58 */ public class LeetCode1202 { public String smallestStringWithSwaps(String s, List<List<Integer>> pairs) { return "0"; } } <file_sep>/src/com/yang/TreeNode.java package com.yang; /** * @description: * @author: yang * @time:2021 2021-3-11 10:04 */ public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } <file_sep>/src/com/yang/LeetCode92.java package com.yang; /** * @description: * * 92. 反转链表 II * * 给你单链表的头节点 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。 *   * * 示例 1: * * * 输入:head = [1,2,3,4,5], left = 2, right = 4 * 输出:[1,4,3,2,5] * 示例 2: * * 输入:head = [5], left = 1, right = 1 * 输出:[5] *   * * 提示: * * 链表中节点数目为 n * 1 <= n <= 500 * -500 <= Node.val <= 500 * 1 <= left <= right <= n *   * * 进阶: 你可以使用一趟扫描完成反转吗? * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/reverse-linked-list-ii * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * * * @author: yang * @time:2021 2021-3-18 11:19 */ public class LeetCode92 { public ListNode reverseBetween(ListNode head, int left, int right) { return head; } } <file_sep>/src/com/yang/LeetCode1622.java package com.yang; import java.util.List; /** * @description: * * 面试题 16.22. 兰顿蚂蚁 * * 一只蚂蚁坐在由白色和黑色方格构成的无限网格上。开始时,网格全白,蚂蚁面向右侧。每行走一步,蚂蚁执行以下操作。 * * (1) 如果在白色方格上,则翻转方格的颜色,向右(顺时针)转 90 度,并向前移动一个单位。 * (2) 如果在黑色方格上,则翻转方格的颜色,向左(逆时针方向)转 90 度,并向前移动一个单位。 * * 编写程序来模拟蚂蚁执行的前 K 个动作,并返回最终的网格。 * * 网格由数组表示,每个元素是一个字符串,代表网格中的一行,黑色方格由 'X' 表示,白色方格由 '_' 表示,蚂蚁所在的位置由 'L', 'U', 'R', 'D' 表示,分别表示蚂蚁 左、上、右、下 的朝向。只需要返回能够包含蚂蚁走过的所有方格的最小矩形。 * * 示例 1: * * 输入: 0 * 输出: ["R"] * 示例 2: * * 输入: 2 * 输出: * [ *   "_X", *   "LX" * ] * 示例 3: * * 输入: 5 * 输出: * [ *   "_U", *   "X_", *   "XX" * ] * 说明: * * K <= 100000 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/langtons-ant-lcci * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * @author: yang * @time:2021 2021-3-2 21:26 */ public class LeetCode1622 { public List<String> printKMoves(int K) { return null; } } <file_sep>/src/com/yang/LeetCode682.java package com.yang; import java.util.Deque; import java.util.LinkedList; /** * @description: * * 682. 棒球比赛 * * 你现在是一场采用特殊赛制棒球比赛的记录员。这场比赛由若干回合组成,过去几回合的得分可能会影响以后几回合的得分。 * * 比赛开始时,记录是空白的。你会得到一个记录操作的字符串列表 ops,其中 ops[i] 是你需要记录的第 i 项操作,ops 遵循下述规则: * * 整数 x - 表示本回合新获得分数 x * "+" - 表示本回合新获得的得分是前两次得分的总和。题目数据保证记录此操作时前面总是存在两个有效的分数。 * "D" - 表示本回合新获得的得分是前一次得分的两倍。题目数据保证记录此操作时前面总是存在一个有效的分数。 * "C" - 表示前一次得分无效,将其从记录中移除。题目数据保证记录此操作时前面总是存在一个有效的分数。 * 请你返回记录中所有得分的总和。 * *   * * 示例 1: * * 输入:ops = ["5","2","C","D","+"] * 输出:30 * 解释: * "5" - 记录加 5 ,记录现在是 [5] * "2" - 记录加 2 ,记录现在是 [5, 2] * "C" - 使前一次得分的记录无效并将其移除,记录现在是 [5]. * "D" - 记录加 2 * 5 = 10 ,记录现在是 [5, 10]. * "+" - 记录加 5 + 10 = 15 ,记录现在是 [5, 10, 15]. * 所有得分的总和 5 + 10 + 15 = 30 * 示例 2: * * 输入:ops = ["5","-2","4","C","D","9","+","+"] * 输出:27 * 解释: * "5" - 记录加 5 ,记录现在是 [5] * "-2" - 记录加 -2 ,记录现在是 [5, -2] * "4" - 记录加 4 ,记录现在是 [5, -2, 4] * "C" - 使前一次得分的记录无效并将其移除,记录现在是 [5, -2] * "D" - 记录加 2 * -2 = -4 ,记录现在是 [5, -2, -4] * "9" - 记录加 9 ,记录现在是 [5, -2, -4, 9] * "+" - 记录加 -4 + 9 = 5 ,记录现在是 [5, -2, -4, 9, 5] * "+" - 记录加 9 + 5 = 14 ,记录现在是 [5, -2, -4, 9, 5, 14] * 所有得分的总和 5 + -2 + -4 + 9 + 5 + 14 = 27 * 示例 3: * * 输入:ops = ["1"] * 输出:1 *   * * 提示: * * 1 <= ops.length <= 1000 * ops[i] 为 "C"、"D"、"+",或者一个表示整数的字符串。整数范围是 [-3 * 104, 3 * 104] * 对于 "+" 操作,题目数据保证记录此操作时前面总是存在两个有效的分数 * 对于 "C" 和 "D" 操作,题目数据保证记录此操作时前面总是存在一个有效的分数 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/baseball-game * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * * @author: yang * @time:2021 2021-4-22 15:25 */ public class LeetCode682 { public int calPoints(String[] ops) { Deque<Integer> deque = new LinkedList<>(); for (String op : ops) { if("C".equals(op)){ deque.poll(); }else if("D".equals(op)){ Integer poll = deque.peek(); int i = poll * 2; deque.push(i); }else if("+".equals(op)){ Integer f = deque.poll(); Integer s = deque.peek(); deque.push(f); deque.push(f+s); }else { deque.push(Integer.valueOf(op)); } } int n = deque.poll(); while (!deque.isEmpty()){ n+=deque.poll(); } return n; } } <file_sep>/src/com/yang/LeetCode91.java package com.yang; /** * @description: * * 91. 解码方法 * * * 一条包含字母 A-Z 的消息通过以下映射进行了 编码 : * * 'A' -> 1 * 'B' -> 2 * ... * 'Z' -> 26 * 要 解码 已编码的消息,所有数字必须基于上述映射的方法,反向映射回字母(可能有多种方法)。例如,"11106" 可以映射为: * * "AAJF" ,将消息分组为 (1 1 10 6) * "KJF" ,将消息分组为 (11 10 6) * 注意,消息不能分组为  (1 11 06) ,因为 "06" 不能映射为 "F" ,这是由于 "6" 和 "06" 在映射中并不等价。 * * 给你一个只含数字的 非空 字符串 s ,请计算并返回 解码 方法的 总数 。 * * 题目数据保证答案肯定是一个 32 位 的整数。 * *   * * 示例 1: * * 输入:s = "12" * 输出:2 * 解释:它可以解码为 "AB"(1 2)或者 "L"(12)。 * 示例 2: * * 输入:s = "226" * 输出:3 * 解释:它可以解码为 "BZ" (2 26), "VF" (22 6), 或者 "BBF" (2 2 6) 。 * 示例 3: * * 输入:s = "0" * 输出:0 * 解释:没有字符映射到以 0 开头的数字。 * 含有 0 的有效映射是 'J' -> "10" 和 'T'-> "20" 。 * 由于没有字符,因此没有有效的方法对此进行解码,因为所有数字都需要映射。 * 示例 4: * * 输入:s = "06" * 输出:0 * 解释:"06" 不能映射到 "F" ,因为字符串含有前导 0("6" 和 "06" 在映射中并不等价)。 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/decode-ways * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * * @author: yang * @time:2021 2021-4-21 14:05 */ public class LeetCode91 { public int numDecodings(String s) { if(s == null || s.length() == 0){ return 0; } int len = s.length(); char f = s.charAt(0); if(f == '0'){ return 0; } if(len == 1){ return 1; } int[] temp = new int[len]; temp[0] = 1; temp[1] = (s.charAt(1) == '0' ? 0 : 1) + (check(f , s.charAt(1)) ? 2 : 1); for (int i = 2 ; i < len ; i++) { temp[i] = (s.charAt(i) == '0' ? 0 : temp[i - 1]) + (check(s.charAt(i-1) , s.charAt(i)) ? temp[i - 2] : 0); } return temp[len - 1]; } private boolean check(char f , char s){ if(f == '1'){ return true; } if(f == '2' && s >= '0' && s <= '6'){ return true; } return false; } } <file_sep>/src/com/yang/LeetCode1178.java package com.yang; import java.util.*; /** * @description: * 1178. 猜字谜 * * 外国友人仿照中国字谜设计了一个英文版猜字谜小游戏,请你来猜猜看吧。 * * 字谜的迷面 puzzle 按字符串形式给出,如果一个单词 word 符合下面两个条件,那么它就可以算作谜底: * * 单词 word 中包含谜面 puzzle 的第一个字母。 * 单词 word 中的每一个字母都可以在谜面 puzzle 中找到。 * 例如,如果字谜的谜面是 "abcdefg",那么可以作为谜底的单词有 "faced", "cabbage", 和 "baggage";而 "beefed"(不含字母 "a")以及 "based"(其中的 "s" 没有出现在谜面中)。 * 返回一个答案数组 answer,数组中的每个元素 answer[i] 是在给出的单词列表 words 中可以作为字谜迷面 puzzles[i] 所对应的谜底的单词数目。 * *   * * 示例: * * 输入: * words = ["aaaa","asas","able","ability","actt","actor","access"], * puzzles = ["aboveyz","abrodyz","abslute","absoryz","actresz","gaswxyz"] * 输出:[1,1,3,2,4,0] * 解释: * 1 个单词可以作为 "aboveyz" 的谜底 : "aaaa" * 1 个单词可以作为 "abrodyz" 的谜底 : "aaaa" * 3 个单词可以作为 "abslute" 的谜底 : "aaaa", "asas", "able" * 2 个单词可以作为 "absoryz" 的谜底 : "aaaa", "asas" * 4 个单词可以作为 "actresz" 的谜底 : "aaaa", "asas", "actt", "access" * 没有单词可以作为 "gaswxyz" 的谜底,因为列表中的单词都不含字母 'g'。 *   * * 提示: * * 1 <= words.length <= 10^5 * 4 <= words[i].length <= 50 * 1 <= puzzles.length <= 10^4 * puzzles[i].length == 7 * words[i][j], puzzles[i][j] 都是小写英文字母。 * 每个 puzzles[i] 所包含的字符都不重复。 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/number-of-valid-words-for-each-puzzle * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * @author: yang * @time:2021 2021-2-26 15:13 */ public class LeetCode1178 { public static List<Integer> findNumOfValidWords(String[] words, String[] puzzles) { List<Set<Character>> list = new ArrayList<>(); List<Integer> answer = new ArrayList(puzzles.length); for (String puzzle : words) { list.add(toSet(puzzle)); } for (String puzzle : puzzles) { char c = puzzle.charAt(0); Set<Character> s = toSet(puzzle); int i = 0; for (Set<Character> set : list) { if(set.contains(c) && s.containsAll(set)){ i++; } } answer.add(i); } return answer; } static Set<Character> toSet(String word){ Set<Character> set = new HashSet<>(); for (char a : word.toCharArray()) { set.add(a); } return set; } } <file_sep>/src/com/yang/TimeMap.java package com.yang; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @description: * * 981. 基于时间的键值存储 * * 创建一个基于时间的键值存储类 TimeMap,它支持下面两个操作: * * 1. set(string key, string value, int timestamp) * * 存储键 key、值 value,以及给定的时间戳 timestamp。 * 2. get(string key, int timestamp) * * 返回先前调用 set(key, value, timestamp_prev) 所存储的值,其中 timestamp_prev <= timestamp。 * 如果有多个这样的值,则返回对应最大的  timestamp_prev 的那个值。 * 如果没有值,则返回空字符串("")。 *   * * 示例 1: * * 输入:inputs = ["TimeMap","set","get","get","set","get","get"], inputs = [[],["foo","bar",1],["foo",1],["foo",3],["foo","bar2",4],["foo",4],["foo",5]] * 输出:[null,null,"bar","bar",null,"bar2","bar2"] * 解释:  * TimeMap kv;   * kv.set("foo", "bar", 1); // 存储键 "foo" 和值 "bar" 以及时间戳 timestamp = 1   * kv.get("foo", 1); // 输出 "bar"   * kv.get("foo", 3); // 输出 "bar" 因为在时间戳 3 和时间戳 2 处没有对应 "foo" 的值,所以唯一的值位于时间戳 1 处(即 "bar")   * kv.set("foo", "bar2", 4);   * kv.get("foo", 4); // 输出 "bar2"   * kv.get("foo", 5); // 输出 "bar2"   * * 示例 2: * * 输入:inputs = ["TimeMap","set","set","get","get","get","get","get"], inputs = [[],["love","high",10],["love","low",20],["love",5],["love",10],["love",15],["love",20],["love",25]] * 输出:[null,null,null,"","high","high","low","low"] *   * * 提示: * * 所有的键/值字符串都是小写的。 * 所有的键/值字符串长度都在 [1, 100] 范围内。 * 所有 TimeMap.set 操作中的时间戳 timestamps 都是严格递增的。 * 1 <= timestamp <= 10^7 * TimeMap.set 和 TimeMap.get 函数在每个测试用例中将(组合)调用总计 120000 次。 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/time-based-key-value-store * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * * * @author: yang * @time:2021 2021-4-8 15:28 */ public class TimeMap { Map<String , List<Node>> temp; public static final String EMTRY = ""; /** Initialize your data structure here. */ public TimeMap() { temp = new HashMap<>(); } public void set(String key, String value, int timestamp) { List<Node> nodes = temp.get(key); if(nodes == null){ nodes = new ArrayList<>(); } nodes.add(new Node(timestamp, value)); temp.put(key , nodes); } public String get(String key, int timestamp) { List<Node> nodes = temp.get(key); if(nodes == null){ return EMTRY; } for (int i = nodes.size() - 1 ; i >= 0 ; i--) { Node node = nodes.get(i); if(timestamp >= node.timestamp){ return node.value; } } return EMTRY; } class Node{ int timestamp; String value; public Node(int timestamp, String value) { this.timestamp = timestamp; this.value = value; } } } <file_sep>/src/com/yang/LeetCode965.java package com.yang; /** * @description: * * 如果二叉树每个节点都具有相同的值,那么该二叉树就是单值二叉树。 * * 只有给定的树是单值二叉树时,才返回 true;否则返回 false。 * *   * * 示例 1: * * * * 输入:[1,1,1,1,1,null,1] * 输出:true * 示例 2: * * * * 输入:[2,2,2,5,2] * 输出:false *   * * 提示: * * 给定树的节点数范围是 [1, 100]。 * 每个节点的值都是整数,范围为 [0, 99] 。 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/univalued-binary-tree * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * * @author: yang * @time:2021 2021-4-24 11:27 */ public class LeetCode965 { public boolean isUnivalTree(TreeNode root) { return check(root , root.val); } private boolean check(TreeNode root , int val){ if(root == null){ return true; } if(root.val != val){ return false; } if(!check(root.left , val)){ return false; } if(!check(root.right , val)){ return false; } return true; } } <file_sep>/src/com/yang/LeetCode213.java package com.yang; /** * @description: * * 你是一个专业的小偷,计划偷窃沿街的房屋,每间房内都藏有一定的现金。这个地方所有的房屋都 围成一圈 ,这意味着第一个房屋和最后一个房屋是紧挨着的。同时,相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警 。 * * 给定一个代表每个房屋存放金额的非负整数数组,计算你 在不触动警报装置的情况下 ,能够偷窃到的最高金额。 * *   * * 示例 1: * * 输入:nums = [2,3,2] * 输出:3 * 解释:你不能先偷窃 1 号房屋(金额 = 2),然后偷窃 3 号房屋(金额 = 2), 因为他们是相邻的。 * 示例 2: * * 输入:nums = [1,2,3,1] * 输出:4 * 解释:你可以先偷窃 1 号房屋(金额 = 1),然后偷窃 3 号房屋(金额 = 3)。 *   偷窃到的最高金额 = 1 + 3 = 4 。 * 示例 3: * * 输入:nums = [0] * 输出:0 *   * * 提示: * * 1 <= nums.length <= 100 * 0 <= nums[i] <= 1000 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/house-robber-ii * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * * * @author: yang * @time:2021 2021-4-15 13:59 */ public class LeetCode213 { public int rob(int[] nums) { if(nums.length == 1){ return nums[0]; }else if(nums.length == 2){ return Math.max(nums[0] , nums[1]); } return Math.max(max(nums , 0 , nums.length - 2) , max(nums , 1 , nums.length - 1)); } public int max(int[] nums , int start , int end){ int f = nums[start]; int s = Math.max(f, nums[start+1]); for (int i = start + 2 ; i <= end ; i++) { int n = Math.max(s , f + nums[i]); f = s; s = n; } return s; } } <file_sep>/src/com/yang/LeetCode1222.java package com.yang; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @description: * * 1222. 可以攻击国王的皇后 * * * 在一个 8x8 的棋盘上,放置着若干「黑皇后」和一个「白国王」。 * * 「黑皇后」在棋盘上的位置分布用整数坐标数组 queens 表示,「白国王」的坐标用数组 king 表示。 * * 「黑皇后」的行棋规定是:横、直、斜都可以走,步数不受限制,但是,不能越子行棋。 * * 请你返回可以直接攻击到「白国王」的所有「黑皇后」的坐标(任意顺序)。 * *   * * 示例 1: * * * * 输入:queens = [[0,1],[1,0],[4,0],[0,4],[3,3],[2,4]], king = [0,0] * 输出:[[0,1],[1,0],[3,3]] * 解释: * [0,1] 的皇后可以攻击到国王,因为他们在同一行上。 * [1,0] 的皇后可以攻击到国王,因为他们在同一列上。 * [3,3] 的皇后可以攻击到国王,因为他们在同一条对角线上。 * [0,4] 的皇后无法攻击到国王,因为她被位于 [0,1] 的皇后挡住了。 * [4,0] 的皇后无法攻击到国王,因为她被位于 [1,0] 的皇后挡住了。 * [2,4] 的皇后无法攻击到国王,因为她和国王不在同一行/列/对角线上。 * 示例 2: * * * * 输入:queens = [[0,0],[1,1],[2,2],[3,4],[3,5],[4,4],[4,5]], king = [3,3] * 输出:[[2,2],[3,4],[4,4]] * 示例 3: * * * * 输入:queens = [[5,6],[7,7],[2,1],[0,7],[1,6],[5,1],[3,7],[0,3],[4,0],[1,2],[6,3],[5,0],[0,4],[2,2],[1,1],[6,4],[5,4],[0,0],[2,6],[4,5],[5,2],[1,4],[7,5],[2,3],[0,5],[4,2],[1,0],[2,7],[0,1],[4,6],[6,1],[0,6],[4,3],[1,7]], king = [3,4] * 输出:[[2,3],[1,4],[1,6],[3,7],[4,3],[5,4],[4,5]] *   * * 提示: * * 1 <= queens.length <= 63 * queens[i].length == 2 * 0 <= queens[i][j] < 8 * king.length == 2 * 0 <= king[0], king[1] < 8 * 一个棋盘格上最多只能放置一枚棋子。 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/queens-that-can-attack-the-king * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * * @author: yang * @time:2021 2021-5-7 09:33 */ public class LeetCode1222 { public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) { int l = king[0] - king[1]; int r = king[0] + king[1]; int[][] rlt = new int[8][2]; int [] a = {-1 , -1}; Arrays.fill(rlt , a); for (int[] queen : queens) { if(queen[0] == king[0]){ if(queen[1] > king[1]){ if(rlt[3][0] == -1){ rlt[3] = queen; }else { if(queen[1] < rlt[3][1]){ rlt[3] = queen; } } }else { if(rlt[7][0] == -1){ rlt[7] = queen; }else { if(queen[1] > rlt[7][1]){ rlt[7] = queen; } } } continue; } if(queen[1] == king[1]){ if(queen[0] > king[0]){ if(rlt[5][0] == -1){ rlt[5] = queen; }else { if(queen[0] < rlt[5][0]){ rlt[5] = queen; } } }else { if(rlt[1] == null){ rlt[1] = queen; }else { if(queen[0] > rlt[1][0]){ rlt[1] = queen; } } } continue; } if(queen[0] - queen[1] == l){ if(queen[1] > king[1]){ if(rlt[4][0] == -1){ rlt[4] = queen; }else { if(queen[1] < rlt[4][1]){ rlt[4] = queen; } } }else { if(rlt[0][0] == -1){ rlt[0] = queen; }else { if(queen[1] > rlt[0][1]){ rlt[0] = queen; } } } continue; } if(queen[0] + queen[1] == r){ if(queen[1] > king[1]){ if(rlt[6][0] == -1){ rlt[6] = queen; }else { if(queen[1] < rlt[6][1]){ rlt[6] = queen; } } }else { if(rlt[2][0] == -1){ rlt[2] = queen; }else { if(queen[1] > rlt[2][1]){ rlt[2] = queen; } } } } } List<List<Integer>> list = new ArrayList<>(); for (int[] t : rlt) { if(t[0] != -1){ List<Integer> o = new ArrayList<>(2); o.add(t[0]); o.add(t[1]); list.add(o); } } return list; } } <file_sep>/src/com/yang/LeetCode41.java package com.yang; import java.util.PriorityQueue; import java.util.Queue; /** * @description: * * 41. 数据流中的中位数 * * 如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。 * * 例如, * * [2,3,4] 的中位数是 3 * * [2,3] 的中位数是 (2 + 3) / 2 = 2.5 * * 设计一个支持以下两种操作的数据结构: * * void addNum(int num) - 从数据流中添加一个整数到数据结构中。 * double findMedian() - 返回目前所有元素的中位数。 * 示例 1: * * 输入: * ["MedianFinder","addNum","addNum","findMedian","addNum","findMedian"] * [[],[1],[2],[],[3],[]] * 输出:[null,null,null,1.50000,null,2.00000] * 示例 2: * * 输入: * ["MedianFinder","addNum","findMedian","addNum","findMedian"] * [[],[2],[],[3],[]] * 输出:[null,null,2.00000,null,2.50000] *   * * 限制: * * 最多会对 addNum、findMedian 进行 50000 次调用。 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/shu-ju-liu-zhong-de-zhong-wei-shu-lcof * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * * @author: yang * @time:2021 2021-3-2 14:55 */ public class LeetCode41 { Queue<Integer> big , small; /** initialize your data structure here. */ public LeetCode41() { big = new PriorityQueue<>(); small = new PriorityQueue<>((a , b) -> b-a); } public void addNum(int num) { //数量为偶数 , 放入大根堆 if(big.size() == small.size()){ small.add(num); big.add(small.poll()); }else { big.add(num); small.add(big.poll()); } } public double findMedian() { if(big.size() == small.size()){ return ((double)(big.peek() + small.peek()) ) / 2; }else { return big.peek(); } } }<file_sep>/src/com/yang/LeetCode201.java package com.yang; /** * @description: * 给你两个整数 left 和 right ,表示区间 [left, right] ,返回此区间内所有数字 按位与 的结果(包含 left 、right 端点)。 * *   * * 示例 1: * * 输入:left = 5, right = 7 * 输出:4 * 示例 2: * * 输入:left = 0, right = 0 * 输出:0 * 示例 3: * * 输入:left = 1, right = 2147483647 * 输出:0 *   * * 提示: * * 0 <= left <= right <= 231 - 1 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/bitwise-and-of-numbers-range * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * * @author: yang * @time:2021 2021-5-21 15:17 */ public class LeetCode201 { public int rangeBitwiseAnd(int left, int right) { int s = right; for (int i = left ; i < right ; i++) { s = s & i; if(s == 0){ return s; } } return s; } public int rangeBitwiseAnd1(int left, int right) { while (left < right){ right = right & (right - 1); } return right; } } <file_sep>/src/com/yang/LeetCode1734.java package com.yang; /** * @description: * * 给你一个整数数组 perm ,它是前 n 个正整数的排列,且 n 是个 奇数 。 * * 它被加密成另一个长度为 n - 1 的整数数组 encoded ,满足 encoded[i] = perm[i] XOR perm[i + 1] 。比方说,如果 perm = [1,3,2] ,那么 encoded = [2,1] 。 * * 给你 encoded 数组,请你返回原始数组 perm 。题目保证答案存在且唯一。 * *   * * 示例 1: * * 输入:encoded = [3,1] * 输出:[1,2,3] * 解释:如果 perm = [1,2,3] ,那么 encoded = [1 XOR 2,2 XOR 3] = [3,1] * 示例 2: * * 输入:encoded = [6,5,4,6] * 输出:[2,4,1,5,3] *   * * 提示: * * 3 <= n < 105 * n 是奇数。 * encoded.length == n - 1 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/decode-xored-permutation * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * @author: yang * @time:2021 2021-5-11 10:55 */ public class LeetCode1734 { public int[] decode(int[] encoded) { int n = encoded.length + 1; int total = 1; for (int i = 2 ; i <= n ; i++) { total ^= i; } int odd = encoded[1]; for (int i = 3 ; i < encoded.length ; i+=2) { odd ^= encoded[i]; } int[] p = new int[n]; p[0] = total ^ odd; for (int i = 0 ; i < encoded.length ; i++) { p[i+1] = encoded[i] ^ p[i]; } return p; } } <file_sep>/src/com/yang/LeetCode82.java package com.yang; /** * @description: * 存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除链表中所有存在数字重复情况的节点,只保留原始链表中 没有重复出现 的数字。 * * 返回同样按升序排列的结果链表。 * *   * * 示例 1: * * * 输入:head = [1,2,3,3,4,4,5] * 输出:[1,2,5] * 示例 2: * * * 输入:head = [1,1,1,2,3] * 输出:[2,3] *   * * 提示: * * 链表中节点数目在范围 [0, 300] 内 * -100 <= Node.val <= 100 * 题目数据保证链表已经按升序排列 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * @author: yang * @time:2021 2021-3-25 09:55 */ public class LeetCode82 { public ListNode deleteDuplicates(ListNode head) { if(head == null || head.next == null){ return head; } ListNode nh = new ListNode(0); nh.next = head; ListNode n = nh; ListNode f = head; ListNode s = f.next; boolean flag = false; while (s != null){ //相同元素 if(f.val == s.val){ s = s.next; flag = true; }else { if(flag){ n.next = s; f = s; s = s.next; }else { n = n.next; f = f.next; s = s.next; } flag = false; } } if(flag){ n.next = null; } return nh.next; } } <file_sep>/src/com/yang/LeetCode16_19.java package com.yang; import java.util.ArrayList; import java.util.List; /** * @description: * * 面试题 16.19. 水域大小 * * * 你有一个用于表示一片土地的整数矩阵land,该矩阵中每个点的值代表对应地点的海拔高度。若值为0则表示水域。由垂直、水平或对角连接的水域为池塘。池塘的大小是指相连接的水域的个数。编写一个方法来计算矩阵中所有池塘的大小,返回值需要从小到大排序。 * * 示例: * * 输入: * [ * [0,2,1,0], * [0,1,0,1], * [1,1,0,1], * [0,1,0,1] * ] * 输出: [1,2,4] * 提示: * * 0 < len(land) <= 1000 * 0 < len(land[i]) <= 1000 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/pond-sizes-lcci * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * * @author: yang * @time:2021 2021-4-12 19:23 */ public class LeetCode16_19 { public static int[] pondSizes(int[][] land) { List<Integer> list = new ArrayList<>(); for (int i = 0 ; i < land.length ; i++) { int[] l = land[i]; for (int j = 0 ; j < l.length ; j++) { int n = find(i, j, land); if(n > 0){ list.add(n); } } } list.sort(Integer::compareTo); int[] a = new int[list.size()]; for (int i = 0 ; i < list.size() ; i++) { a[i] = list.get(i); } return a; } public static int find(int x , int y , int[][] land){ if(x < 0 || x == land.length){ return 0; } if(y < 0 || y == land[x].length){ return 0; } if(land[x][y] == 0){ int n = 1; land[x][y] = -1; n = n + find(x+1 , y , land) + find(x , y+1 , land) + find(x+1 , y+1 , land) + find(x , y-1 , land) + find(x+1 , y-1 , land) + find(x-1 , y-1 , land) + find(x-1 , y , land) + find(x-1 , y+1 , land); return n; }else { return 0; } } } <file_sep>/src/com/yang/LeetCode168.java package com.yang; /** * @description: * * 给定一个正整数,返回它在 Excel 表中相对应的列名称。 * * 例如, * * 1 -> A * 2 -> B * 3 -> C * ... * 26 -> Z * 27 -> AA * 28 -> AB * ... * 示例 1: * * 输入: 1 * 输出: "A" * 示例 2: * * 输入: 28 * 输出: "AB" * 示例 3: * * 输入: 701 * 输出: "ZY" * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/excel-sheet-column-title * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * * * @author: yang * @time:2021 2021-6-7 16:31 */ public class LeetCode168 { public String convertToTitle(int columnNumber) { StringBuilder b = new StringBuilder(); int c = 0 , a = 0; while (true){ a = columnNumber / 26; c = columnNumber % 26; if(c == 0){ b.insert(0 , 'Z'); a --; }else { b.insert(0 , (char)(64+c)); } if(a == 0){ break; } columnNumber = a; } return b.toString(); } } <file_sep>/src/com/yang/LeetCode1333.java package com.yang; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; /** * @description: * * 1333. 餐厅过滤器 * * * 给你一个餐馆信息数组 restaurants,其中  restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]。你必须使用以下三个过滤器来过滤这些餐馆信息。 * * 其中素食者友好过滤器 veganFriendly 的值可以为 true 或者 false,如果为 true 就意味着你应该只包括 veganFriendlyi 为 true 的餐馆,为 false 则意味着可以包括任何餐馆。此外,我们还有最大价格 maxPrice 和最大距离 maxDistance 两个过滤器,它们分别考虑餐厅的价格因素和距离因素的最大值。 * * 过滤后返回餐馆的 id,按照 rating 从高到低排序。如果 rating 相同,那么按 id 从高到低排序。简单起见, veganFriendlyi 和 veganFriendly 为 true 时取值为 1,为 false 时,取值为 0 。 * *   * * 示例 1: * * 输入:restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 1, maxPrice = 50, maxDistance = 10 * 输出:[3,1,5] * 解释: * 这些餐馆为: * 餐馆 1 [id=1, rating=4, veganFriendly=1, price=40, distance=10] * 餐馆 2 [id=2, rating=8, veganFriendly=0, price=50, distance=5] * 餐馆 3 [id=3, rating=8, veganFriendly=1, price=30, distance=4] * 餐馆 4 [id=4, rating=10, veganFriendly=0, price=10, distance=3] * 餐馆 5 [id=5, rating=1, veganFriendly=1, price=15, distance=1] * 在按照 veganFriendly = 1, maxPrice = 50 和 maxDistance = 10 进行过滤后,我们得到了餐馆 3, 餐馆 1 和 餐馆 5(按评分从高到低排序)。 * 示例 2: * * 输入:restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 50, maxDistance = 10 * 输出:[4,3,2,1,5] * 解释:餐馆与示例 1 相同,但在 veganFriendly = 0 的过滤条件下,应该考虑所有餐馆。 * 示例 3: * * 输入:restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 30, maxDistance = 3 * 输出:[4,5] *   * * 提示: * * 1 <= restaurants.length <= 10^4 * restaurants[i].length == 5 * 1 <= idi, ratingi, pricei, distancei <= 10^5 * 1 <= maxPrice, maxDistance <= 10^5 * veganFriendlyi 和 veganFriendly 的值为 0 或 1 。 * 所有 idi 各不相同。 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/filter-restaurants-by-vegan-friendly-price-and-distance * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * * * @author: yang * @time:2021 2021-4-29 16:16 */ public class LeetCode1333 { public List<Integer> filterRestaurants(int[][] restaurants, int veganFriendly, int maxPrice, int maxDistance) { List<int[]> list = new ArrayList<>(); for (int[] restaurant : restaurants) { if(restaurant[2] - veganFriendly > -1 && maxDistance >= restaurant[4] && maxPrice >= restaurant[3]){ list.add(restaurant); } } List<Integer> collect = list.stream().sorted((a, b) -> { int i = a[1] - b[1]; if (i == 0) { return a[0] - b[0]; } return i; }).map(a -> new Integer(a[0])).collect(Collectors.toList()); return collect; } } <file_sep>/src/com/yang/LeetCode179.java package com.yang; import java.util.Arrays; import java.util.Comparator; /** * @description: * * 179. 最大数 * * * 给定一组非负整数 nums,重新排列每个数的顺序(每个数不可拆分)使之组成一个最大的整数。 * * 注意:输出结果可能非常大,所以你需要返回一个字符串而不是整数。 * *   * * 示例 1: * * 输入:nums = [10,2] * 输出:"210" * 示例 2: * * 输入:nums = [3,30,34,5,9] * 输出:"9534330" * 示例 3: * * 输入:nums = [1] * 输出:"1" * 示例 4: * * 输入:nums = [10] * 输出:"10" *   * * 提示: * * 1 <= nums.length <= 100 * 0 <= nums[i] <= 109 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/largest-number * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * * @author: yang * @time:2021 2021-4-12 09:41 */ public class LeetCode179 { public static String largestNumber(int[] nums) { String[] temp = new String[nums.length]; for (int i = 0 ; i < nums.length ; i++) { temp[i] = String.valueOf(nums[i]); } Arrays.sort(temp, (a1 , a2) -> (a1+a2).compareTo(a2+a1) ); StringBuilder builder = new StringBuilder(); for (int i = temp.length - 1 ; i >= 0 ; i--) { builder.append(temp[i]); } String string = builder.toString(); if(string.startsWith("0")){ return "0"; } return string; } } <file_sep>/src/com/yang/LeetCode525.java package com.yang; import java.util.HashMap; import java.util.Map; /** * @description: * * 给定一个二进制数组 nums , 找到含有相同数量的 0 和 1 的最长连续子数组,并返回该子数组的长度。 * *   * * 示例 1: * * 输入: nums = [0,1] * 输出: 2 * 说明: [0, 1] 是具有相同数量0和1的最长连续子数组。 * 示例 2: * * 输入: nums = [0,1,0] * 输出: 2 * 说明: [0, 1] (或 [1, 0]) 是具有相同数量0和1的最长连续子数组。 *   * * 提示: * * 1 <= nums.length <= 105 * nums[i] 不是 0 就是 1 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/contiguous-array * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * * @author: yang * @time:2021 2021-6-3 10:55 */ public class LeetCode525 { public int findMaxLength(int[] nums) { if(nums.length == 1){ return 0; } Map<Integer , Integer> map = new HashMap<>(); map.put(0,-1); int max = 0 , total = 0; for (int i = 0 ; i < nums.length ; i++) { total = total + (nums[i] == 0 ? -1 : 1); Integer l = map.get(-total); if(l != null){ max = Math.max(max , i-l); }else { map.put(total , i); } } return max; } } <file_sep>/src/com/yang/LeetCode224.java package com.yang; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; /** * @description: * * 224. 基本计算器 * * 实现一个基本的计算器来计算一个简单的字符串表达式 s 的值。 * *   * * 示例 1: * * 输入:s = "1 + 1" * 输出:2 * 示例 2: * * 输入:s = " 2-1 + 2 " * 输出:3 * 示例 3: * * 输入:s = "(1+(4+5+2)-3)+(6+8)" * 输出:23 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/basic-calculator * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * * @author: yang * @time:2021 2021-3-10 10:02 */ public class LeetCode224 { public static int calculate(String s) { List<String> hz = toHz(s); return cal(hz); } public static List<String> toHz(String s){ LinkedList<Character> queue = new LinkedList<>(); List<String> hz = new ArrayList<>(); int len = s.length(); for (int i = 0 ; i < len ; i++) { char c = s.charAt(i); if(c == '('){ queue.add(c); }else if(c == '+' || c == '-'){ Character poll = queue.peekLast(); while (poll != null && (poll == '+' || poll == '-')){ hz.add(String.valueOf(queue.pollLast())); poll = queue.peekLast(); } queue.add(c); }else if(c == ')'){ Character poll = queue.pollLast(); while (poll != null && poll != '('){ hz.add(String.valueOf(poll)); poll = queue.pollLast(); } }else if (c == ' '){ } else { int j = i + 1; while (j < len && (s.charAt(j) >= '0' && s.charAt(j) <= '9')){ j++; } hz.add(s.substring(i , j)); i = j - 1; } } while (!queue.isEmpty()){ hz.add(String.valueOf(queue.poll())); } return hz; } public static int cal(List<String> hz){ LinkedList<Integer> queue = new LinkedList<>(); for (String s : hz) { if("+".equals(s)){ Integer a = queue.pollLast(); Integer b = queue.pollLast(); a = a == null ? 0 : a; b = b == null ? 0 : b; queue.add(a+b); }else if("-".equals(s)){ Integer a = queue.pollLast(); Integer b = queue.pollLast(); a = a == null ? 0 : a; b = b == null ? 0 : b; queue.add(b-a); }else { queue.add(Integer.valueOf(s)); } } return queue.pollLast(); } } <file_sep>/src/com/yang/LeetCode1269.java package com.yang; /** * @description: * * 1269. 停在原地的方案数 * * 有一个长度为 arrLen 的数组,开始有一个指针在索引 0 处。 * * 每一步操作中,你可以将指针向左或向右移动 1 步,或者停在原地(指针不能被移动到数组范围外)。 * * 给你两个整数 steps 和 arrLen ,请你计算并返回:在恰好执行 steps 次操作以后,指针仍然指向索引 0 处的方案数。 * * 由于答案可能会很大,请返回方案数 模 10^9 + 7 后的结果。 * *   * * 示例 1: * * 输入:steps = 3, arrLen = 2 * 输出:4 * 解释:3 步后,总共有 4 种不同的方法可以停在索引 0 处。 * 向右,向左,不动 * 不动,向右,向左 * 向右,不动,向左 * 不动,不动,不动 * 示例  2: * * 输入:steps = 2, arrLen = 4 * 输出:2 * 解释:2 步后,总共有 2 种不同的方法可以停在索引 0 处。 * 向右,向左 * 不动,不动 * 示例 3: * * 输入:steps = 4, arrLen = 2 * 输出:8 *   * * 提示: * * 1 <= steps <= 500 * 1 <= arrLen <= 10^6 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/number-of-ways-to-stay-in-the-same-place-after-some-steps * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * * @author: yang * @time:2021 2021-5-13 15:07 */ public class LeetCode1269 { public int numWays(int steps, int arrLen) { int mod = 1000000007; int n = Math.min(steps >> 1 , arrLen) + 1; int[][] dp = new int[steps+1][n]; dp[0][0] = 1; for (int i = 1 ; i < dp.length ; i++) { for (int j = 0 ; j < n && j < i; j++) { dp[i][j] = dp[i-1][j] ; if(j > 0){ dp[i][j] = (dp[i][j] + dp[i-1][j-1]) % mod; } if(j < n - 1){ dp[i][j] = (dp[i][j] + dp[i-1][j+1]) % mod; } } } return dp[steps][0]; } } <file_sep>/src/com/yang/LeetCode953.java package com.yang; /** * @description: * * 953. 验证外星语词典 * * 某种外星语也使用英文小写字母,但可能顺序 order 不同。字母表的顺序(order)是一些小写字母的排列。 * * 给定一组用外星语书写的单词 words,以及其字母表的顺序 order,只有当给定的单词在这种外星语中按字典序排列时,返回 true;否则,返回 false。 * *   * * 示例 1: * * 输入:words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz" * 输出:true * 解释:在该语言的字母表中,'h' 位于 'l' 之前,所以单词序列是按字典序排列的。 * 示例 2: * * 输入:words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz" * 输出:false * 解释:在该语言的字母表中,'d' 位于 'l' 之后,那么 words[0] > words[1],因此单词序列不是按字典序排列的。 * 示例 3: * * 输入:words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz" * 输出:false * 解释:当前三个字符 "app" 匹配时,第二个字符串相对短一些,然后根据词典编纂规则 "apple" > "app",因为 'l' > '∅',其中 '∅' 是空白字符,定义为比任何其他字符都小(更多信息)。 *   * * 提示: * * 1 <= words.length <= 100 * 1 <= words[i].length <= 20 * order.length == 26 * 在 words[i] 和 order 中的所有字符都是英文小写字母。 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/verifying-an-alien-dictionary * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * @author: yang * @time:2021 2021-3-2 16:36 */ public class LeetCode953 { int[] d = new int[26]; public boolean isAlienSorted(String[] words, String order) { for (int i = 0 ; i < order.length() ; i++) { d[order.charAt(i) - 'a'] = i; } for (int i = 1 ; i < words.length ; i++) { if(!compare(words[i - 1] , words[i])){ return false; } } return true; } private boolean compare(String w1 , String w2){ int min = Math.min(w1.length(), w2.length()); int i = 0; while (i < min && w1.charAt(i) == w2.charAt(i)){ i++; } if(i == min){ return w1.length() <= w2.length(); }else { return d[w1.charAt(i) - 'a'] < d[w2.charAt(i) - 'a']; } } } <file_sep>/src/com/yang/LeetCode1481.java package com.yang; import java.util.*; import java.util.stream.Collectors; /** * @description: * * 1481. 不同整数的最少数目 * * 给你一个整数数组 arr 和一个整数 k 。现需要从数组中恰好移除 k 个元素,请找出移除后数组中不同整数的最少数目。 * *   * * 示例 1: * * 输入:arr = [5,5,4], k = 1 * 输出:1 * 解释:移除 1 个 4 ,数组中只剩下 5 一种整数。 * 示例 2: * * 输入:arr = [4,3,1,1,3,3,2], k = 3 * 输出:2 * 解释:先移除 4、2 ,然后再移除两个 1 中的任意 1 个或者三个 3 中的任意 1 个,最后剩下 1 和 3 两种整数。 *   * * 提示: * * 1 <= arr.length <= 10^5 * 1 <= arr[i] <= 10^9 * 0 <= k <= arr.length * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/least-number-of-unique-integers-after-k-removals * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * * * @author: yang * @time:2021 2021-4-26 11:05 */ public class LeetCode1481 { public int findLeastNumOfUniqueInts(int[] arr, int k) { Map<Integer , Integer> map = new HashMap<>(arr.length); for (int i : arr) { Integer n = map.getOrDefault(i, 0); map.put(i , n+1); } List<Integer> collect = map.values().stream().sorted().collect(Collectors.toList()); int size = map.keySet().size(); int n = k; for (int i : collect) { if(n > i){ n -= i; size--; }else { break; } } return size; } }
f47038613c4f4c76918c4a2f87dfc4289ca15869
[ "Java" ]
36
Java
guanzhuyang/my-leetcode
3c891139a6d1a09571e4cdb5bdf80d8dcfe5cb07
922becbb41962a8500a2638a1377d2443db985ca
refs/heads/master
<file_sep>--CREATE DATABASE BankOfTomorrow CREATE TABLE Employees ( Employee_ID NUMBER(15) NOT NULL, FirstName VARCHAR(255) NOT NULL, LastName VARCHAR(255) NOT NULL, JobTitle VARCHAR(255) NOT NULL, Fullname VARCHAR(255), Salary DECIMAL NOT NULL, Address VARCHAR(255) NOT NULL, Manager_ID NUMBER(15), Department_ID NUMBER(15), CONSTRAINT Employee_PK PRIMARY KEY(Employee_ID), CONSTRAINT Department_FK FOREIGN KEY(Department_ID) REFERENCES Departments(Department_ID) ON DELETE SET NULL, CONSTRAINT Manager_FK FOREIGN KEY(Manager_ID) REFERENCES Employees (Employee_id) ON DELETE SET NULL ); CREATE TABLE Clients ( Client_ID NUMBER(15) NOT NULL, FirstName VARCHAR(255) NOT NULL, LastName VARCHAR(255) NOT NULL, LastLog DATE NOT NULL, Client_Password VARCHAR(15) NOT NULL, CONSTRAINT Clients_PK PRIMARY KEY(Client_ID) ); CREATE TABLE Departments ( Department_ID NUMBER(15) NOT NULL, DepartmentName VARCHAR(255) NOT NULL, Town_ID NUMBER(15) NOT NULL, CONSTRAINT Department_PK PRIMARY KEY(Department_ID), CONSTRAINT Town_FK FOREIGN KEY(Town_ID) REFERENCES Towns(Town_ID) ON DELETE SET NULL ); CREATE TABLE Towns ( Town_ID NUMBER(15) NOT NULL, TownName VARCHAR(255) NOT NULL, CONSTRAINT Town_PK PRIMARY KEY(Town_ID) ); --? Find information about all departments names: SELECT DepartmentName FROM Departments; --? Find the salary of each employee SELECT FirstName, LastName, Salary FROM Employees; --? Find the full name of each employee SELECT FirstName, LastName FROM Employees; --? Create a query that produces an employ email address by using the employee first and last name. --The user E-mail consists of first name and last name concatenated by a full stop. --The domain of the E-mail is fakecompany.com. --The result must be produced in a separate column named Full name SELECT CONCAT(CONCAT(CONCAT(FirstName, '.'), LastName), '@fakecompany.com') AS FullName FROM Employees; --? Find all employ with job title Senior executive SELECT * FROM Employees WHERE JobTitle = 'Senior executive' ORDER BY Employee_ID; --? Find all employs with name starts with letter S SELECT * FROM Employees WHERE FirstName LIKE 'S%' ORDER BY Employee_ID; --? Find all employees with a name that contains the letter l SELECT FirstName, LastName FROM Employees WHERE CONCAT(FirstName, LastName) LIKE '%l%' ORDER BY Employee_ID; --? Find all employees that have a salary in the range 2000 – 3000 SELECT FirstName, LastName, Salary FROM Employees WHERE Salary BETWEEN 2000 AND 3000 ORDER BY Employee_ID; --? Find all employees that have salaries 2500 / 3000 / 3500 / 5000 SELECT FirstName, LastName, Salary FROM Employees WHERE (Salary = 2500) OR (Salary = 3000) OR (Salary = 3500) OR (Salary = 5000) ORDER BY Employee_ID; --? Find all employees that do not have a manager SELECT FirstName, LastName, Manager_ID FROM Employees WHERE Manager_ID IS NULL ORDER BY Employee_ID; --? Find all employees that have a senior position in the company and have a salary greater than 5000. --Order them in decreasing order and by alphabetical order by there first name SELECT * FROM Employees WHERE JobTitle LIKE '%Senior%' AND (Salary>5000) ORDER BY FirstName DESC; --? Find the top 5 best-paid employees SELECT * FROM Employees WHERE ROWNUM <= 5 ORDER BY Salary DESC; --? Find all employees and their addresses SELECT FirstName, LastName, Address FROM Employees; --? Find all employees and their manager --Self Join SELECT A.FirstName AS EmployeeFN, A.LastName AS EmployeeLN, B.FirstName AS ManagerFN, B.LastName AS ManagerLN FROM Employees A, Employees B WHERE A.Manager_ID = B.Employee_ID ORDER BY A.Employee_ID; --? Find all employees along with their manager and address SELECT A.FirstName AS EmployeeFN, A.LastName AS EmployeeLN, A.Address AS EmployeeAddress, B.FirstName AS ManagerFN, B.LastName AS ManagerLN, B.Address AS ManagerAddress FROM Employees A, Employees B WHERE A.Manager_ID = B.Employee_ID ORDER BY A.Employee_ID; --? Find all departments and all town names as a single list --Full Join SELECT D.DepartmentName AS Department, T.TownName AS Town FROM Departments D FULL JOIN Towns T ON D.Town_ID = T.Town_ID ORDER BY D.Town_ID; --? Find all of the employees and the manager for each of them along with the employees that do not have a manager --LEFT JOIN SELECT A.FirstName AS EmployeeFN, A.LastName AS EmployeeLN, B.FirstName AS ManagerFN, B.LastName AS ManagerLN FROM Employees A LEFT JOIN Employees B ON A.Manager_ID = B.Employee_ID ORDER BY A.Employee_ID; --? Find all employees from “Sales” and all from “Finance” who are hired between 1995 and 2005 SELECT E.FirstName, E.LastName, E.Hire_Date, D.DepartmentName FROM Employees E FULL JOIN Departments D ON E.Department_ID = D.Department_ID WHERE ((D.DepartmentName = 'Finance') OR (D.DepartmentName = 'Sales')) AND (EXTRACT(YEAR FROM E.Hire_Date) BETWEEN 1995 AND 2005 ) ORDER BY E.Employee_ID; --? Find the full name and salary of the employee that takes minimal salary in the company. SELECT FirstName, LastName, MIN(Salary) AS MinSalary FROM Employees WHERE ROWNUM = 1 GROUP BY FirstName, LastName; --? Find the names and the salary of the employees that have a salary that is up to 10% higher than the minimum salary for the company SELECT FirstName, LastName, Salary FROM Employees WHERE Salary > (SELECT MIN(Salary) FROM Employees) AND Salary <=((SELECT MIN(Salary) FROM Employees) + (SELECT MIN(Salary) FROM Employees)*0.1); --? Find the full name salary and the department of the employees that take the minimum salary in their department. SELECT D.Department_ID, D.DepartmentName, B.FirstName, B.LastName, MIN(E.Salary) AS MinSalary FROM Employees E JOIN Departments D ON E.Department_ID = D.Department_ID JOIN Employees B ON B.Salary = E.Salary GROUP BY D.Department_ID, D.DepartmentName, B.FirstName, B.LastName ORDER BY D.Department_ID; --? Find the average salary in all department list the department name and the average salary SELECT D.Department_ID, D.DepartmentName, AVG(Salary) AS AverageSalary FROM Employees E FULL JOIN Departments D ON E.Department_ID = D.Department_ID GROUP BY D.Department_ID, D.DepartmentName ORDER BY D.Department_ID; --? Find the number of employee in all the departments. List the department and the number of employees in it SELECT D.Department_ID, D.DepartmentName, COUNT(E. Employee_ID) AS NumberOfEmployee FROM Employees E FULL JOIN Departments D ON E.Department_ID = D.Department_ID GROUP BY D.Department_ID, D.DepartmentName ORDER BY D.Department_ID; --? Group all employee by the manager SELECT B.FirstName, B.LastName, COUNT(A.Employee_ID) FROM Employees A JOIN Employees B ON A.Manager_ID = B.Employee_ID GROUP BY B.FirstName, B.LastName; --? Find all employees whose names are exactly 5 characters SELECT FirstName, LastName FROM Employees WHERE LENGTH(FirstName) = 5; --? Create a view that shows all clients that have been in the system today CREATE VIEW LogToday AS SELECT C.FirstName, C.LastName, C.LastLog FROM Clients C WHERE C.LastLog = CURRENT_DATE; --? Change the passwords of all clients that are absent from the system since 10.03.2010 UPDATE Clients SET Client_Password = '<PASSWORD>' WHERE Clients.LastLog <= TO_DATE('10-MAR-2010', 'DD-MON-YYYY'); --? Delete all clients without password DELETE FROM Clients WHERE Client_Password IS NULL; --? Display the town with max employees SELECT T.TownName, COUNT(Employee_ID) AS EmployeeCount FROM Towns T FULL JOIN Departments D ON T.Town_ID = D.Town_ID FULL JOIN Employees E ON E.Department_ID = D.Department_ID GROUP BY T.TownName ORDER BY EmployeeCount DESC; --Create a transaction that deletes the information from the tables, drop all the tables and reroll the transaction at the end of the process DECLARE first_transaction BEGIN SAVEPOINT sp1; DELETE FROM Clients; DELETE FROM Departmnets; DELETE FROM Employees; DELETE FROM Towns; DROP TABLE Clients; DROP TABLE Departments; DROP TABLE Employees; DROP TABLE Towns; ROLLBACK TO sp1; END
a1e3e7886ca255c0d2ad2eeef120f92daaa6e790
[ "SQL" ]
1
SQL
mimz-skywalker/SynergyInternshipTask1_BankOfTomorrow
9bc63bc00058f8dfc544246f819fe780014a5787
14bc93c57d765fc2565c91ad93dc217b78b6dc94
refs/heads/master
<file_sep>import React, {Component} from 'react'; import {Grid, Cell} from 'react-mdl'; import Education from './education'; import Experience from './experience'; import Skills from './skills'; class Resume extends Component{ render(){ return( <div className="resume-background" /*style={{backgroundImage: "url(https://images.pexels.com/photos/988872/pexels-photo-988872.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940)"}}*/> <Grid> <Cell col ={4}> <div style={{ textAlign: 'center'}}> <img src="https://media.licdn.com/dms/image/C4D03AQEy6MT0yLHwFg/profile-displayphoto-shrink_200_200/0?e=1556150400&v=beta&t=s-_zy8xABP9jILYCPazpJuulU0OQay9aKn7eWPtTMGc" alt="avatar" style={{height: '400px'}} /> </div> <h2 style={{paddingTop: '1em'}}><NAME></h2> <h4 style={{color: 'gray'}}>Programmer</h4> <hr style={{borderTop: '3px solid #833fb2', width: '50%'}}></hr> <p>Aspiring game and web developer, proficient in multiple programming languages. Studied full stack web development at Academy Pittsburgh in Allentown, Pennsylvania. Quick learner, critical thinker, and problem solver constantly seeking to better my skills by working with a goal-oriented team. Seeking an entry-level position in web development, game development, software engineering, or quality assurance testing.</p> <hr style={{borderTop: '3px solid #833fb2', width: '50%'}}></hr> <h5>Address</h5> <p>511 Callendale Lane, Durham, NC 27703</p> <h5>Phone</h5> <p>412-926-6985</p> <h5>Email</h5> <p><EMAIL></p> <h5>Web</h5> <p>mywebsite.com</p> <hr style={{borderTop: '3px solid #833fb2', width: '50%'}}></hr> </Cell> <Cell className="resume-right-col" col ={8}> <h2>Education</h2> <Education startYear={2013} endYear={2017} schoolName="Ohio University" schoolDescription="" schoolDescription2="" schoolDescription3="" schoolDescription4= "" /> <Education startYear={2017} endYear={2018} schoolName="Academy Pittsburgh" schoolDescription="Collaborated with classmates on numerous projects through an agile approach" schoolDescription2="Worked with languages and frameworks such as, C#, Ruby, SQL, .NET, React, HTML, CSS, Javascript, Python, Git, TDD, Ruby on Rails, Angular.JS, MVC apps, and advanced algorithms" schoolDescription3="Started a few solo side projects, including a visual novel video game and a portfolio website" schoolDescription4= "Worked on the backend of an application which allowed users to be added into a database in order to remotely unlock the door of the Academy from their mobile device" /> <hr style={{borderTop: '3px solid #e22947'}}/> <h2>Experience</h2> <Experience startYear={2017} endYear={2018} jobName="Help Desk Analyst, American Eagle" jobDescription="Provided various forms of tech support to American Eagle stores across four countries, including idevice troubleshooting, password/account resets, wifi connectivity assistance, and hardware assembly" jobDescription2="Coordinated with a group of 20+ colleagues across various platforms to maintain constant communication with the team and accomplish the united goals" jobDescription3="Learned various skills ranging from increased familiarity with hardware (PC laptops/desktops, idevices etc.) to the use of numerous softwares (Jira ticketing system, airwatch, etc.)" jobDescription4="" /> <Experience startYear={2011} endYear={2017} jobName="Manager, <NAME>" jobDescription="Collaborated with a crew of up to 10 other employees" jobDescription2="Managed 3-4 employees during night shifts" jobDescription3="Provided timely customer service " jobDescription4="" /> <hr style={{borderTop: '3px solid #e22947'}}/> <h2>Skills</h2> <Skills skill="javascript" progress={60} /> <Skills skill="HTML/CSS" progress={80} /> <Skills skill="React" progress={55} /> <Skills skill="C#" progress={60} /> <Skills skill="Python" progress={60} /> <Skills skill="Unity" progress={75} /> </Cell> </Grid> </div> ) } } export default Resume;<file_sep>import React, {Component} from 'react'; class About extends Component{ render(){ return( <div className="aboutme-background" /*style={{backgroundImage: "url(https://images.pexels.com/photos/988872/pexels-photo-988872.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940)"}}*/> </div> ) } } export default About;
e1019ded7148d30fc3b6f615c442b48b16e503f7
[ "JavaScript" ]
2
JavaScript
ETSlagle/portfolio
f1801423fb71124c69357331d2ab18a199f48644
e2348658c5f9687f2dbb4094e59db2d967625705
refs/heads/master
<repo_name>family-group/grandpascan<file_sep>/src/components/PeersView.jsx import React from 'react'; // importing styles import './styles/TransactionsView.css'; // importing utils import Xhr from '../utils/Xhr'; // importing components import TableData from './TableData'; // importing columns import { peersViewData } from '../components-data/peersViewData'; class PeersView extends React.Component { constructor() { super(); this.peersViewContainerRef = this.peersViewContainerRef.bind(this); this.getPeersViewContainerWidth = this.getPeersViewContainerWidth.bind(this); this.getAllPeers = this.getAllPeers.bind(this); } componentDidMount() { this.getAllPeers(); } componentWillUnmount() { if(this.peerRequest) this.peerRequest.abort(); } getAllPeers() { this.peerRequest = new Xhr('peers'); this.props.getPeers(this.peerRequest); } peersViewContainerRef(el) { if (el) this.TransactionsViewContainerRef = el; } getPeersViewContainerWidth() { if (this.TransactionsViewContainerRef) { return parseInt(getComputedStyle(this.TransactionsViewContainerRef).width); } } render() { console.log('PeersView') const { ids, isLoading, error, isEmpty } = this.props; return ( <main className="full-width"> <div ref={this.peersViewContainerRef} className="transactions-view-container"> <h2 className="">Peers</h2> { ids && (<p>{ids.length} Peers found.</p>) } <TableData errorMessage={this.props.isEmpty ? 'No peers connected at this moment.' : this.props.error} data={ids} columns={peersViewData} className={isLoading || error ? 'transactions-list-container flex-axis-centered spacer-lg' : 'transactions-list-container flex-column'} tableContainerWidth={this.getPeersViewContainerWidth} isLoading={isLoading} error={error} isEmpty={isEmpty} retryFunction={this.getAllPeers} > </TableData> </div> </main> ); } } export default PeersView;<file_sep>/src/components/AddressTransactionsView.jsx import React from 'react'; // importing styles import './styles/TransactionsView.css'; // importing utils import Xhr from '../utils/Xhr'; // importing components import TableData from './TableData'; // importing columns import { transactionsViewData } from '../components-data/transactionsViewData'; import { toGrandpaCoin, cleanHexNotation } from '../utils/granpaCoinFunctions';; class AddressTransactionsView extends React.Component { constructor() { super(); this.getTransactionsViewContainerRef = this.getTransactionsViewContainerRef.bind(this); this.getTransactionsViewContainerWidth = this.getTransactionsViewContainerWidth.bind(this); this.getAllAddressTransactions = this.getAllAddressTransactions.bind(this); this.goHome = this.goHome.bind(this); } componentDidMount() { this.getAllAddressTransactions(); } componentDidUpdate(prevProps) { if (prevProps.match.params.address !== this.props.match.params.address) { this.getAllAddressTransactions(); } } componentWillUnmount() { if(this.transactionsRequest) this.transactionsRequest.abort(); } getAllAddressTransactions() { const { address } = this.props.match.params; this.transactionsRequest = new Xhr(`address/${address.trim()}/transactions`); this.props.getAddressTransactions(this.transactionsRequest, cleanHexNotation(address)); } getTransactionsViewContainerRef(el) { if (el) this.transactionsViewContainerRef = el; } getTransactionsViewContainerWidth() { if (this.transactionsViewContainerRef) { return parseInt(getComputedStyle(this.transactionsViewContainerRef).width); } } goHome() { this.props.history.push('/'); } renderBalance() { const { addressBalance } = this.props; if (addressBalance) { return ( <React.Fragment> <p className="balance ellipsis">Confirmed Balance: {toGrandpaCoin(addressBalance.confirmedBalance)}</p> <p className="balance ellipsis">Pending Balance: {toGrandpaCoin(addressBalance.pendingBalance)}</p> <p className="balance ellipsis">Safe Balance: {toGrandpaCoin(addressBalance.safeBalance)}</p> </React.Fragment> ); } } render() { console.log('AddressTransactionsView') const { ids, isLoading, error, isEmpty } = this.props; return ( <main className="main-container flex-row"> <div ref={this.getTransactionsViewContainerRef} className="address-transactions-view-container"> <h2 className="ellipsis">Address: {this.props.match.params.address.trim()}</h2> {this.renderBalance()} <h3>Transactions</h3> { ids && (<p>{ids.length} Transactions found.</p>) } <TableData data={ids} columns={transactionsViewData} className={isLoading || error ? 'transactions-list-container flex-axis-centered spacer-lg' : 'transactions-list-container flex-column'} tableContainerWidth={this.getTransactionsViewContainerWidth} isLoading={isLoading} error={error} isEmpty={isEmpty} retryFunction={this.goHome} > </TableData> </div> </main> ); } } export default AddressTransactionsView;<file_sep>/src/containers/TransactionsViewContainer.jsx import { withRouter } from 'react-router'; import { connect } from 'react-redux'; // component import TransactionsView from '../components/TransactionsView'; // actions import { getTransactions } from '../redux/transactionActions'; export default withRouter( connect( (state, ownProps) => { return { ids: ownProps.location.pathname === '/transactions' ? state.transactionReducer.confirmedTransactionIds : state.transactionReducer.pendingTransactionIds, isLoading: state.transactionReducer.isLoading, isEmpty: state.transactionReducer[ownProps.location.pathname === '/transactions' ? 'areConfirmedEmpty' : 'arePendingEmpty'], error: state.transactionReducer.error }; }, {getTransactions} )(TransactionsView) );<file_sep>/src/components/DetailsBox.jsx import React from 'react'; import ShadowBox from './ShadowBox'; import Loader from './Loader'; import Error from './Error'; import { withRouter } from 'react-router-dom'; import { renderColumnAccordingLabel } from '../utils/granpaCoinFunctions'; import './styles/DetailsBox.css'; class DetailsBox extends React.Component { constructor() { super(); this.goHome = this.goHome.bind(this); this.renderColumnAccordingLabel = renderColumnAccordingLabel.bind(this); } renderRow(label, content) { return ( <div key={label} className="details-box-row flex-row"> <p className="details-box-content">{label}</p> <p className="details-box-content">{content}</p> </div> ); } renderBlockInfo() { if (this.props.isLoading) { return <Loader /> } if (this.props.data) { return Object.keys(this.props.rows).map(key => { return this.renderRow(this.props.rows[key].label, this.renderColumnAccordingLabel(this.props.rows, key)); }); } if (this.props.error) { return ( <Error errorMessage={this.props.error.message} retryFunction={this.goHome} className="error-padding-large" errorMessageClassName="spacer-lg" /> ); } } goHome() { this.props.history.push('/'); } render() { console.log('TransactionView') return ( <ShadowBox tag="section" className={this.props.isLoading || this.props.error ? 'block-info-container flex-column flex-axis-centered' : 'block-info-container flex-column'}> {this.renderBlockInfo()} </ShadowBox> ); } } export default withRouter(DetailsBox);<file_sep>/src/redux/blockReducer.js import { actions } from './blockActions'; import { payloadFormater } from '../utils/reduxFunctions'; const initialState = { isLoading: false, blockIds: [], data: {}, isEmpty: false, error: false }; function blockReducer(state = initialState, action = null) { let payload; switch (action.type) { case actions.GET_BLOCKS + '_START': return { ...state, isLoading: true, error: false }; case actions.GET_BLOCKS + '_SUCCESS': payload = payloadFormater(action.payload, 'blockHash'); return { ...state, isLoading: false, data: {...payload.data, ...state.data}, blockIds: payload.ids.reverse(), isEmpty: payload.ids.length === 0 }; case actions.GET_BLOCKS + '_ERROR': return { ...state, isLoading: false, error: action.payload }; case actions.GET_BLOCK_BY_HASH + '_START': return { ...state, isLoading: true, error: false }; case actions.GET_BLOCK_BY_HASH + '_SUCCESS': payload = payloadFormater(action.payload, 'blockHash') return { ...state, isLoading: false, data: {...payload.data, ...state.data}, blockIds: payload.ids }; case actions.GET_BLOCK_BY_HASH + '_ERROR': return { ...state, isLoading: false, error: action.payload }; case actions.ADD_NEW_BLOCK: payload = payloadFormater(action.block, 'blockHash'); return { ...state, blockIds: [...payload.ids.reverse(), ...state.blockIds], data: { ...state.data, ...payload.data } }; default: return state; } } export default blockReducer;<file_sep>/src/redux/transactionActions.js import { storeAddressBalance } from './balanceActions'; export const actions = { GET_TRANSACTIONS: 'GET_TRANSACTIONS', GET_TRANSACTION_BY_HASH: 'GET_TRANSACTION_BY_HASH', GET_ADDRESS_TRANSACTIONS: 'GET_ADDRESS_TRANSACTIONS', ADD_NEW_TRANSACTIONS: 'ADD_NEW_TRANSACTIONS', ADD_NEW_PENDING_TRANSACTION: 'ADD_NEW_PENDING_TRANSACTION' }; export function getTransactions(request, status = 'confirmed') { return { type: actions.GET_TRANSACTIONS, payload: request.result(), meta: {status} } } export function getTransactionByHash(request) { return { type: actions.GET_TRANSACTION_BY_HASH, payload: request.result() } } export function addNewTransactions(transactions) { return { type: actions.ADD_NEW_TRANSACTIONS, transactions }; } export function addNewPendingTransactions(transaction) { return { type: actions.ADD_NEW_PENDING_TRANSACTION, transaction }; } export function getAddressTransactions(request, address) { if (!address) return console.error(new Error('Second argument required.')); return dispatch => { return dispatch({ type: actions.GET_ADDRESS_TRANSACTIONS, payload: request.result().then(res => { dispatch(storeAddressBalance(address, res.balance)); return res; }), meta: {address} }) } }<file_sep>/src/redux/peerReducer.js import { actions } from './peerActions'; import { payloadFormater, storeGlobalPeers } from '../utils/reduxFunctions'; const initialState = { isLoading: false, peerIds: [], data: {}, isEmpty: false, error: false, nodeInfo: {}, isNodeInfoLoading: false, nodeInfoError: false }; function peerReducer(state = initialState, action = null) { let payload; switch (action.type) { case actions.GET_PEERS + '_START': return { ...state, isLoading: true, error: false, isEmpty: false }; case actions.GET_PEERS + '_SUCCESS': payload = payloadFormater(action.payload, 'nodeUrl', 'object'); storeGlobalPeers(state, payload); return { ...state, peerIds: payload.ids, data: {...payload.data, ...state.data}, isLoading: false, isEmpty: payload.ids.length === 0 }; case actions.GET_PEERS + '_ERROR': return { ...state, isLoading: false, error: true }; case actions.GET_NODE_INFO + '_START': return { ...state, isNodeInfoLoading: true, nodeInfoError: false }; case actions.GET_NODE_INFO + '_SUCCESS': return { ...state, nodeInfo: action.payload, isNodeInfoLoading: false }; case actions.GET_NODE_INFO + '_ERROR': return { ...state, isNodeInfoLoading: false, nodeInfoError: true }; case actions.ADD_NEW_NODE_INFO: return { ...state, nodeInfo: {...action.nodeInfo} }; case actions.ADD_NEW_PEER: payload = payloadFormater(action.peer, 'nodeUrl'); return { ...state, peerIds: [...payload.ids, ...state.peerIds], data: { ...state.data, ...payload.data } }; case actions.REMOVE_PEER: const peerIndex = state.peerIds.indexOf(action.nodeUrl); if (peerIndex > -1) { return { ...state, peerIds: [ ...state.peerIds.slice(0, peerIndex), ...state.peerIds.slice(peerIndex + 1) ] }; } return state; default: return state; } } export default peerReducer;<file_sep>/src/components/SearchInput.jsx import React from 'react'; // importing styles import './styles/SearchInput.css'; import searchIcon from '../assets/images/LUPA.svg' import { withRouter } from 'react-router-dom'; class SearchInput extends React.Component { constructor() { super(); this.setInitialInput = this.setInitialInput.bind(this); this.search = this.search.bind(this); this.onKeyPress = this.onKeyPress.bind(this); this.setFocus = this.setFocus.bind(this); this.setBlur = this.setBlur.bind(this); } componentDidMount() { document.addEventListener('keydown', this.onKeyPress); } componentWillUnmount() { document.removeEventListener('keydown', this.onKeyPress); } setInitialInput(target) { this.setTarget(target); } setTarget(target) { if (target) { this.target = target; } } search() { if (this.getInputValue() === '') return; if (this.isBlockHash()) { this.goTo(`/block/${this.getInputValue()}`) return; } if (this.isTransactionHash()) { this.goTo(`/transaction/${this.getInputValue()}`); return; } if (this.isAddress()) { this.goTo(`/address/${this.getInputValue()}/transactions`); return; } this.goTo(`/not-found/${this.getInputValue()}`); } goTo(endpoint) { this.props.history.push(endpoint); this.target.value = ''; } isTransactionHash() { return /^0x/.test(this.getInputValue()) && this.getInputValue().length === 66; } isBlockHash() { return !/^0x/.test(this.getInputValue()) && this.getInputValue().length === 64; } isAddress() { return this.getInputValue().replace(/^0x/, '').length === 40; } getInputValue() { return this.target.value.trim(); } onKeyPress(e) { if (e.keyCode === 13 && this.isOnFocus) { this.search(); } } setFocus() { this.isOnFocus = true; } setBlur() { this.isOnFocus = false; } render() { return ( <fieldset className="input-container"> <div className="full-width input-wrapper"> <img onClick={this.search} src={searchIcon} alt="search-icon" /> <input ref={this.setInitialInput} type="text" onFocus={this.setFocus} onBlur={this.setBlur} /> </div> </fieldset> ); } } export default withRouter(SearchInput); <file_sep>/src/redux/blockActions.js export const actions = { GET_BLOCKS: 'GET_BLOCKS', GET_BLOCK_BY_HASH: 'GET_BLOCK_BY_HASH', ADD_NEW_BLOCK: 'ADD_NEW_BLOCK' }; export function getBlocks(request) { return { type: actions.GET_BLOCKS, payload: request.result() } } export function getBlockByHash(request) { return { type: actions.GET_BLOCK_BY_HASH, payload: request.result() } } export function addNewBlocks(block) { return { type: actions.ADD_NEW_BLOCK, block }; }<file_sep>/src/components/Loader.jsx import React from 'react'; import './styles/Loader.css'; const Loader = (props) => { const Tag = props.tag || 'div'; const ChildTag = props.tag && props.tag === 'tr' ? 'td' : 'div'; return ( <Tag className="lds-ripple"><ChildTag></ChildTag><ChildTag></ChildTag></Tag> ); } export default Loader;<file_sep>/src/components/TableDataRow.jsx import React from 'react'; // importing styles import './styles/TableDataRow.css'; import { renderColumnAccordingLabel } from '../utils/granpaCoinFunctions'; class TableDataRow extends React.Component { constructor() { super(); this.renderColumnAccordingLabel = renderColumnAccordingLabel.bind(this); } renderColumns() { const { columns, columnsToRender } = this.props; if (columns) { return Object.keys(columns).slice(0, columnsToRender).map(key => { return ( <td key={key} className="transaction-td"> {this.renderColumnAccordingLabel(columns, key)} </td> ); }); } } render() { console.log('TableDataRow') return ( <tr className="transaction-row"> {this.renderColumns()} </tr> ); } } export default TableDataRow;<file_sep>/src/components/TransactionsView.jsx import React from 'react'; // importing styles import './styles/TransactionsView.css'; // importing utils import Xhr from '../utils/Xhr'; // importing components import TableData from './TableData'; // importing columns import { transactionsViewData } from '../components-data/transactionsViewData'; import Link from './Link'; class TransactionsView extends React.Component { constructor() { super(); this.getTransactionsViewContainerRef = this.getTransactionsViewContainerRef.bind(this); this.getTransactionsViewContainerWidth = this.getTransactionsViewContainerWidth.bind(this); this.getAllTransactions = this.getAllTransactions.bind(this); this.goTransactionsHome = this.goTransactionsHome.bind(this); } componentDidMount() { this.getAllTransactions(); } componentDidUpdate(prevProps) { if (prevProps.location.pathname !== this.props.location.pathname) { this.getAllTransactions(); } } componentWillUnmount() { if(this.pendintTransactionsRequest) this.pendintTransactionsRequest.abort(); if(this.confirmedTransactions) this.confirmedTransactions.abort(); } getAllTransactions() { const endpoint = this.props.location.pathname === '/transactions' ? 'transactions/confirmed' : 'transactions/pending'; this.transactionsRequest = new Xhr(endpoint); this.props.getTransactions(this.transactionsRequest, this.props.location.pathname === '/transactions' ? 'confirmed' : 'pending'); } getTransactionsViewContainerRef(el) { if (el) this.TransactionsViewContainerRef = el; } getTransactionsViewContainerWidth() { if (this.TransactionsViewContainerRef) { return parseInt(getComputedStyle(this.TransactionsViewContainerRef).width); } } goTransactionsHome() { if (this.props.location.pathname === '/transactions') { this.props.history.push('/'); } else { this.props.history.push('/transactions'); } } render() { console.log('TransactionsView') const { ids, isLoading, error, isEmpty, location} = this.props; return ( <main className="full-width"> <div ref={this.getTransactionsViewContainerRef} className="transactions-view-container"> <p> <Link to={location.pathname === '/transactions' ? '/transactions/pending' : '/transactions'}> {location.pathname === '/transactions' ? 'View pending transactions' : 'View confirmed transactions'} </Link> </p> <h2 className="">Transactions</h2> { ids && (<p>{ids.length} Transactions found.</p>) } <TableData data={ids} columns={transactionsViewData} className={isLoading || error ? 'transactions-list-container flex-axis-centered spacer-lg' : 'transactions-list-container flex-column'} tableContainerWidth={this.getTransactionsViewContainerWidth} isLoading={isLoading} error={error} isEmpty={isEmpty} buttonMessage={location.pathname === '/transactions' ? 'Go Home' : 'Go to confirmed transactions'} errorMessage={location.pathname === '/transactions' ? 'No confirmed transactions yet.' : 'No pending transactions yet.'} retryFunction={this.goTransactionsHome} /> </div> </main> ); } } export default TransactionsView;<file_sep>/src/components/Header.jsx import React from 'react'; import { withRouter } from 'react-router'; // importing styles import './styles/Header.css'; //importing images import logo from '../assets/images/GRANDPACOIN ICONO.svg'; // importing components import SearchInput from './SearchInput'; // importing utils class Header extends React.Component { constructor() { super(); this.goHome = this.goHome.bind(this); } goHome() { if (this.props.location.pathname !== '/') { this.props.history.push('/'); } } render() { return ( <header className="main-header"> <div className="main-header-content-container"> <div className="logo-container"> <h1 onClick={this.goHome}> <img src={logo} alt="Grandpa coin Logo" /> <span className="title-container"> <span className="coin-name">GrandpaCoin </span> <span className="miner-title">Scan</span> </span> </h1> </div> <div className="search-bar-container"> <SearchInput /> </div> </div> </header> ); } } export default withRouter(Header);<file_sep>/src/redux/peerActions.js export const actions = { GET_PEERS: 'GET_PEERS', GET_NODE_INFO: 'GET_NODE_INFO', ADD_NEW_PEER: 'ADD_NEW_PEER', REMOVE_PEER: 'REMOVE_PEER', ADD_NEW_NODE_INFO: 'ADD_NEW_NODE_INFO' }; export function getPeers(request) { return { type: actions.GET_PEERS, payload: request.result() } } export function getNodeInfo(request) { return { type: actions.GET_NODE_INFO, payload: request.result() } } export function addNewNodeInfo(nodeInfo) { return { type: actions.ADD_NEW_NODE_INFO, nodeInfo } } export function addNewPeer(peer) { return { type: actions.ADD_NEW_PEER, peer }; } export function removePeer(nodeUrl) { return { type: actions.REMOVE_PEER, nodeUrl }; }<file_sep>/src/containers/LatestOperationsContainer.jsx import { withRouter } from 'react-router'; import { connect } from 'react-redux'; // component import LatestOperations from '../components/LatestOperations'; // actions import { getBlocks } from '../redux/blockActions'; import { getTransactions } from '../redux/transactionActions'; export default withRouter( connect( (state, ownProps) => { return { ids: ownProps.type === 'BLOCK' ? state.blockReducer.blockIds : state.transactionReducer.confirmedTransactionIds, isLoading: ownProps.type === 'BLOCK' ? state.blockReducer.isLoading : state.transactionReducer.isLoading, isEmpty: ownProps.type === 'BLOCK' ? state.blockReducer.isEmpty : state.transactionReducer.isEmpty, error: ownProps.type === 'BLOCK' ? state.blockReducer.error : state.transactionReducer.error }; }, { getBlocks, getTransactions } )(LatestOperations) );<file_sep>/src/containers/BlockDetailsViewContainer.jsx import { withRouter } from 'react-router'; import { connect } from 'react-redux'; // component import BlockView from '../components/BlockDetailsView'; // actions import { getBlockByHash } from '../redux/blockActions'; export default withRouter( connect( (state, ownProps) => { return { data: ownProps.match.params.blockHash && state.blockReducer.data[ownProps.match.params.blockHash.trim()], isLoading: state.blockReducer.isLoading, error: state.blockReducer.error }; }, {getBlockByHash} )(BlockView) );<file_sep>/src/containers/AddressTransactionsViewContainer.jsx import { withRouter } from 'react-router'; import { connect } from 'react-redux'; // component import AddressTransactionsView from '../components/AddressTransactionsView'; // actions import { getAddressTransactions } from '../redux/transactionActions'; import { cleanHexNotation } from '../utils/granpaCoinFunctions'; export default withRouter( connect( (state, ownProps) => { return { ids: ownProps.match.params.address && state.transactionReducer.data[cleanHexNotation(ownProps.match.params.address)], isLoading: state.transactionReducer.isLoading, isEmpty: state.transactionReducer.isEmpty, error: state.transactionReducer.error, addressBalance: ownProps.match.params.address && state.balanceReducer.data[cleanHexNotation(ownProps.match.params.address)] }; }, {getAddressTransactions} )(AddressTransactionsView) );<file_sep>/src/redux/transactionReducer.js import { actions } from './transactionActions'; import { payloadFormater } from '../utils/reduxFunctions'; const initialState = { isLoading: false, pendingTransactionIds: [], confirmedTransactionIds: [], data: {}, arePendingEmpty: false, areConfirmedEmpty: false, error: false }; function transactionReducer(state = initialState, action = null) { let payload; let transactions; switch (action.type) { case actions.GET_TRANSACTIONS + '_START': return { ...state, isLoading: true, error: false, [action.meta.status === 'confirmed' ? 'areConfirmedEmpty' : 'arePendingEmpty']: false }; case actions.GET_TRANSACTIONS + '_SUCCESS': payload = payloadFormater(action.payload, 'transactionDataHash'); return { ...state, isLoading: false, data: {...payload.data, ...state.data}, [action.meta.status === 'confirmed' ? 'confirmedTransactionIds' : 'pendingTransactionIds']: payload.ids, [action.meta.status === 'confirmed' ? 'areConfirmedEmpty' : 'arePendingEmpty']: payload.ids.length === 0 }; case actions.GET_TRANSACTIONS + '_ERROR': return { ...state, isLoading: false, error: action.payload } case actions.GET_TRANSACTION_BY_HASH + '_START': return { ...state, isLoading: true, error: false }; case actions.GET_TRANSACTION_BY_HASH + '_SUCCESS': payload = payloadFormater(action.payload, 'transactionDataHash') return { ...state, isLoading: false, data: {...payload.data, ...state.data}, transactionIds: payload.ids }; case actions.GET_TRANSACTION_BY_HASH + '_ERROR': return { ...state, isLoading: false, error: action.payload } case actions.GET_ADDRESS_TRANSACTIONS + '_START': return { ...state, isLoading: true, error: false }; case actions.GET_ADDRESS_TRANSACTIONS + '_SUCCESS': payload = payloadFormater(action.payload.transactions, 'transactionDataHash') return { ...state, isLoading: false, data: { ...state.data, ...payload.data, [action.meta.address] : payload.ids }, isEmpty: payload.ids.length === 0 }; case actions.GET_ADDRESS_TRANSACTIONS + '_ERROR': return { ...state, isLoading: false, error: action.payload }; case actions.ADD_NEW_TRANSACTIONS: transactions = action.transactions.sort((actual, next) => Date.parse(next.dateCreated) - Date.parse(actual.dateCreated)); payload = payloadFormater(transactions, 'transactionDataHash'); return { ...state, confirmedTransactionIds: [...payload.ids, ...state.confirmedTransactionIds], data: { ...state.data, ...payload.data }, areConfirmedEmpty: false }; case actions.ADD_NEW_PENDING_TRANSACTION: payload = payloadFormater(action.transaction, 'transactionDataHash'); return { ...state, pendingTransactionIds: [...payload.ids, ...state.pendingTransactionIds], data: { ...state.data, ...payload.data }, arePendingEmpty: false }; default: return state; } } export default transactionReducer;<file_sep>/src/components/TableData.jsx import React from 'react'; import './styles/TableDataRow.css'; import TableDataRowContainer from '../containers/TableDataRowContainer'; import Loader from './Loader'; import Error from './Error'; import ShadowBox from './ShadowBox'; class TableData extends React.Component { constructor(props) { super(props); this.mediaQueries = { '(max-width: 5000px) and (min-width: 1599px)': 8, '(max-width: 1600px) and (min-width: 1280px)': 7, '(max-width: 1279px) and (min-width: 900px)': 5, '(max-width: 899px) and (min-width: 700px)': 4, '(max-width: 699px) and (min-width: 480px)': 3, '(max-width: 479px) and (min-width: 200px)': 2, }; this.setMediaQueries = this.setMediaQueries.bind(this); this.changeColumnsToRender = this.changeColumnsToRender.bind(this); this.state = { columnsToRender: 8 }; this.addedListeners = []; } componentDidMount() { this.setMediaQueries(); if (this.props.tableContainerWidth()) { document.documentElement.style.setProperty('--columns-width', (this.props.tableContainerWidth() / 8) + 'px'); } } componentWillUnmount() { this.removeMediaQueries(); } setMediaQueries() { Object.keys(this.mediaQueries).forEach(query => { const media = window.matchMedia(query); this.addedListeners.push(media); media.addListener(this.changeColumnsToRender); this.changeColumnsToRender(media); }); } removeMediaQueries() { this.addedListeners.forEach(media => media.removeListener(this.changeColumnsToRender)); } changeColumnsToRender(query) { if (query.matches) { this.setState({ columnsToRender: this.mediaQueries[query.media] }); } } renderTableHead() { if (this.props.columns) { return Object.keys(this.props.columns).slice(0, this.state.columnsToRender).map(key => { return ( <th key={key} className="table-th">{this.props.columns[key].label}</th> ); }); } } renderColumns() { if (this.props.data) { return this.props.data.map((singleData, index) => { return ( <TableDataRowContainer key={singleData} id={singleData} index={index} columns={this.props.columns} columnsToRender={this.state.columnsToRender} /> ); }); } } renderTableContent() { if (this.props.isLoading) return <Loader tag="tr" />; if (this.props.isEmpty) { return ( <Error errorMessage={this.props.errorMessage || 'There are no transactions yet.'} className="error-padding-large" errorMessageClassName="spacer-lg" tag="tr" buttonMessage={this.props.buttonMessage} retryFunction={this.props.retryFunction} /> ); } if (this.props.error) { return ( <Error errorMessage={this.props.error.message} className="error-padding-large" errorMessageClassName="spacer-lg" tag="tr" retryFunction={this.props.retryFunction} /> ); } return ( <React.Fragment> <tr className="transaction-row"> {this.renderTableHead()} </tr> {this.renderColumns()} </React.Fragment> ); } render() { console.log('Rendering TABLE DATA') return ( <ShadowBox tag="table" {...Object.assign({}, this.props.className ? {className: 'table-data ' + this.props.className} : {className: 'table-data'})} > <tbody> {this.renderTableContent()} </tbody> </ShadowBox> ); } } export default TableData;<file_sep>/src/components/ShadowBox.jsx import React from 'react'; // importing styles import './styles/ShadowBox.css'; class ShadowBox extends React.Component { render() { const CustomTag = this.props.tag || 'div'; const { className } = this.props; return ( <CustomTag {...Object.assign({}, className ? {className: 'shadow-box ' + className} : {className: 'shadow-box'})} > {this.props.children} </CustomTag> ); } } export default ShadowBox;<file_sep>/src/components-data/blocksViewData.js export const blocksViewData = { blockHash: {label: 'Hash', linkTo: '/block'}, dateCreated: {label: 'Date created', type: 'date'}, index: {label: 'Index'}, prevBlockHash: {label: 'Previous hash', linkTo: '/block'}, difficulty: {label: 'Difficulty'}, minedBy: {label: 'Mined by', linkTo: '/address', hex: true, type: 'address'}, nonce: {label: 'Nonce'} }<file_sep>/src/socket/ClientSocket.js import IO from 'socket.io-client'; import { addNewBlocks } from '../redux/blockActions'; import { addNewTransactions, addNewPendingTransactions } from '../redux/transactionActions'; import { addNewPeer, removePeer, addNewNodeInfo } from '../redux/peerActions'; class ClientSocket { static CHANNELS_ACTIONS = { NEW_BLOCK: 'NEW_BLOCK', NEW_PEER: 'NEW_PEER', REMOVE_PEER: 'REMOVE_PEER', NEW_CHAIN: 'NEW_CHAIN', ADD_NEW_TRANSACTION: 'ADD_NEW_TRANSACTION' }; constructor(channel, dispatch) { this.dispatch = dispatch; this.channel = channel; this.socket = IO(window.__baseUrl); this.socket.emit('PUBLIC_CONNECTION', ''); this.listen(); } listen() { this.socket.on(this.channel, data => { if (!data.actionType) return; switch (data.actionType) { case ClientSocket.CHANNELS_ACTIONS.NEW_BLOCK: this.dispatch(addNewBlocks(data.block)); this.dispatch(addNewTransactions(data.block.transactions)) break; case ClientSocket.CHANNELS_ACTIONS.NEW_PEER: this.dispatch(addNewPeer(data.peerInfo)); break; case ClientSocket.CHANNELS_ACTIONS.REMOVE_PEER: this.dispatch(removePeer(data.nodeUrl)); break; case ClientSocket.CHANNELS_ACTIONS.ADD_NEW_TRANSACTION: this.dispatch(addNewPendingTransactions(data.transaction)); break; case ClientSocket.CHANNELS_ACTIONS.NEW_CHAIN: let transactions = []; data.chain.forEach(block => { transactions = transactions.concat(block.transactions); }); this.dispatch(addNewBlocks(data.chain)); this.dispatch(addNewPendingTransactions(data.pendingTransactions)); this.dispatch(addNewTransactions(transactions)); this.dispatch(addNewNodeInfo(data.nodeInfo)); break; default: break; } }); } } export default ClientSocket;<file_sep>/src/App.js import React from "react"; import { Provider } from "react-redux"; import { BrowserRouter as Router } from "react-router-dom"; import { configureStore } from "./redux/store"; import { Switch, Redirect, Route } from "react-router"; import HomeView from './components/HomeView'; import NotFound from './components/NotFound'; import TransactionsViewContainer from './containers/TransactionsViewContainer'; import BlockViewContainer from './containers/BlockDetailsViewContainer'; import PeersViewContainer from './containers/PeersViewContainer'; import TransactionDetailsViewContainer from './containers/TransactionDetailsViewContainer'; import AddressTransactionsViewContainer from './containers/AddressTransactionsViewContainer'; import BlocksViewContainer from './containers/BlocksViewContainer'; import Header from "./components/Header"; import Xhr from "./utils/Xhr"; import ClientSocket from './socket/ClientSocket'; // store const store = configureStore(); window.__baseUrl = 'http://localhost:5555/'; // window.__baseUrl = 'http://192.168.1.146:5555/' new ClientSocket('CLIENT_CHANNEL', store.dispatch); // global constants export const COINS = { grandpa: 1000000, son: 1000, grandson: 1 }; Xhr.baseUrl = window.__baseUrl; const App = () => { return ( <Provider store={store}> <Router> <Header /> <Switch> <Route path="/" component={HomeView} exact /> <Route path="/address/:address/transactions" component={AddressTransactionsViewContainer} exact /> <Route path="/block/:blockHash" component={BlockViewContainer} exact /> <Route path="/transaction/:transactionDataHash" component={TransactionDetailsViewContainer} exact /> <Route path="/transactions" component={TransactionsViewContainer} exact /> <Route path="/transactions/pending" component={TransactionsViewContainer} exact /> <Route path="/blocks" component={BlocksViewContainer} exact /> <Route path="/node/peers" component={PeersViewContainer} exact /> <Route path="/not-found/:resource" component={NotFound} exact /> </Switch> </Router> </Provider> ); }; export default App; <file_sep>/src/utils/dateFunctions.js import moment from 'moment'; export function dateHumanize(date) { return moment.duration(moment(date).diff(new Date())).humanize() + ' ago.' }<file_sep>/src/containers/BlocksViewContainer.jsx import { withRouter } from 'react-router'; import { connect } from 'react-redux'; // component import BlocksView from '../components/BlocksView'; // actions import { getBlocks } from '../redux/blockActions'; export default withRouter( connect( (state, ownProps) => { return { ids: state.blockReducer.blockIds, isLoading: state.blockReducer.isLoading, isEmpty: state.blockReducer.isEmpty, error: state.blockReducer.error }; }, {getBlocks} )(BlocksView) );<file_sep>/src/components/ListBox.jsx import React from 'react'; import './styles/ListBox.css'; import Loader from './Loader'; import Error from './Error'; class ListBox extends React.Component { constructor() { super(); this.renderListItems = this.renderListItems.bind(this); } renderListItems() { const { children: ChildrenComponent } = this.props; React.Children.only(this.props.children); if (this.props.isLoading) { return <Loader /> } if (this.props.isEmpty) { return ( <p>There are no blocks yet.</p> ) } if (this.props.error) { return ( <Error errorMessage={this.props.error.message} className="error-padding-large" errorMessageClassName="spacer flex-column text-center" retryFunction={this.props.errorFunction} /> ); } if (typeof ChildrenComponent.type === 'string') return console.error(new Error('Uncaught Invariant Violation: expected to receive a single React Component as a child.')); if (this.props.data) { return this.props.data.map((itemData, index) => { return ( <ChildrenComponent.type key={itemData} id={itemData} index={index} {...this.props.children.props} /> ); }); } } render() { console.log('Rendering ListBox') const Tag = this.props.tag || 'article'; return ( <Tag {...Object.assign({}, this.props.className ? {className: 'list-container ' + this.props.className} : {className: 'list-container'})} > {this.renderListItems()} </Tag> ); } } export default ListBox;<file_sep>/src/components/TransactionDetailsView.jsx import React from 'react'; // importing styles import './styles/BlockDetailsView.css'; // importing utils import Xhr from '../utils/Xhr'; import DetailsBox from './DetailsBox'; import { denoteHex } from '../utils/granpaCoinFunctions'; class TransactionDetailsView extends React.Component { constructor() { super(); this.transactionRows = { from: {label: 'From', linkTo: '/address', type: 'address', hex: true}, to: {label: 'To', linkTo: '/address', type: 'address', hex: true}, value: {label: 'Value', type: 'coin'}, fee: {label: 'Fee', type: 'coin'}, dateCreated: {label: 'Date created', type: 'date'}, data: {label: 'Data', capitalize: true}, senderPubKey: {label: 'Sender Public key'}, transactionDataHash: {label: 'Transaction data hash', linkTo: '/transaction', hex: true}, minedInBlockIndex: {label: 'Mined in block index'}, transferSuccessful: {label: 'Transfer successful', capitalize: true} }; this.getTransaction = this.getTransaction.bind(this); } componentDidMount() { if (!this.props.data) { this.getTransaction(); } } getTransaction() { this.transactionDataRequest = new Xhr(`transaction/${this.props.match.params.transactionDataHash.trim()}`); this.props.getTransactionByHash(this.transactionDataRequest); } render() { console.log('TransactionDetailsView') return ( <main className="full-width"> <div className="show-block-main-content-container"> <h2 className="block-hash"> Transaction # {this.props.data ? denoteHex(this.props.data.transactionDataHash.trim()) : ''} </h2> <DetailsBox data={this.props.data} rows={this.transactionRows} error={this.props.error} isLoading={this.props.isLoading} /> </div> </main> ) } } export default TransactionDetailsView;<file_sep>/src/components-data/transactionsViewData.js export const transactionsViewData = { transactionDataHash: {label: 'Hash', linkTo: '/transaction', hex: true}, dateCreated: {label: 'Date created', type: 'date'}, status: {label: 'Status'}, from: {label: 'From', linkTo: '/address', type: 'address', hex: true}, to: {label: 'To', linkTo: '/address', type: 'address', hex: true}, value: {label: 'Value', type: 'coin'}, // fee: {label: 'Fee'}, minedInBlockIndex: {label: 'Mined in block index'}, data: {label: 'Data'}, };<file_sep>/src/components/NotFound.jsx import React from 'react'; import { withRouter } from 'react-router-dom'; // importing styles import './styles/NotFound.css'; class NotFound extends React.Component { constructor() { super(); this.goHome = this.goHome.bind(this); } goHome() { this.props.history.push('/'); } render() { return ( <main className="not-found-container"> {this.props.match.params.resource && <p>{this.props.match.params.resource}</p>} <h2>Not found</h2> <div className="full-width flex-c-x-centered"> <button onClick={this.goHome} className="btn">Go home</button> </div> </main> ); } } export default withRouter(NotFound);<file_sep>/src/components/HomeView.jsx import React from 'react'; // importing components import LatestOperationsContainer from '../containers/LatestOperationsContainer'; // importing styles import './styles/HomeView.css'; import HomeViewSideElementContainer from '../containers/HomeViewSideElementContainer'; import MobileNodeInfoContainer from '../containers/MobileNodeInfoContainer'; class HomeView extends React.Component { constructor() { super(); this.state = { shouldRenderSideBox: false }; this.mediaQuery = window.matchMedia('(max-width: 967px) and (min-width: 100px)'); this.setMatchMedia = this.setMatchMedia.bind(this); this.renderSideBox = this.renderSideBox.bind(this); } componentDidMount() { this.setMatchMedia(); } setMatchMedia() { this.mediaQuery.addListener(this.renderSideBox); this.renderSideBox(this.mediaQuery) } componentWillUnmount() { this.mediaQuery.removeListener(this.renderSideBox); } renderSideBox(query) { if (query.matches) { if (this.state.shouldRenderSideBox) { this.setState({ shouldRenderSideBox: false }); } } else { if (!this.state.shouldRenderSideBox) { this.setState({ shouldRenderSideBox: true }); } } } render() { console.log('rendering') return ( <main className="home-main flex-row"> {this.state.shouldRenderSideBox && <HomeViewSideElementContainer />} <div className="main-content"> {!this.state.shouldRenderSideBox && <MobileNodeInfoContainer />} <LatestOperationsContainer type="BLOCK" title="Latest Blocks" linkToText="View all" linkTo="blocks" /> <LatestOperationsContainer type="TRANSACTION" title="Latest Transactions" linkToText="View all" linkTo="transactions" /> </div> </main> ); } } export default HomeView;<file_sep>/src/containers/PeersViewContainer.jsx import { withRouter } from 'react-router'; import { connect } from 'react-redux'; // component import PeersView from '../components/PeersView'; // actions import { getPeers } from '../redux/peerActions'; export default withRouter( connect( state => { return { ids: state.peerReducer.peerIds, isLoading: state.peerReducer.isLoading, isEmpty: state.peerReducer.isEmpty, error: state.peerReducer.error }; }, {getPeers} )(PeersView) );<file_sep>/src/components/SideBox.jsx import React from 'react'; // importing styles import './styles/SideBox.css'; // importing utils import { toGrandpaCoin } from '../utils/granpaCoinFunctions'; import Link from './Link'; import Loader from './Loader'; import Error from './Error'; class SideBox extends React.Component { shouldComponentUpdate(prevProps) { if (prevProps.isLoading !== this.props.isLoading) return true; if (prevProps.content !== this.props.content) return true; return false; } renderFirstRowInfo() { const { data, titleContent, parse } = this.props; if (data) { return ( <p className="box-content">{parse ? toGrandpaCoin(data[titleContent]) : data[titleContent]}</p> ); } } renderData() { const { content, isLoading, error, retryFunction } = this.props; if (isLoading) { return ( <Loader /> ); } if (error) { return ( <Error errorMessage="Ups! Something happened." errorMessageClassName="side-box-error" retryFunction={retryFunction} /> ); } if (content) { return content.map(singleData => { return ( <div key={singleData.title} className="latest-box-info flex-column"> <h4 className="sidebox-title">{singleData.title}</h4> {this.renderFormatedData(singleData)} </div> ); }); } } renderFormatedData(singleData) { if (singleData.linkTo) { return ( <Link to={this.getFormattedLinkTo(singleData)}> {singleData.content} </Link> ); } return <p className="box-content ellipsis">{singleData.content}</p>; } getFormattedLinkTo(singleData) { if (singleData.withParam) { return singleData.linkTo + '/' + singleData.content + `${singleData.type === 'address' ? '/transactions' : ''}`; } return singleData.linkTo; } render() { console.log('SideBox') return ( <div className="side-box-container"> <div className="content-container flex-row"> { this.props.image && ( <div className="image-container"> <img src={this.props.image} alt="Latest block icon." /> </div> ) } <div className="flex-column flex no-overflow"> {this.renderData()} </div> </div> </div> ); } } export default SideBox;<file_sep>/src/components-data/peersViewData.js export const peersViewData = { nodeId: {label: 'Node ID'}, nodeUrl: {label: 'Node Url'}, cumulativeDifficulty: {label: 'Node difficulty'} };
ef9e58e3f781b1c2fafdacfc77d25d77bcc00b87
[ "JavaScript" ]
33
JavaScript
family-group/grandpascan
e68d19ec240eb5d888755371a49c756f9c868a86
23e5913975e7a0ee094e031978d60789186373eb
refs/heads/master
<file_sep>var Player = function(id){ this.id = id; this.lastRollSum = 0; }; exports.Player = Player<file_sep># dice-app ###Using docker: 1. docker build -t glisauskas/dice-app . 2. docker run -p 8080:8080 -d glisauskas/dice-app ###or not: 1. npm install 2. node app.js #####Resulting url: http://localhost:8080<file_sep>var GameInfo = React.createClass({ render: function() { return ( <div> <GeneralGameInfo diceCount={2} playerCount={3} /> {/*<PlayerList players=players />*/} </div> ) } }); var GeneralGameInfo = React.createClass({ render: function() { return ( <div id="game-info"> <h1>Amazing dice game</h1> <h3>Current dice count: <span>{this.props.diceCount}</span></h3> <h3>Current player count: <span>{this.props.playerCount}</span></h3> </div> ) } }); var PlayerList = React.createClass({ render: function() { var rows = []; this.props.players.forEach(function(player) { rows.push(<PlayerRow key={player.id} lastRollSum={player.lastRollSum}/>); }); return ( <div> <ul> {rows} </ul> </div> ) } }); var PlayerRow = React.createClass({ render: function() { return ( <li key={this.props.key}> <div> <span className="player-id">{this.props.key}</span> <span className="player-last-roll-sum">{this.props.lastRollSum}</span> </div> </li> ) } });<file_sep>var DiceAmountPicker = React.createClass({ render: function() { return ( <div> <span>As the number of dices have not been set yet, you have honour to do that</span> <DicePickRow /> <input type="button">Set!</input> </div> ) } }); var DicePickRow = React.createClass({ render: function() { var diceNumbers = [1, 2, 3, 4]; diceNumbers.map(function(number){ return <li>{number}</li> }); return ( <ul> {diceNumbers} </ul> ) } });<file_sep>'use strict'; var express = require('express'); var app = express(); var serv = require('http').Server(app); var Game = require('./server/game').Game; var Player = require('./server/player').Player; var io, socketList, game; init(); function init() { app.get('/', function (req, res) { res.sendFile(__dirname + '/client/index.html'); }); app.use('/client', express.static(__dirname + '/client')); app.use('/client/js', express.static(__dirname + '/client/js')); serv.listen(8080) io = require('socket.io')(serv, {}); socketList = []; game = new Game(); setEventHandlers(); } function setEventHandlers() { io.sockets.on("connection", onSocketConnection); } function onSocketConnection(socket) { socket.on("disconnect", onSocketDisconnect); socket.on("new player", onNewPlayer); // socket.on("set number of dices", onSetNumberOfDices); } function onSocketDisconnect() { console.log('Player disconected' + this.id); removeFromGameInfo(this); updateClientsGameInfo(this); } function onNewPlayer() { console.log('New player connected: ' + this.id); // if (game.numberOfDices == 0) { // this.emit('set number of dices'); // } addToGameInfo(this); updateClientsGameInfo(); } function updateClientsGameInfo() { for (var i = 0; i < socketList.length; i++) { socketList[i].emit("update game info", game); } } function onSetNumberOfDices(data) { console.log('dice number being set to: ' + data.number); if (data.number >= 1 && data.number <= 4 && game.numberOfDices == 0) { game.numberOfDices = data.number; } this.broadcast.emit("number of dices", {number: game.numberOfDices}); } function addToGameInfo(socket) { socketList.push(socket); game.players.push(new Player(socket.id)); } function removeFromGameInfo(socket) { socketList.splice(socketList.indexOf(socket), 1); for (var i = 0; i < game.players.length; i++) { if (game.players[i].id == socket.id) { game.players.splice(i, 1); break; } } } function listGameLists() { // for debugging reasons console.log('Number of players connected: ' + game.players.length); game.players.forEach(function (player) { console.log(player.id); }); console.log('Number of sockets: ' + socketList.length); socketList.forEach(function (socket) { console.log(socket.id); }); }
cc030659c6085f373949b73cf081e064b749294d
[ "JavaScript", "Markdown" ]
5
JavaScript
npmcdn-to-unpkg-bot/dice-app
1f57972ed490bd71dc6aac276a73bf75cf10c4e4
2d67038e96b7149903a7414631406f2952a9e2c6
refs/heads/master
<file_sep>/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* This is a JNI example where we use native methods to play video * using the native AMedia* APIs. * See the corresponding Java source file located at: * * src/com/example/nativecodec/NativeMedia.java * * In this example we use assert() for "impossible" error conditions, * and explicit handling and recovery for more likely error conditions. */ #include <assert.h> #include <jni.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/time.h> #include "looper.h" #include "media/NdkMediaCodec.h" #include "media/NdkMediaExtractor.h" // for __android_log_print(ANDROID_LOG_INFO, "YourApp", "formatted message"); #include <android/log.h> #define TAG "NativeCodec" #define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, TAG, __VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__) // for native window JNI #include <android/native_window_jni.h> typedef struct { int fd; ANativeWindow* window; AMediaExtractor* ex; AMediaCodec *codec; int64_t renderstart; bool sawInputEOS; bool sawOutputEOS; bool isPlaying; bool renderonce; jobject surface; int32_t width; int32_t height; } workerdata; workerdata data = {-1, NULL, NULL, NULL, 0, false, false, false, false, 0, 0, 0}; bool bSwap = false; enum { kMsgCodecBuffer, kMsgPause, kMsgResume, kMsgPauseAck, kMsgDecodeDone, kMsgSeek, }; /* Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *t2, struct timeval *t1) { long int diff = (t2->tv_usec + 1000000 * t2->tv_sec) - (t1->tv_usec + 1000000 * t1->tv_sec); result->tv_sec = diff / 1000000; result->tv_usec = diff % 1000000; LOGE("Diff Time:%d",diff); return (diff<0); } class mylooper: public looper { virtual void handle(int what, void* obj); }; static mylooper *mlooper = NULL; int64_t systemnanotime() { timespec now; clock_gettime(CLOCK_MONOTONIC, &now); return now.tv_sec * 1000000000LL + now.tv_nsec; } void doCodecWork(workerdata *d) { ssize_t bufidx = -1; if (!d->sawInputEOS) { bufidx = AMediaCodec_dequeueInputBuffer(d->codec, 2000); // LOGV("input buffer %zd", bufidx); if (bufidx >= 0) { size_t bufsize; auto buf = AMediaCodec_getInputBuffer(d->codec, bufidx, &bufsize); auto sampleSize = AMediaExtractor_readSampleData(d->ex, buf, bufsize); if (sampleSize < 0) { sampleSize = 0; d->sawInputEOS = true; LOGV("EOS"); } auto presentationTimeUs = AMediaExtractor_getSampleTime(d->ex); AMediaCodec_queueInputBuffer(d->codec, bufidx, 0, sampleSize, presentationTimeUs, d->sawInputEOS ? AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM : 0); AMediaExtractor_advance(d->ex); } } if (!d->sawOutputEOS) { AMediaCodecBufferInfo info; int status = AMediaCodec_dequeueOutputBuffer(d->codec, &info, 0); if (status >= 0) { if (info.flags & AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM) { LOGV("output EOS"); d->sawOutputEOS = true; } int64_t presentationNano = info.presentationTimeUs * 1000; if (d->renderstart < 0) { d->renderstart = systemnanotime() - presentationNano; } int64_t delay = (d->renderstart + presentationNano) - systemnanotime(); if (delay > 0) { usleep(delay / 1000); } size_t frame_size = 0; uint8_t* framePt = NULL; framePt = AMediaCodec_getOutputBuffer(d->codec,status,&frame_size); if(NULL!=framePt) { ANativeWindow_Buffer buffer; int WIDNOW_FORMAT_NV21 = 0x11; ANativeWindow_setBuffersGeometry(data.window,d->width,d->height,WIDNOW_FORMAT_NV21); if (ANativeWindow_lock(data.window, &buffer, NULL) == 0) { struct timeval tvBegin, tvEnd, tvDiff; gettimeofday(&tvBegin, NULL); if(!bSwap) { memcpy(buffer.bits, framePt, d->width * d->height * 3 / 2); } else { int ySize = d->width * d->height; unsigned char* dest = (unsigned char*)buffer.bits; memcpy(dest,framePt,ySize); int uvSize = ySize>>1; int uSize = uvSize>>1; memcpy(dest+ySize,framePt+ySize+1,uvSize-1); unsigned char *nvcur = framePt+ySize; unsigned char *yuvcur = dest+ySize+1; int i=0; while(i<uSize) { (*yuvcur)=(*nvcur); yuvcur+=2; nvcur+=2; ++i; } } gettimeofday(&tvEnd, NULL); long int diff = (tvEnd.tv_usec + 1000000 * tvEnd.tv_sec) - (tvBegin.tv_usec + 1000000 * tvBegin.tv_sec); LOGE("Spend Time:%d",diff/1000); ANativeWindow_unlockAndPost(data.window); } } AMediaCodec_releaseOutputBuffer(d->codec, status, info.size != 0); if (d->renderonce) { d->renderonce = false; return; } } else if (status == AMEDIACODEC_INFO_OUTPUT_BUFFERS_CHANGED) { LOGV("output buffers changed"); } else if (status == AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED) { auto format = AMediaCodec_getOutputFormat(d->codec); LOGV("format changed to: %s", AMediaFormat_toString(format)); AMediaFormat_delete(format); } else if (status == AMEDIACODEC_INFO_TRY_AGAIN_LATER) { LOGV("no output buffer right now"); } else { LOGV("unexpected info code: %zd", status); } } if (!d->sawInputEOS || !d->sawOutputEOS) { mlooper->post(kMsgCodecBuffer, d); } } void mylooper::handle(int what, void* obj) { switch (what) { case kMsgCodecBuffer: doCodecWork((workerdata*)obj); break; case kMsgDecodeDone: { workerdata *d = (workerdata*)obj; AMediaCodec_stop(d->codec); AMediaCodec_delete(d->codec); AMediaExtractor_delete(d->ex); d->sawInputEOS = true; d->sawOutputEOS = true; } break; case kMsgSeek: { workerdata *d = (workerdata*)obj; AMediaExtractor_seekTo(d->ex, 0, AMEDIAEXTRACTOR_SEEK_NEXT_SYNC); AMediaCodec_flush(d->codec); d->renderstart = -1; d->sawInputEOS = false; d->sawOutputEOS = false; if (!d->isPlaying) { d->renderonce = true; post(kMsgCodecBuffer, d); } LOGV("seeked"); } break; case kMsgPause: { workerdata *d = (workerdata*)obj; if (d->isPlaying) { // flush all outstanding codecbuffer messages with a no-op message d->isPlaying = false; post(kMsgPauseAck, NULL, true); } } break; case kMsgResume: { workerdata *d = (workerdata*)obj; if (!d->isPlaying) { d->renderstart = -1; d->isPlaying = true; post(kMsgCodecBuffer, d); } } break; } } extern "C" { static struct CachedFields { jclass fileDescriptorClass; jmethodID fileDescriptorCtor; jfieldID descriptorField; } gCachedFields; bool bInit = false; int jniGetFdFromFileDescriptor(JNIEnv* env, jobject jFileDescriptor) { if(!bInit) { gCachedFields.fileDescriptorClass = env->FindClass("java/io/FileDescriptor"); gCachedFields.fileDescriptorCtor = env->GetMethodID(gCachedFields.fileDescriptorClass, "<init>", "()V"); gCachedFields.descriptorField = env->GetFieldID(gCachedFields.fileDescriptorClass, "descriptor", "I"); } return env->GetIntField(jFileDescriptor, gCachedFields.descriptorField); } void Java_com_example_nativecodec_NativeCodec_doUVSwap(JNIEnv* env, jclass clazz, jboolean swap) { bSwap = swap; } jboolean Java_com_example_nativecodec_NativeCodec_createStreamingMediaPlayer(JNIEnv* env, jclass clazz, jobject jFileDescriptor) { LOGV("@@@ create"); off_t outStart = 0; off64_t outLen=0x7ffffffffffffffL; int fd = jniGetFdFromFileDescriptor(env, jFileDescriptor); if (fd < 0) { LOGE("failed to open file: %s %d (%s)", fd, strerror(errno)); return JNI_FALSE; } data.fd = fd; workerdata *d = &data; AMediaExtractor *ex = AMediaExtractor_new(); media_status_t err = AMediaExtractor_setDataSourceFd(ex, d->fd, static_cast<off64_t>(outStart), outLen); close(d->fd); if (err != AMEDIA_OK) { LOGV("setDataSource error: %d", err); return JNI_FALSE; } int numtracks = AMediaExtractor_getTrackCount(ex); AMediaCodec *codec = NULL; LOGV("input has %d tracks", numtracks); for (int i = 0; i < numtracks; i++) { AMediaFormat *format = AMediaExtractor_getTrackFormat(ex, i); const char *s = AMediaFormat_toString(format); LOGV("track %d format: %s", i, s); const char *mime; if (!AMediaFormat_getString(format, AMEDIAFORMAT_KEY_MIME, &mime)) { LOGV("no mime type"); return JNI_FALSE; } else if (!strncmp(mime, "video/", 6)) { AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_HEIGHT, &data.height); AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_WIDTH, &data.width); int64_t NV21 = 21; AMediaFormat_setInt64(format, AMEDIAFORMAT_KEY_COLOR_FORMAT, NV21); // Omitting most error handling for clarity. // Production code should check for errors. AMediaExtractor_selectTrack(ex, i); codec = AMediaCodec_createDecoderByType(mime); AMediaCodec_configure(codec, format, NULL, NULL, 0); d->ex = ex; d->codec = codec; d->renderstart = -1; d->sawInputEOS = false; d->sawOutputEOS = false; d->isPlaying = false; d->renderonce = true; AMediaCodec_start(codec); } AMediaFormat_delete(format); } mlooper = new mylooper(); mlooper->post(kMsgCodecBuffer, d); return JNI_TRUE; } // set the playing state for the streaming media player void Java_com_example_nativecodec_NativeCodec_setPlayingStreamingMediaPlayer(JNIEnv* env, jclass clazz ,jboolean isPlaying) { // workerdata* data = (workerdata*) workdata; LOGV("@@@ playpause: %d", isPlaying); if (mlooper) { if (isPlaying) { mlooper->post(kMsgResume, &data); } else { mlooper->post(kMsgPause, &data); } } } // shut down the native media system void Java_com_example_nativecodec_NativeCodec_shutdown(JNIEnv* env, jclass clazz) { LOGV("@@@ shutdown"); if (mlooper) { mlooper->post(kMsgDecodeDone, &data, true /* flush */); mlooper->quit(); delete mlooper; mlooper = NULL; } } // set the surface void Java_com_example_nativecodec_NativeCodec_setSurface(JNIEnv *env, jclass clazz,jobject surface) { // obtain a native window from a Java surface if (data.window) { ANativeWindow_release(data.window); data.window = NULL; } data.window = ANativeWindow_fromSurface(env, surface); LOGV("@@@ setsurface %p", data.window); } // rewind the streaming media player void Java_com_example_nativecodec_NativeCodec_rewindStreamingMediaPlayer(JNIEnv *env, jclass clazz) { LOGV("@@@ rewind"); if (mlooper) { mlooper->post(kMsgSeek, &data); } } } <file_sep>//#include <stdint.h> extern void *memcpy_hybrid(void *dest, const void *src, size_t n);
88acbd9e34bf673e77617701d0d6d3d5c7917f4b
[ "C", "C++" ]
2
C++
hank5000/NativeCodec
cdfdb00f640d420c797afb69a759108c6da69ddd
1c2c0a06d31e3528440754c740091501852dd39d
refs/heads/master
<file_sep>package com.testauto.framework.testsuite.general; import com.testauto.framework.pageobjects.HomePage; import com.testauto.framework.testsuite.WebDriverListener; import org.apache.log4j.Logger; import org.junit.*; import org.junit.Test; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.events.EventFiringWebDriver; import ru.yandex.qatools.allure.annotations.*; import java.io.IOException; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; /** * Created by maheshb on 6/15/17. * * Allure annotations are used along with the junit annotation to facilitate to generate the allure report * @Title @Description @Step are allure annotations * * Allure Reports for Junit framework: * https://github.com/allure-framework/allure1/wiki/JUnit * * Junit runner classes such as JUnitcore Result & Failure are used to drive the Junit test case * http://junit.sourceforge.net/javadoc/org/junit/runner/JUnitCore.html * * Comparison of Hamcrest assertion matcher framework with Junit4 assertion framework style * http://www.vogella.com/tutorials/Hamcrest/article.html * * Debugger used log4j 2.x * https://logging.apache.org/log4j/2.x/manual/index.html * */ @Title("Test for Php Travels booking") @Description("The objective of the test case is to search the packages available for the given destination") public class Runner { static WebDriver stDriver; static EventFiringWebDriver driver; static Logger logger; HomePage home; @BeforeClass public static void setUp() { System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + "\\chromedriver.exe"); //Instantiating driver object and launching browser stDriver = new ChromeDriver(); driver = new EventFiringWebDriver(stDriver); WebDriverListener webDriverListener = new WebDriverListener(); driver.register(webDriverListener); logger = Logger.getLogger(Runner.class.getName()); driver.manage().window().maximize(); driver.get("https://autorqa.events.epam.com/autoqa-login?email=<EMAIL>&return_url=/"); } @AfterClass public static void tearDown() { driver.close(); } @Before public void before() { logger.debug("Before Test"); } @After public void after() { logger.debug("After Test"); } @Test public void test() throws IOException { home = PageFactory.initElements(driver, HomePage.class); logger.debug("Page is initialised"); searchUrl(); home.goToAdminMenu(); } @Step("Search on the basis of city") private void searchUrl() throws IOException { logger.trace("Searching City Name"); assertThat(driver.getCurrentUrl(), containsString("autorqa")); } public static void main(String[] args) { Result result = JUnitCore.runClasses(Runner.class); for (Failure failure : result.getFailures()) { logger.trace(failure.toString()); } logger.trace(result.wasSuccessful()); } }
299fc7f0f601aa42b686bd5f99b8ae0f161707fb
[ "Java" ]
1
Java
globant-mahesh/UICucumberTestNG
4887d16b34a778b856c4a25ac1721fc7513d26c4
df5b4faaa474ebfd95ab1220ca0266ea2d4901ea
refs/heads/master
<file_sep>#------------------------------------------------------------------------------------------------------------# ### 1.0 LOAD LIBRARY'S ---- import os, sys import pandas as pd import numpy as np import dateutil # Workflow # 1.Create a neural network that can convert Celsius to Fahrenheit # and examine the weights. # 2. Using TensorFlow andKeras build a single layered network with a # single input and a single output and a single neuron. # 3. Using NumPy generate ~20 input/output values to test # 4. Train the neural network on your data. # 5. Test the neural network to see if it is working. # 6. Examine the weights to see if they match F = C * 1.8 + 32F=C∗1.8+32. ### train dataframe num = np.random.randint(-100, 100, size=(20, 1)) train = pd.DataFrame(num, columns=['degrees_c']) train['degrees_f'] = train['degrees_c'] * 1.8 + 32 ### test dataframe num = np.random.randint(-100, 100, size=(5, 1)) test = pd.DataFrame(num, columns=['degrees_c']) test['degrees_f'] = test['degrees_c'] * 1.8 + 32 print(train) ### split into dependent/independent predictors x_train = train.drop(['degrees_f'], axis=1) y_train = train['degrees_f'] x_test = test.drop(['degrees_f'], axis=1) y_test = test['degrees_f'] #------------------------------------------------------------------------------------------------------------# ### 2.0 KERAS ---- from keras.models import Sequential from keras.layers import Dense # Create a Sequential model model = Sequential() # Need ~50 neurons in order for the predictions to be accurate # Add dense layers model.add(Dense(50, input_shape=(1,))) # Add two Dense layers with 50 neurons model.add(Dense(50)) model.add(Dense(50)) # End your model with a Dense layer and no activation model.add(Dense(1)) # Compile your model model.compile(optimizer="adam", loss="mse") # Fit your model on your data for 30 epochs model.fit(x_train, y_train, epochs = 500) # Get model predicions model.predict(x_test) test print("Check weight: {}".format(model.get_weights())) #------------------------------------------------------------------------------------------------------------# ### 3.0 TENSORFLOW ---- import tensorflow as tf print(tf.__version__) # Below are the key parts to the network: # - Sequential: We will want this to be a sequential network. For the most part, # this is the default type. It just means that the data flows sequentially # through all of the layers. # - Dense: This is the simplest layer available. For a deeper understanding you # can check out the official documentation here # units: This specifies the number of neurons in the layer. In other words, this # is the number of variables the layer has to learn. # input_shape: This specifies how many parameters that we will pass to our # network. Since we are just going to send in the temperate in Celcius # we only need 1. # - compile: We need to compile the network to be able to start using it. # - loss: This is the loss function. It is how the network is able to determin # how far off the prediction is from the desired outcome. # - optimizer: This determines the way the internal values are adjusted to reduce # the loss. For more information on the Adam optimizer go to the documentation # here. model = tf.keras.Sequential( tf.keras.layers.Dense(units=1, input_shape=[1]) ) model.compile(loss='mean_squared_error', optimizer=tf.keras.optimizers.Adam(0.1)) # Below are the key parts of the training code: # - history: These values are the results of the # training. We will use these after to graph what # we have done. # - fit: This is the method that does the training of # the model. We are passing in our celsius data and # also passing in our expected output (fahrenheit) # data. # - epochs: This parameter specifies how many times # this cycle should be run. history = model.fit(x_train, y_train, epochs=500, verbose=True) import matplotlib.pyplot as plt plt.xlabel('Epoch') plt.ylabel('Loss') plt.plot(history.history['loss']) # Get model predicions model.predict(x_test) test # Examine weights print("This is the weight that should be pretty close to the *1.8 in the formula: {}".format( model.layers[0].get_weights()[0][0] )) print("This is the bias that should be pretty close to the +32 in the formula: {}".format( model.layers[0].get_weights()[1] )) <file_sep>#------------------------------------------------------------------------------------------------------------# ### 1.0 LOAD LIBRARY'S ---- import tensorflow as tf from tensorflow import keras import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.preprocessing import StandardScaler pd.set_option('display.max_rows', 10) pd.set_option('display.max_columns', 10) pd.set_option('display.width', 100) np.set_printoptions(suppress=True) pd.set_option('display.float_format', lambda x: '%.5f' % x) # Workflow # Overfit a the neural network from milestone 3. # There are ways to overfit your network, but for this # milestone we want to over-train on the training data. # See Chapter 6 of Grokking Deep Learning for more details. # Graph the training versus validation metrics prove overfitting. # Load the data set from the last milestone 1 column_names = ['Date','HomeTeam','HomeScore','AwayTeam','AwayScore', 'HomeScoreAverage','HomeDefenseAverage','AwayScoreAverage','AwayDefenseAverage', 'Result'] games_csv = 'https://liveproject-resources.s3.amazonaws.com/other/deeplearningbasketballscores/Games-Calculated.csv' all_data = pd.read_csv(games_csv, header=None, names=column_names) all_data.head() #------------------------------------------------------------------------------------------------------------# ### 2.0 SPLIT DATASET ---- # Drop the columns that we are NOT going to train on all_data.drop(['Date','HomeTeam','HomeScore','AwayTeam','AwayScore'], axis=1, inplace=True) all_data.tail() #Break it into 80/20 splits train = all_data.sample(frac=0.8, random_state=0) test = all_data.drop(train.index) print('Training Size: %s' % train.shape[0]) print('Testing Size: %s' % test.shape[0]) #Create the labels train_labels = train.pop('Result') test_labels = test.pop('Result') # Standardize the train and test features sc = StandardScaler() train_data = pd.DataFrame(sc.fit_transform(train)) test_data = pd.DataFrame(sc.transform(test)) train_data.columns = train.columns test_data.columns = test.columns train_data.describe() test_data.describe() #------------------------------------------------------------------------------------------------------------# ### 3.0 NEURAL NETWORK ---- def Build_Model(): model = keras.models.Sequential([ keras.layers.Dense(32, activation='relu', input_shape=(train_data.shape[1],)), keras.layers.Dense(32, activation='relu'), keras.layers.Dense(1) ]) opt = keras.optimizers.RMSprop() m = [ keras.metrics.MeanAbsoluteError(), keras.metrics.Accuracy(), keras.metrics.MeanSquaredError() ] l = keras.losses.MeanSquaredError() model.compile(loss=l, optimizer=opt, metrics=m) return model model = Build_Model() #------------------------------------------------------------------------------------------------------------# ### 4.0 TRAIN MODEL ---- history = model.fit(train_data, train_labels, epochs=300, validation_split=0.2, verbose=True ) # Check the results # Create a DataFrame from the output from the fit method hist = pd.DataFrame(history.history) # Create an epoch column and set it to the epoch index hist['epoch'] = history.epoch hist.tail() # Test the network against your testing data set test_loss, mae, test_acc, mse = model.evaluate(test_data, test_labels) mae def plot_history(history): plt.figure() plt.xlabel('Epoch') plt.ylabel('Mean Absolute Error') plt.plot(history['epoch'], history['mean_absolute_error'], label='Train Mean Absolute Error') plt.plot(history['epoch'], history['val_mean_absolute_error'], label = 'Val Mean Absolute Error') plt.legend() #plt.ylim([0,1]) plt.show() plot_history(hist) <file_sep>#------------------------------------------------------------------------------------------------------------# ### 1.0 LOAD LIBRARY'S ---- from __future__ import absolute_import, division, print_function from tensorflow import keras from tensorflow.keras import layers from kerastuner.tuners import RandomSearch import pandas as pd import numpy as np import matplotlib.pyplot as plt from IPython.display import SVG from keras.utils.vis_utils import model_to_dot from sklearn.preprocessing import StandardScaler pd.set_option('display.max_rows', 10) pd.set_option('display.max_columns', 10) pd.set_option('display.width', 100) np.set_printoptions(suppress=True) pd.set_option('display.float_format', lambda x: '%.5f' % x) # Workflow # Start with your original network and check the mean absolute error that # you get from running the evaluate method on your testing data. # Create a series of networks that try and beat those results. Check the # notes section for a recommendation on the process. # Alter the network’s layers, neurons, optimizers, activation functions, # loss function, and so on. # Repeat until you have a satisfactory result. # Download your best model in h5 format. # Load the data set from the last milestone 1 column_names = ['Date','HomeTeam','HomeScore','AwayTeam','AwayScore', 'HomeScoreAverage','HomeDefenseAverage','AwayScoreAverage','AwayDefenseAverage', 'Result'] games_csv = 'https://liveproject-resources.s3.amazonaws.com/other/deeplearningbasketballscores/Games-Calculated.csv' all_data = pd.read_csv(games_csv, header=None, names=column_names) all_data.head() #------------------------------------------------------------------------------------------------------------# ### 2.0 SPLIT DATASET ---- # Drop the columns that we are NOT going to train on all_data.drop(['Date','HomeTeam','HomeScore','AwayTeam','AwayScore'], axis=1, inplace=True) all_data.tail() #Break it into 80/20 splits train = all_data.sample(frac=0.8, random_state=0) test = all_data.drop(train.index) print('Training Size: %s' % train.shape[0]) print('Testing Size: %s' % test.shape[0]) #Create the labels train_labels = train.pop('Result') test_labels = test.pop('Result') # Standardize the train and test features sc = StandardScaler() train_data = pd.DataFrame(sc.fit_transform(train)) test_data = pd.DataFrame(sc.transform(test)) train_data.columns = train.columns test_data.columns = test.columns train_data.describe() test_data.describe() #------------------------------------------------------------------------------------------------------------# ### 3.0 NEURAL NETWORK GRID---- def build_model(hp): model = keras.Sequential() for i in range(hp.Int('num_layers', 1, 6)): model.add(layers.Dense(units=hp.Int('units_' + str(i), min_value = 8, max_value = 32, step = 4), activation = hp.Choice('dense_activation', values = ['relu', 'tanh', 'sigmoid']))) model.add(layers.Dropout(hp.Float('dropout', min_value=0.01, max_value=0.2,step=0.02))) model.add(layers.Dense(1)) model.compile( optimizer = keras.optimizers.Adam( hp.Choice('learning_rate', [0.0001, 0.001, 0.01, 0.1])), loss = keras.losses.MeanSquaredError(), metrics = keras.metrics.MeanAbsoluteError()) return model tuner = RandomSearch( build_model, objective = 'val_loss', max_trials = 10, executions_per_trial = 3, overwrite = True ) tuner.search_space_summary() tuner.search(train_data, train_labels, epochs = 20, validation_data=(test_data, test_labels)) tuner.results_summary() # get bets model best_model = tuner.get_best_models(num_models=1)[0] # get the optimal hyperparameters best_hps = tuner.get_best_hyperparameters(num_trials = 1)[0] print(f""" The hyperparameter search is complete. - optimal number of units in the 0 layer is {best_hps.get('units_0')} - optimal number of units in the 1 densely-connected layer is {best_hps.get('units_1')} - optimal number of units in the 2 densely-connected layer is {best_hps.get('units_2')} - optimal number of units in the 3 densely-connected layer is {best_hps.get('units_3')} - optimal number of units in the 4 densely-connected layer is {best_hps.get('units_4')} - optimal number of units in the 5 densely-connected layer is {best_hps.get('units_5')} - optimal activation is is {best_hps.get('dense_activation')} - optimal dropout is {best_hps.get('dropout')} - the optimal learning rate for the optimizer is {best_hps.get('learning_rate')}. """) # Build the model with the optimal hyperparameters and train it on the data model = tuner.hypermodel.build(best_hps) history = model.fit(train_data, train_labels, epochs=20, validation_data=(test_data, test_labels), verbose=True # ,callbacks= [monitor_val_loss] ) model.summary() # Test the network against your testing data set mae, mse = model.evaluate(test_data, test_labels) def plot_history(history): plt.figure() plt.xlabel('Epoch') plt.ylabel('Mean Absolute Error') plt.plot(history['epoch'], history['mean_absolute_error'], label='Train Mean Absolute Error') plt.plot(history['epoch'], history['val_mean_absolute_error'], label = 'Val Mean Absolute Error') plt.legend() #plt.ylim([0,1]) plt.show() # Check the results # Create a DataFrame from the output from the fit method hist = pd.DataFrame(history.history) # Create an epoch column and set it to the epoch index hist['epoch'] = history.epoch hist.tail() plot_history(hist)<file_sep>#------------------------------------------------------------------------------------------------------------# ### 1.0 LOAD LIBRARY'S ---- import os import sys import pandas as pd import numpy as np pd.set_option('display.max_rows', 10) pd.set_option('display.max_columns', 10) pd.set_option('display.width', 100) # Import the sequential model and dense layer from keras.models import Sequential from keras.layers import Dense from keras import models from tensorflow import keras from tensorflow.keras import layers # Import seaborn import seaborn as sns import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler pd.set_option('display.max_rows', 10) pd.set_option('display.max_columns', 10) pd.set_option('display.width', 100) np.set_printoptions(suppress=True) pd.set_option('display.float_format', lambda x: '%.5f' % x) # Workflow # 1.Create the training and testing datasets. # Typically, training is either 70% or 80% of the # total dataset. # 2. Train the neural network against your training data and # validate against your testing data. # 3. Graph the results to validate that you are getting # closer to your desired results. ### set header for datasets columns_games_df = ['Date','HomeTeam','HomeScore','AwayTeam','AwayScore', 'HomeScoreAverage', 'HomeDefenseAverage', 'AwayScoreAverage', 'AwayDefenseAverage', 'Result'] ### change `DATA_DIR` to the location where movielens-20m dataset sits DATA_DIR = 'C:/Users/Guest01/Documents/github_projects/predict_basketball_scores/data' df_games = pd.read_csv(os.path.join(DATA_DIR, 'Games-Calculated.csv'), header=None, names=columns_games_df) print(df_games) #------------------------------------------------------------------------------------------------------------# ### 2.0 SPLIT DATASET ---- train, test = train_test_split(df_games, test_size=0.2, random_state=1234) y_train = train.loc[:, ['Result']] train_data = train.loc[:, ['HomeScoreAverage', 'HomeDefenseAverage', 'AwayScoreAverage', 'AwayDefenseAverage']] y_test = test.loc[:, ['Result']] test_data = test.loc[:, ['HomeScoreAverage', 'HomeDefenseAverage', 'AwayScoreAverage', 'AwayDefenseAverage']] # standardize the train and test features sc = StandardScaler() x_train = pd.DataFrame(sc.fit_transform(train_data)) x_test = pd.DataFrame(sc.transform(test_data)) x_train.columns = train_data.columns x_test.columns = test_data.columns x_train.describe() x_test.describe() #------------------------------------------------------------------------------------------------------------# ### 3.0 NEURAL NETWORK ---- # Create a sequential model model = Sequential() # Add dense layers model.add(Dense(64, input_shape=(x_train.shape[1],), activation = 'relu')) model.add(Dense(32, activation = 'relu')) model.add(Dense(32, activation = 'relu')) model.add(Dense(1)) model.summary() # Compile your model model.compile(optimizer="adam", loss="mse", metrics=['mae']) # Train the model history = model.fit(x = x_train, y = y_train, validation_split=0.2, epochs = 100, batch_size = 92, shuffle=True, verbose = True) print(history.history.keys()) # Plot train vs test loss per epoch plt.figure() plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'validation'], loc='upper left') plt.show() # Plot train vs test mae per epoch plt.figure() plt.plot(history.history['mae']) plt.plot(history.history['val_mae']) plt.title('Model mae') plt.ylabel('Mae') plt.xlabel('Epoch') plt.legend(['train', 'validation'], loc='upper left') plt.show() # Evaluate your model's accuracy on the test data mae = model.evaluate(x_test, y_test)[1] mae <file_sep>#------------------------------------------------------------------------------------------------------------# ### 1.0 LOAD LIBRARY'S ---- import os, sys import pandas as pd import numpy as np import dateutil import re # Workflow # 1. Take the Teams and Games CSV files and load them into their own DataFrames. # Don’t forget to include their column names to make everything easier later on. # 2. Clean the data. # Cleaning includes making sure all of the team names match # (Ex. St Joe vs St. Joe) between the Teams and Games DataFrames. # 3. Prepare the data for processing by creating columns that # we can train against. # Get creative. Try and think of data points that make sense with # respect to basketball. For example, home court is a very real thing. # What can you create that will let the network use that to learn? # 4. Save the output from your added columns to # Games-Calculated.csv. ### set header for datasets columns_games_df = ['Date','HomeTeam','HomeScore','AwayTeam','AwayScore'] columns_teams_df = ['Conference','Team'] ### change `DATA_DIR` to the location where movielens-20m dataset sits games_csv = 'https://liveproject-resources.s3.amazonaws.com/other/deeplearningbasketballscores/Games.csv' games = pd.read_csv(games_csv, header=None, names=columns_games_df) teams_csv = 'https://liveproject-resources.s3.amazonaws.com/other/deeplearningbasketballscores/Teams.csv' teams = pd.read_csv(teams_csv, header=None, names=columns_teams_df) games.head() teams.head() ### remove any games without a score games = games.drop( games[(games['HomeScore'] == 0)].index ) games = games.drop( games[(games['AwayScore'] == 0)].index ) # ### clean strings # games['HomeTeam'] = games['HomeTeam'].str.replace('&amp;', '&') # games['AwayTeam'] = games['AwayTeam'].str.replace('&amp;', '&') # games['HomeTeam'] = games['HomeTeam'].str.replace('&#039;', "'") # games['AwayTeam'] = games['AwayTeam'].str.replace('&#039;', "'") ### break the Games DataFrame into seasons s2015 = games[(games['Date'] > '2015-11-01') & (games['Date'] < '2016-04-15')].copy() s2016 = games[(games['Date'] > '2016-11-01') & (games['Date'] < '2017-04-15')].copy() s2017 = games[(games['Date'] > '2017-11-01') & (games['Date'] < '2018-04-15')].copy() s2018 = games[(games['Date'] > '2018-11-01') & (games['Date'] < '2019-04-15')].copy() print('2015 (%s): %s - %s' % (s2015.shape[0],np.min(s2015.Date),np.max(s2015.Date))) print('2016 (%s): %s - %s' % (s2016.shape[0],np.min(s2016.Date),np.max(s2016.Date))) print('2017 (%s): %s - %s' % (s2017.shape[0],np.min(s2017.Date),np.max(s2017.Date))) print('2018 (%s): %s - %s' % (s2018.shape[0],np.min(s2018.Date),np.max(s2018.Date))) ### Clean the team names if they don't match the Teams entry # games['away'] = games['away'].str.replace('.', "") # games['home'] = games['home'].str.replace('.;', "") def RenameTeams(df_games, column_name): df_games.loc[ df_games[column_name] == 'A&M-Corpus Chris' , column_name ] = 'Texas A&M-CC' df_games.loc[ df_games[column_name] == 'Alabama St.' , column_name ] = 'Alabama State' df_games.loc[ df_games[column_name] == 'Albany (NY)' , column_name ] = 'Albany' df_games.loc[ df_games[column_name] == 'Alcorn St.' , column_name ] = 'Alcorn State' df_games.loc[ df_games[column_name] == 'American' , column_name ] = 'American University' df_games.loc[ df_games[column_name] == 'Appalachian St.' , column_name ] = 'Appalachian State' df_games.loc[ df_games[column_name] == 'Arizona St.' , column_name ] = 'Arizona State' df_games.loc[ df_games[column_name] == 'Army West Point' , column_name ] = 'Army' df_games.loc[ df_games[column_name] == 'Ark.-Pine Bluff' , column_name ] = 'Arkansas-Pine Bluff' df_games.loc[ df_games[column_name] == 'UALR' , column_name ] = 'Arkansas-Little Rock' df_games.loc[ df_games[column_name] == 'Little Rock' , column_name ] = 'Arkansas-Little Rock' df_games.loc[ df_games[column_name] == 'Arkansas St.' , column_name ] = 'Arkansas State' df_games.loc[ df_games[column_name] == 'Ball St.' , column_name ] = 'Ball State' df_games.loc[ df_games[column_name] == 'Boise St.' , column_name ] = 'Boise State' df_games.loc[ df_games[column_name] == 'Boston U.' , column_name ] = 'Boston University' df_games.loc[ df_games[column_name] == 'Cal Baptist' , column_name ] = 'California Baptist' df_games.loc[ df_games[column_name] == 'Charleston So.' , column_name ] = 'Charleston Southern' df_games.loc[ df_games[column_name] == 'Cent. Conn. St.' , column_name ] = 'Central Connecticut State' df_games.loc[ df_games[column_name] == 'Central Conn. St.' , column_name ] = 'Central Connecticut State' df_games.loc[ df_games[column_name] == 'Central Mich.' , column_name ] = 'Central Michigan' df_games.loc[ df_games[column_name] == 'Col. of Charleston' , column_name ] = 'Charleston' df_games.loc[ df_games[column_name] == 'Chicago St.' , column_name ] = 'Chicago State' df_games.loc[ df_games[column_name] == 'Cleveland St.' , column_name ] = 'Cleveland State' df_games.loc[ df_games[column_name] == 'Coastal Caro.' , column_name ] = 'Coastal Carolina' df_games.loc[ df_games[column_name] == 'Colorado St.' , column_name ] = 'Colorado State' df_games.loc[ df_games[column_name] == 'Coppin St.' , column_name ] = 'Coppin State' df_games.loc[ df_games[column_name] == 'Bakersfield' , column_name ] = 'Cal State Bakersfield' df_games.loc[ df_games[column_name] == 'CSU Bakersfield' , column_name ] = 'Cal State Bakersfield' df_games.loc[ df_games[column_name] == 'Bryant' , column_name ] = 'Bryant University' df_games.loc[ df_games[column_name] == 'Cal St. Fullerton' , column_name ] = 'Cal State Fullerton' df_games.loc[ df_games[column_name] == 'CSU Fullerton' , column_name ] = 'Cal State Fullerton' df_games.loc[ df_games[column_name] == 'CSUN' , column_name ] = 'Cal State Northridge' df_games.loc[ df_games[column_name] == 'Cal St. Northridge' , column_name ] = 'Cal State Northridge' df_games.loc[ df_games[column_name] == 'Central Ark.' , column_name ] = 'Central Arkansas' df_games.loc[ df_games[column_name] == 'Delaware St.' , column_name ] = 'Delaware State' df_games.loc[ df_games[column_name] == 'Detroit' , column_name ] = 'Detroit Mercy' df_games.loc[ df_games[column_name] == 'East Tenn. St.' , column_name ] = 'East Tennessee State' df_games.loc[ df_games[column_name] == 'Eastern Ill.' , column_name ] = 'Eastern Illinois' df_games.loc[ df_games[column_name] == 'Eastern Ky.' , column_name ] = 'Eastern Kentucky' df_games.loc[ df_games[column_name] == 'Eastern Mich.' , column_name ] = 'Eastern Michigan' df_games.loc[ df_games[column_name] == 'Eastern Wash.' , column_name ] = 'Eastern Washington' df_games.loc[ df_games[column_name] == "<NAME>" , column_name ] = '<NAME>' df_games.loc[ df_games[column_name] == 'FGCU' , column_name ] = 'Florida Gulf Coast' df_games.loc[ df_games[column_name] == 'FIU' , column_name ] = 'Florida International' df_games.loc[ df_games[column_name] == 'Fla. Atlantic' , column_name ] = 'Florida Atlantic' df_games.loc[ df_games[column_name] == 'Florida St.' , column_name ] = 'Florida State' df_games.loc[ df_games[column_name] == 'Fresno St.' , column_name ] = 'Fresno State' df_games.loc[ df_games[column_name] == 'Fort Wayne' , column_name ] = 'Purdue Fort Wayne' df_games.loc[ df_games[column_name] == 'IPFW' , column_name ] = 'Purdue Fort Wayne' df_games.loc[ df_games[column_name] == 'Ga. Southern' , column_name ] = 'Georgia Southern' df_games.loc[ df_games[column_name] == 'Georgia St.' , column_name ] = 'Georgia State' df_games.loc[ df_games[column_name] == 'Geo. Washington' , column_name ] = 'Ge<NAME>' df_games.loc[ df_games[column_name] == 'Grambling' , column_name ] = 'Grambling State' df_games.loc[ df_games[column_name] == 'Humboldt St.' , column_name ] = 'Humboldt State' df_games.loc[ df_games[column_name] == 'Idaho St.' , column_name ] = 'Idaho State' df_games.loc[ df_games[column_name] == 'Illinois St.' , column_name ] = 'Illinois State' df_games.loc[ df_games[column_name] == 'Iowa St.' , column_name ] = 'Iowa State' df_games.loc[ df_games[column_name] == 'Indiana St.' , column_name ] = 'Indiana State' df_games.loc[ df_games[column_name] == 'Jackson St.' , column_name ] = 'Jackson State' df_games.loc[ df_games[column_name] == 'Jacksonville St.' , column_name ] = 'Jacksonville State' df_games.loc[ df_games[column_name] == 'Kansas St.' , column_name ] = 'Kansas State' df_games.loc[ df_games[column_name] == 'Kennesaw St.' , column_name ] = 'Kennesaw State' df_games.loc[ df_games[column_name] == 'Kent St.' , column_name ] = 'Kent State' df_games.loc[ df_games[column_name] == 'Louisiana' , column_name ] = 'Louisiana-Lafayette' df_games.loc[ df_games[column_name] == 'Lamar University' , column_name ] = 'Lamar' df_games.loc[ df_games[column_name] == 'La.-Monroe' , column_name ] = 'Louisiana-Monroe' df_games.loc[ df_games[column_name] == 'Long Beach St.' , column_name ] = 'Long Beach State' df_games.loc[ df_games[column_name] == 'Long Island' , column_name ] = 'LIU Brooklyn' df_games.loc[ df_games[column_name] == 'LMU' , column_name ] = 'Loyola Marymount' df_games.loc[ df_games[column_name] == 'Loyola Chicago' , column_name ] = 'Loyola (IL)' df_games.loc[ df_games[column_name] == 'Loyola Maryland' , column_name ] = 'Loyola (MD)' df_games.loc[ df_games[column_name] == 'Loyola (Md.)' , column_name ] = 'Loyola (MD)' df_games.loc[ df_games[column_name] == 'UMES' , column_name ] = 'Maryland-Eastern Shore' df_games.loc[ df_games[column_name] == 'Miami (Fla.)' , column_name ] = 'Miami (FL)' df_games.loc[ df_games[column_name] == 'Miami (Ohio)' , column_name ] = 'Miami (OH)' df_games.loc[ df_games[column_name] == "Mt. St. Mary's" , column_name ] = "Mount St Mary's" df_games.loc[ df_games[column_name] == 'Mass.-Lowell' , column_name ] = 'Massachusetts-Lowell' df_games.loc[ df_games[column_name] == 'McNeese' , column_name ] = 'McNeese State' df_games.loc[ df_games[column_name] == 'McNeese ' , column_name ] = 'McNeese State' df_games.loc[ df_games[column_name] == 'McNeese St.' , column_name ] = 'McNeese State' df_games.loc[ df_games[column_name] == 'Middle Tenn.' , column_name ] = 'Middle Tennessee' df_games.loc[ df_games[column_name] == 'Mississippi St.' , column_name ] = 'Mississippi State' df_games.loc[ df_games[column_name] == 'Mississippi Val.' , column_name ] = 'Mississippi Valley State' df_games.loc[ df_games[column_name] == 'Mich. St. ' , column_name ] = 'Michigan State' df_games.loc[ df_games[column_name] == 'Michigan St.' , column_name ] = 'Michigan State' df_games.loc[ df_games[column_name] == 'Mississippi' , column_name ] = 'Ole Miss' df_games.loc[ df_games[column_name] == 'Missouri St.' , column_name ] = 'Missouri State' df_games.loc[ df_games[column_name] == 'Montana St.' , column_name ] = 'Montana State' df_games.loc[ df_games[column_name] == 'Morehead St.' , column_name ] = 'Morehead State' df_games.loc[ df_games[column_name] == 'Morgan St.' , column_name ] = 'Morgan State' df_games.loc[ df_games[column_name] == 'Murray St.' , column_name ] = 'Murray State' df_games.loc[ df_games[column_name] == 'N.C. A&T' , column_name ] = 'North Carolina A&T' df_games.loc[ df_games[column_name] == 'N.C. Central' , column_name ] = 'North Carolina Central' df_games.loc[ df_games[column_name] == 'New Mexico St.' , column_name ] = 'New Mexico State' df_games.loc[ df_games[column_name] == 'NC State' , column_name ] = 'North Carolina State' df_games.loc[ df_games[column_name] == 'North Carolina St.' , column_name ] = 'North Carolina State' df_games.loc[ df_games[column_name] == 'North Dakota St.' , column_name ] = 'North Dakota State' df_games.loc[ df_games[column_name] == 'Northern Ariz.' , column_name ] = 'Northern Arizona' df_games.loc[ df_games[column_name] == 'Northern Colo.' , column_name ] = 'Northern Colorado' df_games.loc[ df_games[column_name] == 'Northern Ill.' , column_name ] = 'Northern Illinois' df_games.loc[ df_games[column_name] == "N'western St." , column_name ] = "Northwestern State" df_games.loc[ df_games[column_name] == 'Northwestern St.' , column_name ] = "Northwestern State" df_games.loc[ df_games[column_name] == 'Nicholls St.' , column_name ] = 'Nicholls State' df_games.loc[ df_games[column_name] == 'Norfolk St.' , column_name ] = 'Norfolk State' df_games.loc[ df_games[column_name] == 'Northern Ky.' , column_name ] = 'Northern Kentucky' df_games.loc[ df_games[column_name] == 'Ohio St.' , column_name ] = 'Ohio State' df_games.loc[ df_games[column_name] == 'Ohio St. ' , column_name ] = 'Ohio State' df_games.loc[ df_games[column_name] == 'Oklahoma St.' , column_name ] = 'Oklahoma State' df_games.loc[ df_games[column_name] == 'Oregon St.' , column_name ] = 'Oregon State' df_games.loc[ df_games[column_name] == 'Neb. Omaha' , column_name ] = 'Nebraska-Omaha' df_games.loc[ df_games[column_name] == 'Omaha' , column_name ] = 'Nebraska-Omaha' df_games.loc[ df_games[column_name] == 'Penn' , column_name ] = 'Pennsylvania' df_games.loc[ df_games[column_name] == 'Penn St.' , column_name ] = 'Penn State' df_games.loc[ df_games[column_name] == 'Prairie View' , column_name ] = 'Prairie View A&M' df_games.loc[ df_games[column_name] == 'Portland St.' , column_name ] = 'Portland State' df_games.loc[ df_games[column_name] == 'S.C. Upstate' , column_name ] = 'USC Upstate' df_games.loc[ df_games[column_name] == 'S. Carolina St.' , column_name ] = 'South Carolina State' df_games.loc[ df_games[column_name] == 'South Carolina St.' , column_name ] = 'South Carolina State' df_games.loc[ df_games[column_name] == 'Sacramento St.' , column_name ] = 'Sacramento State' df_games.loc[ df_games[column_name] == 'Sam Houston St.' , column_name ] = 'Sam Houston State' df_games.loc[ df_games[column_name] == 'San Diego St.' , column_name ] = 'San Diego State' df_games.loc[ df_games[column_name] == 'San Jose St.' , column_name ] = 'San Jose State' df_games.loc[ df_games[column_name] == 'Savannah St.' , column_name ] = 'Savannah State' df_games.loc[ df_games[column_name] == 'Seattle U' , column_name ] = 'Seattle' df_games.loc[ df_games[column_name] == 'SFA' , column_name ] = '<NAME>' df_games.loc[ df_games[column_name] == '<NAME>' , column_name ] = '<NAME>' df_games.loc[ df_games[column_name] == 'SIU Edwardsville' , column_name ] = 'SIU-Edwardsville' df_games.loc[ df_games[column_name] == 'SIUE' , column_name ] = 'SIU-Edwardsville' df_games.loc[ df_games[column_name] == 'South Ala.' , column_name ] = 'South Alabama' df_games.loc[ df_games[column_name] == 'South Dakota St.' , column_name ] = 'South Dakota State' df_games.loc[ df_games[column_name] == 'South Fla.' , column_name ] = 'South Florida' df_games.loc[ df_games[column_name] == 'Southern Ill.' , column_name ] = 'Southern Illinois' df_games.loc[ df_games[column_name] == 'Southeast Mo. St.' , column_name ] = 'Southeast Missouri State' df_games.loc[ df_games[column_name] == 'Southeastern La.' , column_name ] = 'Southeastern Louisiana' df_games.loc[ df_games[column_name] == 'Southern Miss.' , column_name ] = 'Southern Miss' df_games.loc[ df_games[column_name] == 'Southern U.' , column_name ] = 'Southern University' df_games.loc[ df_games[column_name] == 'Southern Univ.' , column_name ] = 'Southern University' df_games.loc[ df_games[column_name] == "St. Bonaventure" , column_name ] = "St Bonaventure" df_games.loc[ df_games[column_name] == "St. Francis (B'klyn)" , column_name ] = "St Francis (BKN)" df_games.loc[ df_games[column_name] == 'St. Francis (NY)' , column_name ] = "St Francis (BKN)" df_games.loc[ df_games[column_name] == 'St. Francis (PA)' , column_name ] = "St Francis (PA)" df_games.loc[ df_games[column_name] == 'St. Francis (Pa.)' , column_name ] = "St Francis (PA)" df_games.loc[ df_games[column_name] == "Saint Joseph's" , column_name ] = "Saint Joseph's (PA)" df_games.loc[ df_games[column_name] == "St. Mary's (CA)" , column_name ] = "Saint Mary's" df_games.loc[ df_games[column_name] == "St. Mary's (Cal.)" , column_name ] = "Saint Mary's" df_games.loc[ df_games[column_name] == "St. Peter's" , column_name ] = "St Peter's" df_games.loc[ df_games[column_name] == "St. John's (NY)" , column_name ] = "St John's" df_games.loc[ df_games[column_name] == "St. John's " , column_name ] = "St John's" df_games.loc[ df_games[column_name] == 'Tennessee St.' , column_name ] = 'Tennessee State' df_games.loc[ df_games[column_name] == 'Texas A&M-C.C.' , column_name ] = 'Texas A&M-CC' df_games.loc[ df_games[column_name] == 'Texas St.' , column_name ] = 'Texas State' df_games.loc[ df_games[column_name] == 'UC Santa Barbara' , column_name ] = 'UC Santa Barb.' df_games.loc[ df_games[column_name] == 'Ill.-Chicago' , column_name ] = 'UIC' df_games.loc[ df_games[column_name] == 'Md.-East. Shore' , column_name ] = 'Maryland-Eastern Shore' df_games.loc[ df_games[column_name] == 'UNCG' , column_name ] = 'UNC Greensboro' df_games.loc[ df_games[column_name] == 'UNCW' , column_name ] = 'North Carolina-Wilmington' df_games.loc[ df_games[column_name] == 'UNC Wilmington' , column_name ] = 'North Carolina-Wilmington' df_games.loc[ df_games[column_name] == 'Southern California', column_name ] = 'USC' df_games.loc[ df_games[column_name] == 'UConn' , column_name ] = 'Connecticut' df_games.loc[ df_games[column_name] == 'UC Santa Barb.' , column_name ] = 'UC Santa Barbara' df_games.loc[ df_games[column_name] == 'UIC' , column_name ] = 'Illinois-Chicago' df_games.loc[ df_games[column_name] == 'UNI' , column_name ] = 'Northern Iowa' df_games.loc[ df_games[column_name] == 'UT Arlington' , column_name ] = 'Texas-Arlington' df_games.loc[ df_games[column_name] == 'UT Arlington ' , column_name ] = 'Texas-Arlington' df_games.loc[ df_games[column_name] == 'UT Martin' , column_name ] = 'Tennessee-Martin' df_games.loc[ df_games[column_name] == 'UTRGV' , column_name ] = 'Texas Rio Grande Valley' df_games.loc[ df_games[column_name] == 'Utah St.' , column_name ] = 'Utah State' df_games.loc[ df_games[column_name] == 'VCU' , column_name ] = 'Virginia Commonwealth' df_games.loc[ df_games[column_name] == 'VMI' , column_name ] = 'Virginia Military' df_games.loc[ df_games[column_name] == 'Washington St.' , column_name ] = 'Washington State' df_games.loc[ df_games[column_name] == 'Weber St.' , column_name ] = 'Weber State' df_games.loc[ df_games[column_name] == 'Western Caro.' , column_name ] = 'Western Carolina' df_games.loc[ df_games[column_name] == 'Western Ill.' , column_name ] = 'Western Illinois' df_games.loc[ df_games[column_name] == 'Western Ky.' , column_name ] = 'Western Kentucky' df_games.loc[ df_games[column_name] == 'Western Mich.' , column_name ] = 'Western Michigan' df_games.loc[ df_games[column_name] == 'Wichita St.' , column_name ] = 'Wichita State' df_games.loc[ df_games[column_name] == 'Wright St.' , column_name ] = 'Wright State' df_games.loc[ df_games[column_name] == 'Youngstown St.' , column_name ] = 'Youngstown State' RenameTeams(s2015,'HomeTeam') RenameTeams(s2015,'AwayTeam') RenameTeams(s2016,'HomeTeam') RenameTeams(s2016,'AwayTeam') RenameTeams(s2017,'HomeTeam') RenameTeams(s2017,'AwayTeam') RenameTeams(s2018,'HomeTeam') RenameTeams(s2018,'AwayTeam') ### calculate different statistics # team's scoring average at home # team's scoring average away # team's home defensive average # team's away defensive average # https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.expanding.html # expanding().mean() Documentation gives us a rolling average. def CalculateScores(df): for index, row in teams.iterrows(): ## Home Team Stats df.loc[ df['HomeTeam'] == row.Team, 'HomeScoreAverage' ] = df[(df['HomeTeam'] == row.Team)]['HomeScore'].expanding().mean() df.loc[ df['HomeTeam'] == row.Team, 'HomeDefenseAverage' ] = df[(df['HomeTeam'] == row.Team)]['AwayScore'].expanding().mean() ## Away Team Stats df.loc[ df['AwayTeam'] == row.Team, 'AwayScoreAverage' ] = df[(df['AwayTeam'] == row.Team)]['AwayScore'].expanding().mean() df.loc[ df['AwayTeam'] == row.Team, 'AwayDefenseAverage' ] = df[(df['AwayTeam'] == row.Team)]['HomeScore'].expanding().mean() CalculateScores(s2015) CalculateScores(s2016) CalculateScores(s2017) CalculateScores(s2018) ### Combine the data, remove NA values, and calculate the results all_data = pd.concat([s2015,s2016,s2017,s2018]) #Remove NAN values print(len(all_data)) all_data.dropna(inplace=True) print(len(all_data)) all_data['Result'] = games.HomeScore - games.AwayScore # Save both DataFrames to csv files all_data.to_csv('C:/Users/Guest01/Documents/github_projects/predict_basketball_scores/data/all_data.csv') <file_sep>#------------------------------------------------------------------------------------------------------------# ### 1.0 LOAD LIBRARY'S ---- from __future__ import absolute_import, division, print_function from tensorflow import keras from tensorflow.keras import layers from kerastuner.tuners import RandomSearch import pandas as pd import numpy as np import matplotlib.pyplot as plt from IPython.display import SVG from keras.utils.vis_utils import model_to_dot from sklearn.preprocessing import StandardScaler pd.set_option('display.max_rows', 10) pd.set_option('display.max_columns', 10) pd.set_option('display.width', 100) np.set_printoptions(suppress=True) pd.set_option('display.float_format', lambda x: '%.5f' % x) seed(42) tensorflow.random.set_seed(42) # Workflow # Start with your original network and check the mean absolute error that # you get from running the evaluate method on your testing data. # Create a series of networks that try and beat those results. Check the # notes section for a recommendation on the process. # Alter the network’s layers, neurons, optimizers, activation functions, # loss function, and so on. # Repeat until you have a satisfactory result. # Download your best model in h5 format. # Load the data set from the last milestone 1 column_names = ['Date','HomeTeam','HomeScore','AwayTeam','AwayScore', 'HomeScoreAverage','HomeDefenseAverage','AwayScoreAverage','AwayDefenseAverage', 'Result'] games_csv = 'https://liveproject-resources.s3.amazonaws.com/other/deeplearningbasketballscores/Games-Calculated.csv' all_data = pd.read_csv(games_csv, header=None, names=column_names) all_data.head() #------------------------------------------------------------------------------------------------------------# ### 2.0 SPLIT DATASET ---- # Drop the columns that we are NOT going to train on all_data.drop(['Date','HomeTeam','HomeScore','AwayTeam','AwayScore'], axis=1, inplace=True) all_data.tail() #Break it into 80/20 splits train = all_data.sample(frac=0.8, random_state=0) test = all_data.drop(train.index) print('Training Size: %s' % train.shape[0]) print('Testing Size: %s' % test.shape[0]) #Create the labels train_labels = train.pop('Result') test_labels = test.pop('Result') # Standardize the train and test features sc = StandardScaler() train_data = pd.DataFrame(sc.fit_transform(train)) test_data = pd.DataFrame(sc.transform(test)) train_data.columns = train.columns test_data.columns = test.columns train_data.describe() test_data.describe() #------------------------------------------------------------------------------------------------------------# ### 3.0 NEURAL NETWORK---- # Milestone 3 Network def Build_Model_Milestone3(): model = keras.models.Sequential([ keras.layers.Dense(32, activation='relu', input_shape=[4]), keras.layers.Dense(32, activation='relu'), keras.layers.Dense(1) ]) opt = keras.optimizers.RMSprop() m = [ keras.metrics.MeanAbsoluteError(), keras.metrics.Accuracy(), keras.metrics.MeanSquaredError() ] l = keras.losses.MeanSquaredError() model.compile(loss=l, optimizer=opt, metrics=m) return model m3 = Build_Model_Milestone3() m3_history = m3.fit(train_data, train_labels, epochs=100, validation_split=0.2, verbose=0) _, m3_mean_absolute_error, _, _ = m3.evaluate(test_data, test_labels,verbose=0) print('Milestone 3 model: %s' % m3_mean_absolute_error) # Less Neutrons # I started with 32 neutrons in each layer. I am going to adjust that down to 24, 12, and 8. def Build_Model_24Neutrons(): model = keras.models.Sequential([ keras.layers.Dense(24, activation='relu', input_shape=[4]), keras.layers.Dense(24, activation='relu'), keras.layers.Dense(1) ]) opt = keras.optimizers.RMSprop() m = [ keras.metrics.MeanAbsoluteError(), keras.metrics.Accuracy(), keras.metrics.MeanSquaredError() ] l = keras.losses.MeanSquaredError() model.compile(loss=l, optimizer=opt, metrics=m) return model def Build_Model_12Neutrons(): model = keras.models.Sequential([ keras.layers.Dense(12, activation='relu', input_shape=[4]), keras.layers.Dense(12, activation='relu'), keras.layers.Dense(1) ]) opt = keras.optimizers.RMSprop() m = [ keras.metrics.MeanAbsoluteError(), keras.metrics.Accuracy(), keras.metrics.MeanSquaredError() ] l = keras.losses.MeanSquaredError() model.compile(loss=l, optimizer=opt, metrics=m) return model def Build_Model_8Neutrons(): model = keras.models.Sequential([ keras.layers.Dense(8, activation='relu', input_shape=[4]), keras.layers.Dense(8, activation='relu'), keras.layers.Dense(1) ]) opt = keras.optimizers.RMSprop() m = [ keras.metrics.MeanAbsoluteError(), keras.metrics.Accuracy(), keras.metrics.MeanSquaredError() ] l = keras.losses.MeanSquaredError() model.compile(loss=l, optimizer=opt, metrics=m) return model # Train the networks m8 = Build_Model_8Neutrons() m8_history = m8.fit(train_data, train_labels, epochs=100, validation_split=0.2, verbose=True) m12 = Build_Model_12Neutrons() m12_history = m12.fit(train_data, train_labels, epochs=100, validation_split=0.2, verbose=True) m24 = Build_Model_24Neutrons() m24_history = m24.fit(train_data, train_labels, epochs=100, validation_split=0.2, verbose=True) # Grab Their Results _, m8_mean_absolute_error, _, _ = m8.evaluate(test_data, test_labels,verbose=0) print('8 Neurons model: %s' % m8_mean_absolute_error) _, m12_mean_absolute_error, _, _ = m12.evaluate(test_data, test_labels,verbose=0) print('12 Neurons model: %s' % m12_mean_absolute_error) _, m24_mean_absolute_error, _, _ = m24.evaluate(test_data, test_labels,verbose=0) print('24 Neurons model: %s' % m24_mean_absolute_error) print('Milestone 3 model: %s' % m3_mean_absolute_error) # Activation Functions # We currently have RELU (rectified linear unit). We will try sigmoid and softmax. def Build_Model_Sigmoid(): model = keras.models.Sequential([ keras.layers.Dense(24, activation='sigmoid', input_shape=[4]), keras.layers.Dense(24, activation='sigmoid'), keras.layers.Dense(1) ]) opt = keras.optimizers.RMSprop() m = [ keras.metrics.MeanAbsoluteError(), keras.metrics.Accuracy(), keras.metrics.MeanSquaredError() ] l = keras.losses.MeanSquaredError() model.compile(loss=l, optimizer=opt, metrics=m) return model def Build_Model_Softmax(): model = keras.models.Sequential([ keras.layers.Dense(24, activation='softmax', input_shape=[4]), keras.layers.Dense(24, activation='softmax'), keras.layers.Dense(1) ]) opt = keras.optimizers.RMSprop() m = [ keras.metrics.MeanAbsoluteError(), keras.metrics.Accuracy(), keras.metrics.MeanSquaredError() ] l = keras.losses.MeanSquaredError() model.compile(loss=l, optimizer=opt, metrics=m) return model # Train the networks msg = Build_Model_Sigmoid() msg_history = msg.fit(train_data, train_labels, epochs=100, validation_split=0.2, verbose=True) msm = Build_Model_Softmax() msm_history = msm.fit(train_data, train_labels, epochs=100, validation_split=0.2, verbose=True) _, msg_mean_absolute_error, _, _ = msg.evaluate(test_data, test_labels,verbose=0) print('Sigmoid model: %s' % msg_mean_absolute_error) _, msm_mean_absolute_error, _, _ = msm.evaluate(test_data, test_labels,verbose=0) print('Softmax model: %s' % msm_mean_absolute_error) print('24 Neuron model: %s' % m24_mean_absolute_error) # Optimizers # We started with RMSProp and we are going to try SDG (stochastic gradient descent), Adam, and Adamax. def Build_Model_SDG(): model = keras.models.Sequential([ keras.layers.Dense(24, activation='relu', input_shape=[4]), keras.layers.Dense(24, activation='relu'), keras.layers.Dense(1) ]) opt = keras.optimizers.SGD() m = [ keras.metrics.MeanAbsoluteError(), keras.metrics.Accuracy(), keras.metrics.MeanSquaredError() ] l = keras.losses.MeanSquaredError() model.compile(loss=l, optimizer=opt, metrics=m) return model def Build_Model_Adam(): model = keras.models.Sequential([ keras.layers.Dense(24, activation='relu', input_shape=[4]), keras.layers.Dense(24, activation='relu'), keras.layers.Dense(1) ]) opt = keras.optimizers.Adam() m = [ keras.metrics.MeanAbsoluteError(), keras.metrics.Accuracy(), keras.metrics.MeanSquaredError() ] l = keras.losses.MeanSquaredError() model.compile(loss=l, optimizer=opt, metrics=m) return model def Build_Model_Adamax(): model = keras.models.Sequential([ keras.layers.Dense(24, activation='relu', input_shape=[4]), keras.layers.Dense(24, activation='relu'), keras.layers.Dense(1) ]) opt = keras.optimizers.Adamax() m = [ keras.metrics.MeanAbsoluteError(), keras.metrics.Accuracy(), keras.metrics.MeanSquaredError() ] l = keras.losses.MeanSquaredError() model.compile(loss=l, optimizer=opt, metrics=m) return model # Train the networks sdg = Build_Model_SDG() sdg_history = sdg.fit(train_data, train_labels, epochs=100, validation_split=0.2, verbose=True) adam = Build_Model_Adam() adam_history = adam.fit(train_data, train_labels, epochs=100, validation_split=0.2, verbose=True) ada = Build_Model_Adamax() ada_history = ada.fit(train_data, train_labels, epochs=100, validation_split=0.2, verbose=True) _, sdg_mean_absolute_error, _, _ = sdg.evaluate(test_data, test_labels,verbose=0) print('SDG model: %s' % sdg_mean_absolute_error) _, adam_mean_absolute_error, _, _ = adam.evaluate(test_data, test_labels,verbose=0) print('Adam model: %s' % adam_mean_absolute_error) _, ada_mean_absolute_error, _, _ = ada.evaluate(test_data, test_labels,verbose=0) print('Adamax model: %s' % ada_mean_absolute_error) print('RMSProp model: %s' % m24_mean_absolute_error) # Export h5 Model # We will use the built in Keras save function to export the model #Save the model and all it's weights m24.save('C:/Users/Guest01/Documents/github_projects/predict_basketball_scores/bball/deeplearning-manning.h5') # #Google Colab code to download # from google.colab import files # files.download('deeplearning-manning.h5') <file_sep>#------------------------------------------------------------------------------------------------------------# ### 1.0 LOAD LIBRARY'S ---- from __future__ import absolute_import, division, print_function import tensorflow as tf from tensorflow import keras import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.preprocessing import StandardScaler pd.set_option('display.max_rows', 10) pd.set_option('display.max_columns', 10) pd.set_option('display.width', 100) np.set_printoptions(suppress=True) pd.set_option('display.float_format', lambda x: '%.5f' % x) # Workflow # 1.Create the training and testing datasets. # Typically, training is either 70% or 80% of the # total dataset. # 2. Train the neural network against your training data and # validate against your testing data. # 3. Graph the results to validate that you are getting # closer to your desired results. # Load the data set from the last milestone 1 column_names = ['Date','HomeTeam','HomeScore','AwayTeam','AwayScore', 'HomeScoreAverage','HomeDefenseAverage','AwayScoreAverage','AwayDefenseAverage', 'Result'] games_csv = 'https://liveproject-resources.s3.amazonaws.com/other/deeplearningbasketballscores/Games-Calculated.csv' all_data = pd.read_csv(games_csv, header=None, names=column_names) all_data.head() #------------------------------------------------------------------------------------------------------------# ### 2.0 SPLIT DATASET ---- # Create the Train/Test/Validate data sets # All about data # When training a network we need to send in data for it to learn. We can't then use the # same data to test if it is learning. It would be like working a problem in school and # then get that same problem on the test. All it proves is you know that data. We need # the model to generalize the data versus knowing the actual data. # Generalization is a term used to describe the model's ability to understand new data # it hasn't seen before. In this project, we need to generalize to all games in the future # versus the individual games in the past. When the model doesn't generalize it gets # into a scenario where it overfits. # Overfitting is a term used to describe when the model only learns the data it has # versus the new data. You can see this visually in the graph of the errors resulting # from training. You will see that your training errors will decrease while your # validation errors will start to increase again. # Splits # As stated above, we need to ensure we don't overfit to the data. To handle this we # need to separate the data into 3 data sets (With the way Keras handles the validation # within the network we only create 2). # In my example, I used 80% of train (which will get split 80/20 for validation) and # 20% for testing. This allows me plenty of randomized data to test my model. # Data Labels # You will notice that I remove the Results column and name those as the labels. The # labels are used as the answers or truth in the network. When the network gets the # data it will then try and predict its own label and compare it versus the correct # label. After they get the error (we use mean square error) it uses an algorithm # called backpropagation to go back through all the weights and biases in the nodes # to attempt to get the answer correct next time. # Data Normalization # At the end of the code I normalize all of the data. The reason for me doing this # is to ensure that the scale of the values are all similiar. If our first input # ranges from 30 to 120 and the second input ranges from 2 to 10 the first input # will have an outsized impact on our learning. # Drop the columns that we are NOT going to train on all_data.drop(['Date','HomeTeam','HomeScore','AwayTeam','AwayScore'], axis=1, inplace=True) all_data.tail() #Break it into 80/20 splits train = all_data.sample(frac=0.8, random_state=0) test = all_data.drop(train.index) print('Training Size: %s' % train.shape[0]) print('Testing Size: %s' % test.shape[0]) #Create the labels train_labels = train.pop('Result') test_labels = test.pop('Result') # # Normalize the data # mean = train.mean(axis=0) # train_data = train - mean # std = train_data.std(axis=0) # train_data /= std # test_data = test - mean # test_data /= std # train_data.describe() # test_data.describe() # Standardize the train and test features sc = StandardScaler() train_data = pd.DataFrame(sc.fit_transform(train)) test_data = pd.DataFrame(sc.transform(test)) train_data.columns = train.columns test_data.columns = test.columns train_data.describe() test_data.describe() #------------------------------------------------------------------------------------------------------------# ### 3.0 NEURAL NETWORK ---- # Create a sequential neural network with 3 dense layers, and compile # Parameters # Sequential (Documantaion): A sequential network runs linearly # through the layers. # Dense (Documentaion): A densely connected network layer. This is the standard # for most neural networks. # Neurons/Units: We set these to 32 to start. This is the dimensionality of the # output space. Since we just want a final score differences we set the last # value to 1. # Input Shape: This is the size of the data you are using to train. In our case, # we have home team score, away team score, home team defense and away team # defense. So, we set this value to 4. # Activation (Documentation): We picked Recified Linear Unit (relu). Using trial # and error you can determine which one is best for your data. There are some # activations that are for specific network results. # Optimizers (Documentation): Optimizers are used during training to try and # find the global optimum which will lead to better results. We chose RMSProp # as a general purpose optimizer. # Metrics (Documentation): This array determines what values are tracked and # returned during training. We will use these to graph our results and determine # how well our model is representing our data. # Loss Function (Documentation): The loss function is what is computed to determine # how good or bad our output matches our expected results. def Build_Model(): model = keras.models.Sequential([ keras.layers.Dense(32, activation='relu', input_shape=(train_data.shape[1],)), keras.layers.Dense(32, activation='relu'), keras.layers.Dense(1) ]) opt = keras.optimizers.RMSprop() m = [ keras.metrics.MeanAbsoluteError(), keras.metrics.Accuracy(), keras.metrics.MeanSquaredError() ] l = keras.losses.MeanSquaredError() model.compile(loss=l, optimizer=opt, metrics=m) return model bballmodel = Build_Model() # This method will be used in place of the normal output. This is cleaner # in my opinion class PrintDoc(keras.callbacks.Callback): def on_epoch_end(self, epoch, logs): if epoch % 10 == 0: print('') print('.', end='') # Model Complexity # I am going to take this section to talk about the complexity of the model # as well as high bias and high variance. # Bias: A model with low model complexity with a high error rate is said to have # high bias. The high bias comes from underfitting the data. # Variance: A model with high complexity with a high error rate is said to have # high variance. The high variance comes from overfitting the data. #------------------------------------------------------------------------------------------------------------# ### 4.0 TRAIN MODEL ---- history = bballmodel.fit(train_data, train_labels, epochs=100, validation_split=0.2, verbose=True # , callbacks=[PrintDoc()] ) # Check the results # Create a DataFrame from the output from the fit method hist = pd.DataFrame(history.history) # Create an epoch column and set it to the epoch index hist['epoch'] = history.epoch hist.tail() # Test the network against your testing data set test_loss, mae, test_acc, mse = bballmodel.evaluate(test_data, test_labels) mae def plot_history(history): plt.figure() plt.xlabel('Epoch') plt.ylabel('Mean Absolute Error') plt.plot(history['epoch'], history['mean_absolute_error'], label='Train Mean Absolute Error') plt.plot(history['epoch'], history['val_mean_absolute_error'], label = 'Val Mean Absolute Error') plt.legend() #plt.ylim([0,1]) plt.show() plot_history(hist) <file_sep>Repo related to using-deep-learning-to-predict-basketball-scores, manning live project <file_sep>#------------------------------------------------------------------------------------------------------------# ### 1.0 LOAD LIBRARY'S ---- import os, sys import pandas as pd import numpy as np import dateutil # Workflow # 1.Create a 4 column DataFrame with 10 rows, the first column being a date # field and the rest numbers. # 2.Fill the first column with the first day of each month for 3 years # (for example: 1/1/2018, 2/1/2018). # 3.Fill the next 2 columns with random numbers. # 4.Fill the 4th column with the difference of the first 2 data columns # (for example: Col3 - Col2). # 5.Break the DataFrame into 3 different DataFrames based on the dates # (for example: 2018, 2019, 2020) ### dates dataframe df_data1 = pd.DataFrame({'date': ['2018-01-01', '2018-02-01', '2018-03-01', '2018-04-01' ,'2019-01-01', '2019-02-01', '2019-03-01' ,'2020-01-01', '2020-02-01', '2020-03-01'] }) ### random numbers dataframe num = np.random.randint(5, 30, size=(10, 2)) df_data2 = pd.DataFrame(num, columns=['random_numbers_1', 'random_numbers_2']) ### merged dataframe df_data = pd.concat([df_data1.reset_index(drop=True), df_data2], axis=1) ### difference column df_data['difference'] = df_data['random_numbers_2'] - df_data['random_numbers_1'] ### add column to date type df_data["date"] = df_data["date"].apply(lambda x: dateutil.parser.parse(x)) ### split by year for m in df_data["date"].dt.to_period("Y").unique(): temp = 'df_data_{}'.format(m) vars()[temp] = df_data[df_data["date"].dt.to_period("Y")==m] <file_sep>#------------------------------------------------------------------------------------------------------------# ### 1.0 LOAD LIBRARY'S ---- from __future__ import absolute_import, division, print_function import tensorflow as tf import tensorflow.keras as keras # Import KerasClassifier from keras scikit learn wrappers from keras.wrappers.scikit_learn import KerasClassifier from sklearn.model_selection import GridSearchCV # Import the early stopping callback from keras.callbacks import EarlyStopping import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.preprocessing import StandardScaler pd.set_option('display.max_rows', 10) pd.set_option('display.max_columns', 10) pd.set_option('display.width', 100) np.set_printoptions(suppress=True) pd.set_option('display.float_format', lambda x: '%.5f' % x) # Workflow # Start with your original network and check the mean absolute error that # you get from running the evaluate method on your testing data. # Create a series of networks that try and beat those results. Check the # notes section for a recommendation on the process. # Alter the network’s layers, neurons, optimizers, activation functions, # loss function, and so on. # Repeat until you have a satisfactory result. # Download your best model in h5 format. # Load the data set from the last milestone 1 column_names = ['Date','HomeTeam','HomeScore','AwayTeam','AwayScore', 'HomeScoreAverage','HomeDefenseAverage','AwayScoreAverage','AwayDefenseAverage', 'Result'] games_csv = 'https://liveproject-resources.s3.amazonaws.com/other/deeplearningbasketballscores/Games-Calculated.csv' all_data = pd.read_csv(games_csv, header=None, names=column_names) all_data.head() #------------------------------------------------------------------------------------------------------------# ### 2.0 SPLIT DATASET ---- # Drop the columns that we are NOT going to train on all_data.drop(['Date','HomeTeam','HomeScore','AwayTeam','AwayScore'], axis=1, inplace=True) all_data.tail() #Break it into 80/20 splits train = all_data.sample(frac=0.8, random_state=0) test = all_data.drop(train.index) print('Training Size: %s' % train.shape[0]) print('Testing Size: %s' % test.shape[0]) #Create the labels train_labels = train.pop('Result') test_labels = test.pop('Result') # Standardize the train and test features sc = StandardScaler() train_data = pd.DataFrame(sc.fit_transform(train)) test_data = pd.DataFrame(sc.transform(test)) train_data.columns = train.columns test_data.columns = test.columns train_data.describe() test_data.describe() #------------------------------------------------------------------------------------------------------------# ### 3.0 NEURAL NETWORK GRID---- # Create hyperparameter options # Define the parameters to try out params = {'activation': ['relu', 'tanh'], 'batch_size': [16, 32, 64], 'epochs': [50], 'learning_rate': [0.0001, 0.001, 0.01, 0.1], 'neurons':[16, 32]} def Build_Model(learning_rate, activation, neurons): # Start neural network model = keras.models.Sequential([ # Add fully connected layer with a XXX activation function keras.layers.Dense(neurons, activation = activation, input_shape=(train_data.shape[1],)), # Add fully connected layer with a XXX activation function keras.layers.Dense(neurons, activation = activation), # Add fully connected layer with a XXX activation function keras.layers.Dense(1) ]) opt = keras.optimizers.Adam(learning_rate=learning_rate) m = [ keras.metrics.MeanAbsoluteError(), keras.metrics.Accuracy(), keras.metrics.MeanSquaredError() ] l = keras.losses.MeanSquaredError() model.compile(loss = l, optimizer = opt, metrics = m) return model # Create a KerasClassifier model = KerasClassifier(build_fn = Build_Model) # Create grid search grid = GridSearchCV(estimator=model, cv=3, param_grid=params) # Fit grid search grid_result = grid.fit(train_data, train_labels) # View hyperparameters of best neural network grid_result.best_params_ # Print results print("Best score: {}".format(grid_result.best_score_ )) print("Best parameters: {}".format(grid_result.best_params_)) #------------------------------------------------------------------------------------------------------------# ### 3.0 NEURAL NETWORK WITH BEST RESULTS---- # Define a callback to monitor val_acc monitor_val_loss = EarlyStopping(monitor='val_loss', patience=5) # Create hyperparameter options # Define the parameters to try out params = {'activation': ['relu'], 'batch_size': [16], 'epochs': [50], 'learning_rate': [0.0001], 'neurons':[16]} def Build_Model(learning_rate, activation, neurons): # Start neural network model = keras.models.Sequential([ # Add fully connected layer with a XXX activation function keras.layers.Dense(neurons, activation = activation, input_shape=(train_data.shape[1],)), # Add fully connected layer with a XXX activation function keras.layers.Dense(neurons, activation = activation), # Add fully connected layer with a XXX activation function keras.layers.Dense(1) ]) opt = keras.optimizers.Adam(learning_rate=learning_rate) m = [ keras.metrics.MeanAbsoluteError(), keras.metrics.Accuracy(), keras.metrics.MeanSquaredError() ] l = keras.losses.MeanSquaredError() model.compile(loss = l, optimizer = opt, metrics = m) return model model = Build_Model(activation = 'relu', learning_rate = 0.0001, neurons = 16) history = model.fit(train_data, train_labels, epochs=50, validation_split=0.2, verbose=True # ,callbacks= [monitor_val_loss] ) # Test the network against your testing data set test_loss, mae, test_acc, mse = model.evaluate(test_data, test_labels) mae def plot_history(history): plt.figure() plt.xlabel('Epoch') plt.ylabel('Mean Absolute Error') plt.plot(history['epoch'], history['mean_absolute_error'], label='Train Mean Absolute Error') plt.plot(history['epoch'], history['val_mean_absolute_error'], label = 'Val Mean Absolute Error') plt.legend() #plt.ylim([0,1]) plt.show() # Check the results # Create a DataFrame from the output from the fit method hist = pd.DataFrame(history.history) # Create an epoch column and set it to the epoch index hist['epoch'] = history.epoch hist.tail() plot_history(hist)
13121de253eb931103821367dda30d963125f6c8
[ "Markdown", "Python" ]
10
Python
PaulCristina/predict_basketball_scores
9e6c60bf97af7ac65c66eb1f60ee8a46150912e6
6e3458c44983d305674607fbabfd6765dc4abf80
refs/heads/master
<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package pbo10k.pkg10119920.latihan41.massajenis; /** * * @author * NAMA : <NAME> * KELAS : IF10K * NIM : 10119920 * Deskripsi Program : Program ini berisi program untuk menampilkan * jenis-jenis tipe data bilangan bulat * */ class Kubus { private int sisi; private int massa; public int getSisi() { return sisi; } public void setSisi(int sisi){ this.sisi = sisi; } public int getMassa() { return massa; } public void setMassa(int massa){ this.massa = massa; } public int hitungVolume(int parSisi){ int volume; volume = parSisi * parSisi * parSisi; return volume; } public int hitungMassaJenis(int parMassa, int volume){ int massaJenis; massaJenis = parMassa / volume; return massaJenis; } } public class MassaJenis { public static void main(String[] args) { Kubus sisiKubus = new Kubus(); Kubus massaKubus = new Kubus(); Kubus volumeKubus = new Kubus(); Kubus massaJenisKubus = new Kubus(); sisiKubus.setSisi(5); massaKubus.setMassa(250); System.out.println("=====Massa Jenis Kubus====="); System.out.println("Sisi : " + sisiKubus.getSisi()); System.out.println("Massa : " + massaKubus.getMassa()); System.out.println(); System.out.println("=====Hasil Perhitungan====="); System.out.println("Volume : " + volumeKubus.hitungVolume(sisiKubus.getSisi())); System.out.println("Massa Jenis : " + massaJenisKubus.hitungMassaJenis(massaKubus.getMassa(), volumeKubus.hitungVolume(sisiKubus.getSisi()))); } }
8682f7216318a4234dd22d02ef1b15fdadf32c0f
[ "Java" ]
1
Java
ursBot/PBO10K-10119920-Latihan41-MassaJenis
205749a3199dbed7151ea05855dbf0f4faacb696
5c5b101bd2cd101648364950dcbfa347e43ec15c
refs/heads/main
<repo_name>man-ish-fs-2021/spacex-internship-challenge-for-man-ish-fs-2021<file_sep>/src/actions/actionTypes.js export const UPDATE_LAUNCH = "UPDATE_LAUNCH"; export const START_FETCH = "START_FETCH"; <file_sep>/src/components/Table.js import React, { useState } from "react"; import { PaginationComp } from "./index"; import { useTable, usePagination, useGlobalFilter } from "react-table"; import Modal from "react-modal"; import { GlobalFilter } from "./GlobalFilter"; import ModalComp from "./ModalComp"; // react-modal component Modal.setAppElement("#root"); export const Table = ({ columns, data }) => { const tableInstance = useTable( { columns, data, }, useGlobalFilter, usePagination ); const { getTableProps, getTableBodyProps, headerGroups, page, prepareRow, state, setGlobalFilter, preGlobalFilteredRows, globalFilteredRows, } = tableInstance; // modal state const [modalIsOpen, setIsOpen] = useState(false); const [selectedRowId, setSelectedRowId] = useState({}); function openModal() { setIsOpen(true); } function afterOpenModal() { // references are now sync'd and can be accessed. } const handleShow = (selectedId, date) => { // sending the id of the selected row to the modal setSelectedRowId({ selectedId, date }); }; function closeModal() { setIsOpen(false); } return ( <> <GlobalFilter globalFilter={state.globalFilter} setGlobalFilter={setGlobalFilter} preGlobalFilteredRows={preGlobalFilteredRows} /> <table {...getTableProps()}> <thead> {headerGroups.map((headerGroup) => ( <tr {...headerGroup.getHeaderGroupProps()}> {headerGroup.headers.map((column) => ( <th {...column.getHeaderProps({ style: { width: column.width }, })} > {column.render("Header")} </th> ))} </tr> ))} </thead> {globalFilteredRows.length === 0 && ( <div className="empty-state"> No results found for the specified filter </div> )} <tbody {...getTableBodyProps()} className="table-body"> {page.map((row) => { prepareRow(row); return ( <tr {...row.getRowProps()} className="tr-body" onClick={() => { openModal(); handleShow(row.id, row.original.launch_date_utc); }} > {row.cells.map((cell) => { return ( <td {...cell.getCellProps({ style: { width: cell.column.width }, })} > {cell.render("Cell")} </td> ); })} </tr> ); })} </tbody> </table> {/* if is progress is true, dont show modal and show a loading screen */} <ModalComp data={data} rowData={selectedRowId} isOpen={modalIsOpen} onAfterOpen={afterOpenModal} onRequestClose={closeModal} /> <PaginationComp {...tableInstance} /> </> ); }; export default Table; <file_sep>/src/components/App.js import { useSelector, useDispatch } from "react-redux"; import { Header, Table } from "./index"; import { useEffect, useMemo } from "react"; import { fetchLaunch } from "../actions/launch"; import { COLUMNS } from "./columns"; import LoadingState from "./LoadingState"; import "../loadingState.css"; function App() { // dipatching using redux hooks. const dispatch = useDispatch(); useEffect(() => { dispatch(fetchLaunch()); }, [dispatch]); const launch = useSelector((state) => state.launch.launch); const isProgress = useSelector((state) => state.launch.isProgress); // memorising the columns for the table const columns = useMemo(() => COLUMNS, []); const data = useMemo(() => launch, [launch]); return ( <div className="App"> <Header /> {isProgress ? <LoadingState /> : <Table columns={columns} data={data} />} </div> ); } export default App; <file_sep>/README.old.md # spacex-internship-challenge-for-man-ish-fs-2021<file_sep>/src/components/index.js import Header from "./Header"; import App from "./App"; import Table from "./Table"; import PaginationComp from "./PaginationComp"; import ModalComp from "./ModalComp"; import LoadingState from "./LoadingState"; export { Header, App, Table, PaginationComp, ModalComp, LoadingState }; <file_sep>/src/reducers/index.js import { combineReducers } from "redux"; import launch from "./launch"; // redux combined reducer export default combineReducers({ launch, }); <file_sep>/src/components/GlobalFilter.js import React, { useEffect, useState } from "react"; import "../dropdown.css"; // global filter options const options = ["All Launches", "Upcoming", "Failed", "Succesful"]; export const GlobalFilter = ({ setGlobalFilter, rows }) => { // state for the dropdown list const [isOpen, setIsOpen] = useState(false); const [selectedOption, setSelectedOption] = useState(""); // setting the global filter useEffect(() => { if (selectedOption === "All Launches") { setGlobalFilter(""); } else if (selectedOption === "Upcoming") { setGlobalFilter("upcoming"); } else if (selectedOption === "Succesful") { setGlobalFilter("true"); } else if (selectedOption === "Failed") { setGlobalFilter("false"); } }, [selectedOption, setGlobalFilter]); const onOptionClicked = (value) => () => { setSelectedOption(value); setIsOpen(false); }; const toggling = () => setIsOpen(!isOpen); return ( <> <div className="DropDownContainer"> <div className="DropDownHeader" onClick={toggling}> <span className="filter-icon"> <svg xmlns="http://www.w3.org/2000/svg" width="12" height="13" viewBox="0 0 12 13" fill="none" > <path d="M12 0.666656V1.99999H11.3333L8 6.99999V12.6667H4V6.99999L0.666667 1.99999H0V0.666656H12ZM2.26933 1.99999L5.33333 6.59599V11.3333H6.66667V6.59599L9.73067 1.99999H2.26933Z" fill="#4B5563" /> </svg> </span> {selectedOption || "All Launches"} <span className="arrow"> <svg xmlns="http://www.w3.org/2000/svg" width="10" height="6" viewBox="0 0 10 6" fill="none" > <path d="M4.99999 3.78135L8.29999 0.481354L9.24266 1.42402L4.99999 5.66669L0.757324 1.42402L1.69999 0.481354L4.99999 3.78135Z" fill="#4B5563" /> </svg> </span> </div> {isOpen && ( <div className="DropDownListContainer"> <ul className="DropDownList"> {options.map((option, index) => ( <li className="list-item" onClick={onOptionClicked(option)} key={`option-${index}`} > {option} </li> ))} </ul> </div> )} </div> </> ); }; export default GlobalFilter; <file_sep>/src/actions/launch.js import axios from "axios"; import { API } from "../utils/url"; import { UPDATE_LAUNCH, START_FETCH } from "./actionTypes"; // redux action export function fetchLaunch() { return async (dispatch) => { const url = API.root(); dispatch(startFetch()); try { const response = await axios.get(url); const data = await response.data; dispatch(updateLaunch(data)); } catch (err) { console.error(err); } }; } export function startFetch() { return { type: START_FETCH, }; } export function updateLaunch(data) { return { type: UPDATE_LAUNCH, data, }; } <file_sep>/src/utils/url.js export const API = { root: () => "https://api.spacexdata.com/v3/launches", };
0c96652f006faed9816478820e29356d8ec4dd07
[ "JavaScript", "Markdown" ]
9
JavaScript
man-ish-fs-2021/spacex-internship-challenge-for-man-ish-fs-2021
3690481c59c2156653d86a6a1462341c4b3c0a41
5f1d83533a90b425502d03db0a1ba1ffff0c7d3e
refs/heads/main
<file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using ZXing; namespace QRCodeScanner { public partial class MainPage : ContentPage { public MainPage() { InitializeComponent(); } public void scanView_OnScanResult(Result result) { Device.BeginInvokeOnMainThread(async () => { await DisplayAlert("Scanned result", "The barcode's text is " + result.Text + ". The barcode's format is " + result.BarcodeFormat, "OK"); }); } } }
c001b5c3876f6958eb919d0263ce37535944a456
[ "C#" ]
1
C#
sh1karasu/QRCodeScanner
b8b45e2010683ea824cec8a58898eed29f4c37e0
850c55f96f08dd5a9705a26f53e58d51f76a06c5
refs/heads/master
<repo_name>j0nesma/advent-of-code-2020<file_sep>/src/test/java/matthew/jones/advent/of/code/days/day4/keyValues/ExpirationYearTest.java package matthew.jones.advent.of.code.days.day4.keyValues; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class ExpirationYearTest { private ExpirationYear underTest; @BeforeEach void setUp() { underTest = new ExpirationYear(); } @Test void isValid() { assertTrue(underTest.isValid("2020")); assertTrue(underTest.isValid("2030")); assertFalse(underTest.isValid("2019")); assertFalse(underTest.isValid("2031")); assertFalse(underTest.isValid("20311")); assertFalse(underTest.isValid("2fdsfds")); } @Test void getKey() { assertEquals("eyr", underTest.getKey()); } }<file_sep>/src/main/java/matthew/jones/advent/of/code/days/day7/bag/Bag.java package matthew.jones.advent.of.code.days.day7.bag; import java.util.List; public class Bag { private String bagLabel; private int noOfBags; private List<LinkedBag> linkedBagList; public Bag(String bagLabel, int noOfBags, List<LinkedBag> linkedBagList) { this.bagLabel = bagLabel; this.noOfBags = noOfBags; this.linkedBagList = linkedBagList; } public String getBagLabel() { return bagLabel; } public int getNoOfBags() { return noOfBags; } public List<LinkedBag> getLinkedBagList() { return linkedBagList; } } <file_sep>/src/main/java/matthew/jones/advent/of/code/util/StringUtils.java package matthew.jones.advent.of.code.util; import com.google.common.collect.Lists; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class StringUtils { public static final String EOL = "\r\n"; public static List<Integer> convertStringToIntegerList(String integerString) { String[] splitNumbers = split(integerString); return Arrays.stream(splitNumbers) .map(Integer::parseInt) .collect(Collectors.toList()); } public static String[] split(String integerString) { return integerString.split(EOL); } public static List<String> splitToList(String data) { return Arrays.asList(data.split(EOL)); } public static ArrayList<String> splitToArrayList(String data) { return Lists.newArrayList(splitToList(data)); } } <file_sep>/src/main/java/matthew/jones/advent/of/code/days/day1/Day1.java package matthew.jones.advent.of.code.days.day1; import lombok.extern.slf4j.Slf4j; import matthew.jones.advent.of.code.days.AbstractDay; import matthew.jones.advent.of.code.util.StringUtils; import java.util.Collections; import java.util.List; //https://adventofcode.com/2020/day/1 @Slf4j public class Day1 extends AbstractDay { private static List<Integer> DATA_LIST; public Day1(String data) { super(data); DATA_LIST = StringUtils.convertStringToIntegerList(getData()); } @Override public void run() { log.info("Day1 - two digits which add up to make 2020 multiplied =" + multiplyTwoDigitsWhichAddToMake2020()); log.info("Day1 - three digits which add up to make 2020 multiplied =" + multiplyThreeDigitsWhichAddToMake2020()); } public int multiplyTwoDigitsWhichAddToMake2020() { for (Integer item : DATA_LIST) { if (makes2020(item)) { return item * getExpectedValue(item); } } throw new RuntimeException("No 2020 value provided"); } private boolean makes2020(Integer item) { return DATA_LIST.contains(getExpectedValue(item)); } public int multiplyThreeDigitsWhichAddToMake2020() { Collections.sort(DATA_LIST); for(int i = 0; i < DATA_LIST.size(); i++) { Integer lowValue = DATA_LIST.get(i); for(int j = 1; j< DATA_LIST.size(); j++) { Integer testingValue = DATA_LIST.get(j); int total = lowValue + testingValue; if (makes2020(total)) { return lowValue * testingValue * getExpectedValue(total); } } } throw new RuntimeException("No 2020 value provided"); } private int getExpectedValue(Integer value) { return 2020 - value; } } <file_sep>/src/test/java/matthew/jones/advent/of/code/days/day8/Day8Test.java package matthew.jones.advent.of.code.days.day8; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class Day8Test { //nop +0 | 1 //acc +1 | 2, 8(!) //jmp +4 | 3 //acc +3 | 6 //jmp -3 | 7 //acc -99 | //acc +1 | 4 //jmp -4 | 5 //acc +6 | @Test void test() { //GIVEN Day8 undertest = new Day8("nop +0\r\n" + "acc +1\r\n" + "jmp +4\r\n" + "acc +3\r\n" + "jmp -3\r\n" + "acc -99\r\n" + "acc +1\r\n" + "jmp -4\r\n" + "acc +6"); //WHEN int actual = undertest.runCode(); //THEN assertEquals(5, actual); } }<file_sep>/src/main/java/matthew/jones/advent/of/code/days/day4/keyValues/Height.java package matthew.jones.advent.of.code.days.day4.keyValues; public class Height extends AbstractKeyValue { public static final int SUFFIX_LENGTH = 2; public static final String CENTIMETER = "cm"; public static final String INCH = "in"; private static final String KEY = "hgt"; @Override public boolean isValid(String value) { String suffix = value.substring(value.length() - SUFFIX_LENGTH); int prefix; try { prefix = Integer.parseInt(value.substring(0, value.length() - SUFFIX_LENGTH)); } catch (NumberFormatException e) { return false; } if (suffix.equals(CENTIMETER)) { return prefix >= 150 && prefix <= 193; } if (suffix.equals(INCH)) { return prefix >= 59 && prefix <= 76; } return false; } @Override public String getKey() { return KEY; } } <file_sep>/src/test/java/matthew/jones/advent/of/code/days/day7/Day7Test.java package matthew.jones.advent.of.code.days.day7; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class Day7Test { @Test void test() { // GIVEN Day7 underTest = new Day7("light red bags contain 1 bright white bag, 2 muted yellow bags.\r\n" + "dark orange bags contain 3 bright white bags, 4 muted yellow bags.\r\n" + "bright white bags contain 1 shiny gold bag.\r\n" + "muted yellow bags contain 2 shiny gold bags, 9 shiny gold bags.\r\n" + "shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags.\r\n" + "dark olive bags contain 3 faded blue bags, 4 dotted black bags.\r\n" + "vibrant plum bags contain 5 faded blue bags, 6 dotted black bags.\r\n" + "faded blue bags contain no other bags.\r\n" + "dotted black bags contain no other bags."); // WHEN int actual = underTest.howManyBagsssss(); // THEN assertEquals(4, actual); } @Test void part2() { // GIVEN Day7 underTest = new Day7("shiny gold bags contain 2 dark red bags.\r\n" + "dark red bags contain 2 dark orange bags.\r\n" + "dark orange bags contain 2 dark yellow bags.\r\n" + "dark yellow bags contain 2 dark green bags.\r\n" + "dark green bags contain 2 dark blue bags.\r\n" + "dark blue bags contain 2 dark violet bags.\r\n" + "dark violet bags contain no other bags."); // WHEN int actual = underTest.howManyBagsssssPart2(); // THEN assertEquals(126, actual); } @Test void part2_1() { // GIVEN Day7 underTest = new Day7("light red bags contain 1 bright white bag, 2 muted yellow bags.\r\n" + "dark orange bags contain 3 bright white bags, 4 muted yellow bags.\r\n" + "bright white bags contain 1 shiny gold bag.\r\n" + "muted yellow bags contain 2 shiny gold bags, 9 faded blue bags.\r\n" + "shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags.\r\n" + "dark olive bags contain 3 faded blue bags, 4 dotted black bags.\r\n" + "vibrant plum bags contain 5 faded blue bags, 6 dotted black bags.\r\n" + "faded blue bags contain no other bags.\r\n" + "dotted black bags contain no other bags."); // WHEN int actual = underTest.howManyBagsssssPart2(); // THEN assertEquals(32, actual); } }<file_sep>/src/main/java/matthew/jones/advent/of/code/days/day4/Day4.java package matthew.jones.advent.of.code.days.day4; import com.google.common.collect.Lists; import lombok.extern.slf4j.Slf4j; import matthew.jones.advent.of.code.days.AbstractDay; import matthew.jones.advent.of.code.days.day4.keyValues.*; import matthew.jones.advent.of.code.util.StringUtils; import java.util.ArrayList; import java.util.Map; //https://adventofcode.com/2020/day/4 @Slf4j public class Day4 extends AbstractDay { public static Map<String, AbstractKeyValue> validColumns = Map.of("byr", new BirthYear(), "iyr", new IssueYear(), "eyr", new ExpirationYear(), "hgt", new Height(), "hcl", new HairColor(), "ecl", new EyeColor(), "pid", new PassportId(), "cid", new CountryId()); public ArrayList<String> requiredColumns; public Day4(String data) { super(data); } @Override public void run() { log.info("Day4 - Valid passports = " + testPassports()); } private void reset() { requiredColumns = Lists.newArrayList("byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"); } public int testPassports() { String[] split = StringUtils.split(getData()); reset(); int count = 0; int i = 0; for (String value : split) { if (value.equals("")) { if (requiredColumns.size() == 0) { count++; } reset(); } else { String[] details = value.split(" "); for (String detail : details) { String[] keyValue = detail.split(":"); String key = keyValue[0]; String val = keyValue[1]; if (containsValidKey(key, val)) { requiredColumns.remove(key); } } } i++; } if (requiredColumns.size() == 0) { count++; } return count; } private boolean containsValidKey(String key, String val) { return validColumns.containsKey(key) && validColumns.get(key).isValid(val); } } <file_sep>/src/main/java/matthew/jones/advent/of/code/days/day4/keyValues/EyeColor.java package matthew.jones.advent.of.code.days.day4.keyValues; import java.util.List; public class EyeColor extends AbstractKeyValue { public static final List<String> COLORS = List.of("amb", "blu", "brn", "gry", "grn", "hzl", "oth"); private static final String KEY = "ecl"; @Override public boolean isValid(String value) { return COLORS.contains(value); } @Override public String getKey() { return KEY; } } <file_sep>/src/main/java/matthew/jones/advent/of/code/days/day2/Day2.java package matthew.jones.advent.of.code.days.day2; import lombok.extern.slf4j.Slf4j; import matthew.jones.advent.of.code.days.AbstractDay; import matthew.jones.advent.of.code.util.StringUtils; //https://adventofcode.com/2020/day/2 @Slf4j public class Day2 extends AbstractDay { public static final int RULE_DEFINITION = 0; public static final int PASSWORD = 1; public static final int RULE = 0; public static final int CHARACTER = 1; public static final int RULE_MAX = 0; public static final int RULE_MIN = 1; public static final String ROW_SPLIT_CHARACTER = ":"; public static final String RULES_SPLIT_CHARACTER = " "; public static final String MIN_MAX_SPLIT_CHARACTER = "-"; private String password; private char value; private int ruleMin; private int ruleMax; public Day2(String data) { super(data); } @Override public void run() { log.info("Day2 - Number of Valid Passwords =" + checkPasswords()); log.info("Day2 - Number of Valid Passwords NEW POLICY =" + checkPasswordsNewPolicy()); } public Integer checkPasswords() { String[] dataRow = StringUtils.split(getData()); Integer count = 0; for (String row : dataRow) { extractData(row); if (validPassword(password, value, ruleMin, ruleMax)) { count++; } } return count; } public Integer checkPasswordsNewPolicy() { String[] dataRow = StringUtils.split(getData()); int count = 0; for (String row : dataRow) { extractData(row); if (characterInValidPosition(password, value, ruleMin, ruleMax)) { count++; } } return count; } private boolean characterInValidPosition(String password, char value, int ruleMin, int ruleMax) { return password.charAt(ruleMin) == value ^ password.charAt(ruleMax) == value; } private boolean validPassword(String password, char value, int ruleMin, int ruleMax) { int count = countValueInPassword(password, value, 0); return count <= ruleMax && count >= ruleMin; } private int countValueInPassword(String password, char value, int index) { if (index >= password.length()) { return 0; } int count = password.charAt(index) == value ? 1 : 0; return count + countValueInPassword(password, value, index + 1); } private void extractData(String row) { String[] dataColumns = row.split(ROW_SPLIT_CHARACTER); password = dataColumns[PASSWORD]; String[] rules = dataColumns[RULE_DEFINITION].split(RULES_SPLIT_CHARACTER); value = rules[CHARACTER].charAt(0); String rule = rules[RULE]; String[] ruleMinMax = rule.split(MIN_MAX_SPLIT_CHARACTER); ruleMin = Integer.parseInt(ruleMinMax[RULE_MAX]); ruleMax = Integer.parseInt(ruleMinMax[RULE_MIN]); } } <file_sep>/src/main/java/matthew/jones/advent/of/code/days/day8/Day8.java package matthew.jones.advent.of.code.days.day8; import com.google.common.collect.Lists; import lombok.extern.slf4j.Slf4j; import matthew.jones.advent.of.code.days.AbstractDay; import matthew.jones.advent.of.code.util.StringUtils; import java.util.ArrayList; //https://adventofcode.com/2020/day/8 @Slf4j public class Day8 extends AbstractDay { public int accumulator; public Day8(String data) { super(data); } @Override public void run() { log.info("Day8 - accumulator =" + runCode()); } public int runCode() { ArrayList<String> lines = StringUtils.splitToArrayList(getData()); ArrayList<Integer> linesRun = Lists.newArrayList(); boolean hasRepeated = false; int i = 0; while (!hasRepeated) { if (linesRun.contains(i)) { return accumulator; } linesRun.add(i); String line = lines.get(i); String command = line.substring(0, 3); String operand = line.substring(4, 5); int value = Integer.parseInt(line.substring(line.indexOf(operand) + 1)); switch (command) { case "acc": if ("+".equals(operand)) { accumulator += value; } if ("-".equals(operand)) { accumulator -= value; } break; case "nop": break; case "jmp": if ("+".equals(operand)) { if (i + value > lines.size()) { int diff = i - value; i = i + value % lines.size(); } else { i += value; } } if ("-".equals(operand)) { if (i - value < 0) { int diff = i - value; i = lines.size() + diff % lines.size(); } else { i -= value; } } break; } if (!"jmp".equals(command)) { if (i + 1 > lines.size()) { i = 0; } else { i++; } } } return 0; } public int runCodePart2() { ArrayList<String> lines = StringUtils.splitToArrayList(getData()); ArrayList<Integer> linesRun = Lists.newArrayList(); boolean hasRepeated = false; int i = 0; while (!hasRepeated) { if (linesRun.contains(i)) { String prevLine = lines.get(linesRun.get(linesRun.size() - 1)); return accumulator; } linesRun.add(i); String line = lines.get(i); String command = line.substring(0, 3); String operand = line.substring(4, 5); int value = Integer.parseInt(line.substring(line.indexOf(operand) + 1)); switch (command) { case "acc": if ("+".equals(operand)) { accumulator += value; } if ("-".equals(operand)) { accumulator -= value; } break; case "nop": break; case "jmp": if ("+".equals(operand)) { if (i + value > lines.size()) { int diff = i - value; i = i + value % lines.size(); } else { i += value; } } if ("-".equals(operand)) { if (i - value < 0) { int diff = i - value; i = lines.size() + diff % lines.size(); } else { i -= value; } } break; } if (!"jmp".equals(command)) { if (i + 1 > lines.size()) { i = 0; } else { i++; } } } return 0; } } <file_sep>/src/main/java/matthew/jones/advent/of/code/days/day4/keyValues/HairColor.java package matthew.jones.advent.of.code.days.day4.keyValues; public class HairColor extends AbstractKeyValue { public static final String REGEX = "#[a-f,0-9]{6}"; private static final String KEY = "hcl"; @Override public boolean isValid(String value) { return value.matches(REGEX); } @Override public String getKey() { return KEY; } } <file_sep>/src/test/java/matthew/jones/advent/of/code/days/day4/keyValues/EyeColorTest.java package matthew.jones.advent.of.code.days.day4.keyValues; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class EyeColorTest { private EyeColor underTest; @BeforeEach void setUp() { underTest = new EyeColor(); } @Test //amb blu brn gry grn hzl oth void isValid() { assertTrue(underTest.isValid("amb")); assertTrue(underTest.isValid("blu")); assertTrue(underTest.isValid("brn")); assertTrue(underTest.isValid("gry")); assertTrue(underTest.isValid("grn")); assertTrue(underTest.isValid("hzl")); assertTrue(underTest.isValid("oth")); assertFalse(underTest.isValid("#123abz")); assertFalse(underTest.isValid("123abc")); } @Test void getKey() { assertEquals("ecl", underTest.getKey()); } }<file_sep>/src/main/java/matthew/jones/advent/of/code/days/day6/Day6.java package matthew.jones.advent.of.code.days.day6; import com.google.common.collect.Lists; import lombok.extern.slf4j.Slf4j; import matthew.jones.advent.of.code.days.AbstractDay; import matthew.jones.advent.of.code.util.StringUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.List; //https://adventofcode.com/2020/day/6 @Slf4j public class Day6 extends AbstractDay { public Day6(String data) { super(data); } @Override public void run() { log.info("Day6 - number of questions = " + customDeclarationForm()); log.info("Day6 - number of questions part 2 = " + customDeclarationFormWhoAnswered()); } public int customDeclarationForm() { String[] data = StringUtils.split(getData()); ArrayList<String> mergedLines = Lists.newArrayList(); StringBuilder answers = new StringBuilder(); for (String line : data) { if (line.equals("")) { mergedLines.add(answers.toString()); answers = new StringBuilder(); } answers.append(line); } //Check if there is a straggler if (answers.length() > 0) { mergedLines.add(answers.toString()); } return mergedLines.stream().map(this::getDistinct).mapToInt(Integer::intValue).sum(); } private Integer getDistinct(String ele) { return (int) ele.chars().distinct().count(); } public int customDeclarationFormWhoAnswered() { List<String> data = Arrays.asList(StringUtils.split(getData())); ArrayList<String> answeredQuestions = Lists.newArrayList(Arrays.asList(data.get(0).split(""))); int count = 0; for (int i = 0; i < data.size(); i++) { String line = data.get(i); if (line.isEmpty()) { count += answeredQuestions.size(); answeredQuestions = Lists.newArrayList(Arrays.asList(data.get(i + 1).split(""))); } else { List<String> tempAnsweredQuestions = Arrays.asList(line.split("")); answeredQuestions.retainAll(tempAnsweredQuestions); } } if (!answeredQuestions.isEmpty()) { count += answeredQuestions.size(); } return count; } } <file_sep>/src/main/java/matthew/jones/advent/of/code/AdventOfCode.java package matthew.jones.advent.of.code; import com.google.common.base.Charsets; import lombok.extern.slf4j.Slf4j; import matthew.jones.advent.of.code.days.DayManager; import matthew.jones.advent.of.code.days.day1.Day1; import matthew.jones.advent.of.code.days.day2.Day2; import matthew.jones.advent.of.code.days.day3.Day3; import matthew.jones.advent.of.code.days.day4.Day4; import matthew.jones.advent.of.code.days.day5.Day5; import matthew.jones.advent.of.code.days.day6.Day6; import matthew.jones.advent.of.code.days.day7.Day7; import matthew.jones.advent.of.code.days.day8.Day8; import java.io.IOException; import java.net.URL; @Slf4j public class AdventOfCode { public static void main(String[] args) { DayManager dayManager = new DayManager(); dayManager.addDay(new Day1(getData("day1.txt"))); dayManager.addDay(new Day2(getData("day2.txt"))); dayManager.addDay(new Day3(getData("day3.txt"))); dayManager.addDay(new Day4(getData("day4.txt"))); dayManager.addDay(new Day5(getData("day5.txt"))); dayManager.addDay(new Day6(getData("day6.txt"))); dayManager.addDay(new Day7(getData("day7.txt"))); dayManager.addDay(new Day8(getData("day8.txt"))); dayManager.run(); } private static String getData(String path) { URL url = com.google.common.io.Resources.getResource(path); try { return com.google.common.io.Resources.toString(url, Charsets.UTF_8); } catch (IOException ex) { throw new RuntimeException(ex); } } }
39637dae591f2db42d80bf1953231fcac9968764
[ "Java" ]
15
Java
j0nesma/advent-of-code-2020
5fff83bd4f1a3665f46e400a41c9bd691f4ec021
d5aed787dc34341bfc7caeeae7955983bff5f09f
refs/heads/master
<repo_name>ridouku/pycasbin<file_sep>/requirements.txt casbin==1.9.2 <file_sep>/README.md # Casbin demo with python This repository contains a little demo about casbin implementation ## Getting started Follow the next instructions to get the project ready to use. ## Requirements: - [Python version 3](https://www.python.org/download/releases/3.0/) (recommended 3.8 or less) in your path. It will install automatically [pip](https://pip.pypa.io/en/stable/) as well. - A virtual environment, namely [.venv](https://docs.python.org/3/library/venv.html). ### Create a virtual environment Execute the next command at the root of the project: ```shell python -m venv .venv ``` **Activate the environment** Windows: ```shell .venv\Scripts\activate.bat ``` In Unix based operative systems: ```shell source .venv/bin/activate ``` ## Dependencies: The dependencies are defined in requirements.txt ### Installation Execute the next command once you have created the venv: ```shell pip install -r requirements.txt ``` <file_sep>/main.py from typing import Any import casbin e: Any = casbin.Enforcer("./model.conf", "./policy.csv") def test_permission(): sub = "b8b1294c-04b2-4245-9d4d-0ac60a7804b7" # the user that wants to access a resource. obj = "3f70632a-2168-11ec-9621-0242ac130002" # the resource that is going to be accessed. act = "read" # the operation that the user performs on the resource. # e.add_policy("bob", "data2", "write") # e.update_policy(["bob", "data2", "delete"], ["bob", "data2", "read"]) # e.save_policy() # e.remove_policy(["bob", "data2", "delete"]) # e.remove_filtered_policy(0, "", "3f70632a-2168-11ec-9621-0242ac130002") # e.save_policy() # print(f'User, {sub} gets the permissions', e.get_permissions_for_user(sub)) print(f'User, {sub} gets the permissions for resource {obj}', e.get_filtered_policy(0, sub, obj)) if e.enforce(sub, obj, act): print(f'Hi, {sub} is authorized to {act} resource {obj}') pass else: print(f'Hi, {sub} is not authorized to {act} resource {obj}') pass if __name__ == '__main__': test_permission()
40f7d71972ff9e72e37b0de268ce37a59c399562
[ "Markdown", "Python", "Text" ]
3
Text
ridouku/pycasbin
2d93f89c326e59ae2e7fc3d9d7e8e35a40ba2eff
ff46c15fd6f560c984d95d27ee34e989abf637da
refs/heads/master
<repo_name>webber999/pushgateway<file_sep>/go.mod module github.com/prometheus/pushgateway require ( github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc // indirect github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf // indirect github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/gogo/protobuf v1.1.1 // indirect github.com/golang/protobuf v1.2.0 github.com/julienschmidt/httprouter v0.0.0-20171027133709-e1b9828bc9e5 github.com/matttproud/golang_protobuf_extensions v1.0.1 github.com/onsi/gomega v1.4.2 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/prometheus/client_golang v0.9.0 github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910 github.com/prometheus/common v0.0.0-20181015124227-bcb74de08d37 github.com/prometheus/procfs v0.0.0-20180725123919-05ee40e3a273 // indirect github.com/shurcooL/httpfs v0.0.0-20171119174359-809beceb2371 // indirect github.com/shurcooL/vfsgen v0.0.0-20180825020608-02ddb050ef6b github.com/sirupsen/logrus v0.0.0-20180515154058-0dad3b6953e7 // indirect github.com/stretchr/testify v1.2.2 // indirect golang.org/x/crypto v0.0.0-20180515001509-1a580b3eff78 // indirect golang.org/x/tools v0.0.0-20181115194243-f87c222f1487 // indirect gopkg.in/airbrake/gobrake.v2 v2.0.9 // indirect gopkg.in/alecthomas/kingpin.v2 v2.2.6 gopkg.in/gemnasium/logrus-airbrake-hook.v2 v2.1.2 // indirect ) <file_sep>/storage/diskmetricstore.go // Copyright 2014 The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package storage import ( "encoding/gob" "fmt" "io/ioutil" "os" "path" "sync" "time" "github.com/golang/protobuf/proto" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/common/log" "github.com/prometheus/common/model" dto "github.com/prometheus/client_model/go" ) const ( writeQueueCapacity = 1000 ) // DiskMetricStore is an implementation of MetricStore that persists metrics to // disk. type DiskMetricStore struct { lock sync.RWMutex // Protects metricFamilies. writeQueue chan WriteRequest drain chan struct{} done chan error metricGroups GroupingKeyToMetricGroup persistenceFile string predefinedHelp map[string]string } type mfStat struct { pos int // Where in the result slice is the MetricFamily? copied bool // Has the MetricFamily already been copied? } // NewDiskMetricStore returns a DiskMetricStore ready to use. To cleanly shut it // down and free resources, the Shutdown() method has to be called. // // If persistenceFile is the empty string, no persisting to disk will // happen. Otherwise, a file of that name is used for persisting metrics to // disk. If the file already exists, metrics are read from it as part of the // start-up. Persisting is happening upon shutdown and after every write action, // but the latter will only happen persistenceDuration after the previous // persisting. // // If a non-nil Gatherer is provided, the help strings of metrics gathered by it // will be used as standard. Pushed metrics with deviating help strings will be // adjusted to avoid inconsistent expositions. func NewDiskMetricStore( persistenceFile string, persistenceInterval time.Duration, gaptherPredefinedHelpFrom prometheus.Gatherer, ) *DiskMetricStore { // TODO: Do that outside of the constructor to allow the HTTP server to // serve /-/healthy and /-/ready earlier. dms := &DiskMetricStore{ writeQueue: make(chan WriteRequest, writeQueueCapacity), drain: make(chan struct{}), done: make(chan error), metricGroups: GroupingKeyToMetricGroup{}, persistenceFile: persistenceFile, } if err := dms.restore(); err != nil { log.Errorln("Could not load persisted metrics:", err) } if helpStrings, err := extractPredefinedHelpStrings(gaptherPredefinedHelpFrom); err == nil { dms.predefinedHelp = helpStrings } else { log.Errorln("Could not gather metrics for predefined help strings:", err) } go dms.loop(persistenceInterval) return dms } // SubmitWriteRequest implements the MetricStore interface. func (dms *DiskMetricStore) SubmitWriteRequest(req WriteRequest) { dms.writeQueue <- req } // GetMetricFamilies implements the MetricStore interface. func (dms *DiskMetricStore) GetMetricFamilies() []*dto.MetricFamily { result := []*dto.MetricFamily{} mfStatByName := map[string]mfStat{} dms.lock.RLock() defer dms.lock.RUnlock() for _, group := range dms.metricGroups { for name, tmf := range group.Metrics { mf := tmf.GetMetricFamily() stat, exists := mfStatByName[name] if exists { existingMF := result[stat.pos] if !stat.copied { mfStatByName[name] = mfStat{ pos: stat.pos, copied: true, } existingMF = copyMetricFamily(existingMF) result[stat.pos] = existingMF } if mf.GetHelp() != existingMF.GetHelp() { log.Infof( "Metric families '%s' and '%s' have inconsistent help strings. The latter will have priority. This is bad. Fix your pushed metrics!", mf, existingMF, ) } // Type inconsistency cannot be fixed here. We will detect it during // gathering anyway, so no reason to log anything here. for _, metric := range mf.Metric { existingMF.Metric = append(existingMF.Metric, metric) } } else { copied := false if help, ok := dms.predefinedHelp[name]; ok && mf.GetHelp() != help { log.Infof("Metric family '%s' has the same name as a metric family used by the Pushgateway itself but it has a different help string. Changing it to the standard help string %q. This is bad. Fix your pushed metrics!", mf, help) mf = copyMetricFamily(mf) copied = true mf.Help = proto.String(help) } mfStatByName[name] = mfStat{ pos: len(result), copied: copied, } result = append(result, mf) } } } return result } // Shutdown implements the MetricStore interface. func (dms *DiskMetricStore) Shutdown() error { close(dms.drain) return <-dms.done } // Healthy implements the MetricStore interface. func (dms *DiskMetricStore) Healthy() error { // By taking the lock we check that there is no deadlock. dms.lock.Lock() defer dms.lock.Unlock() // A pushgateway that cannot be written to should not be // considered as healthy. if len(dms.writeQueue) == cap(dms.writeQueue) { return fmt.Errorf("write queue is full") } return nil } // Ready implements the MetricStore interface. func (dms *DiskMetricStore) Ready() error { return dms.Healthy() } func (dms *DiskMetricStore) loop(persistenceInterval time.Duration) { lastPersist := time.Now() persistScheduled := false lastWrite := time.Time{} persistDone := make(chan time.Time) var persistTimer *time.Timer checkPersist := func() { if dms.persistenceFile != "" && !persistScheduled && lastWrite.After(lastPersist) { persistTimer = time.AfterFunc( persistenceInterval-lastWrite.Sub(lastPersist), func() { persistStarted := time.Now() if err := dms.persist(); err != nil { log.Errorln("Error persisting metrics:", err) } else { log.Infof( "Metrics persisted to '%s'.", dms.persistenceFile, ) } persistDone <- persistStarted }, ) persistScheduled = true } } for { select { case wr := <-dms.writeQueue: dms.processWriteRequest(wr) lastWrite = time.Now() checkPersist() case lastPersist = <-persistDone: persistScheduled = false checkPersist() // In case something has been written in the meantime. case <-dms.drain: // Prevent a scheduled persist from firing later. if persistTimer != nil { persistTimer.Stop() } // Now draining... for { select { case wr := <-dms.writeQueue: dms.processWriteRequest(wr) default: dms.done <- dms.persist() return } } } } } func (dms *DiskMetricStore) processWriteRequest(wr WriteRequest) { dms.lock.Lock() defer dms.lock.Unlock() key := model.LabelsToSignature(wr.Labels) if wr.MetricFamilies == nil { // Delete. delete(dms.metricGroups, key) return } // Update. for name, mf := range wr.MetricFamilies { group, ok := dms.metricGroups[key] if !ok { group = MetricGroup{ Labels: wr.Labels, Metrics: NameToTimestampedMetricFamilyMap{}, } dms.metricGroups[key] = group } group.Metrics[name] = TimestampedMetricFamily{ Timestamp: wr.Timestamp, GobbableMetricFamily: (*GobbableMetricFamily)(mf), } } } // GetMetricFamiliesMap implements the MetricStore interface. func (dms *DiskMetricStore) GetMetricFamiliesMap() GroupingKeyToMetricGroup { dms.lock.RLock() defer dms.lock.RUnlock() groupsCopy := make(GroupingKeyToMetricGroup, len(dms.metricGroups)) for k, g := range dms.metricGroups { metricsCopy := make(NameToTimestampedMetricFamilyMap, len(g.Metrics)) groupsCopy[k] = MetricGroup{Labels: g.Labels, Metrics: metricsCopy} for n, tmf := range g.Metrics { metricsCopy[n] = tmf } } return groupsCopy } func (dms *DiskMetricStore) persist() error { // Check (again) if persistence is configured because some code paths // will call this method even if it is not. if dms.persistenceFile == "" { return nil } f, err := ioutil.TempFile( path.Dir(dms.persistenceFile), path.Base(dms.persistenceFile)+".in_progress.", ) if err != nil { return err } inProgressFileName := f.Name() e := gob.NewEncoder(f) dms.lock.RLock() err = e.Encode(dms.metricGroups) dms.lock.RUnlock() if err != nil { f.Close() os.Remove(inProgressFileName) return err } if err := f.Close(); err != nil { os.Remove(inProgressFileName) return err } return os.Rename(inProgressFileName, dms.persistenceFile) } func (dms *DiskMetricStore) restore() error { if dms.persistenceFile == "" { return nil } f, err := os.Open(dms.persistenceFile) if os.IsNotExist(err) { return nil } if err != nil { return err } defer f.Close() d := gob.NewDecoder(f) if err := d.Decode(&dms.metricGroups); err != nil { return err } return nil } func copyMetricFamily(mf *dto.MetricFamily) *dto.MetricFamily { return &dto.MetricFamily{ Name: mf.Name, Help: mf.Help, Type: mf.Type, Metric: append([]*dto.Metric{}, mf.Metric...), } } // extractPredefinedHelpStrings extracts all the HELP strings from the provided // gatherer so that the DiskMetricStore can fix deviations in pushed metrics. func extractPredefinedHelpStrings(g prometheus.Gatherer) (map[string]string, error) { if g == nil { return nil, nil } mfs, err := g.Gather() if err != nil { return nil, err } result := map[string]string{} for _, mf := range mfs { result[mf.GetName()] = mf.GetHelp() } return result, nil } <file_sep>/Dockerfile FROM quay.io/prometheus/busybox:latest LABEL maintainer "The Prometheus Authors <<EMAIL>>" COPY pushgateway /bin/pushgateway EXPOSE 9091 RUN mkdir -p /pushgateway WORKDIR /pushgateway ENTRYPOINT [ "/bin/pushgateway" ] <file_sep>/.github/ISSUE_TEMPLATE.md <!-- Note that we use GitHub issues for bugs and (uncontroversial) feature requests (see below for details). Please do *NOT* ask usage questions in GitHub issues. Usage questions make most sense on the users mailing list, where more people are available to potentially respond to your question, and the whole community can benefit from the answers provided (perhaps your question has already been answered, search the archive to find out): https://groups.google.com/forum/#!forum/prometheus-users While a GitHub issue is fine to track progress on an uncontroversial feature request, many feature requests touch the best practices and concepts of Prometheus as a whole and need to be discussed with the wider developer community first. This is in particular true for a request to reconsider a prior rejection of a feature request or any of the declared non-goals (see README.md). Those overarching discussions happen on the developer mailing list (GitHub issues, in particular closed ones, are not tracked by the wider developer community and thus inadequate): https://groups.google.com/forum/#!forum/prometheus-developers You can find more information at: https://prometheus.io/community/ --> ## Feature request **Use case. Why is this important?** *“Nice to have” is not a good use case. :)* ## Bug Report **What did you do?** **What did you expect to see?** **What did you see instead? Under which circumstances?** **Environment** * System information: Insert output of `uname -srm` here. * Pushgateway version: Insert output of `pushgateway --version` here. * Pushgateway command line: Insert full command line. * Logs: ``` Insert Pushgateway logs relevant to the issue here. ```
cb925367160fe443ddb96fc7b3d536c679e4af2d
[ "Go", "Go Module", "Dockerfile", "Markdown" ]
4
Go Module
webber999/pushgateway
949c8316b893f0676025abf94cd5ad5c382d5071
233e764ba59970951a3e5b3a02206b024ec8a7d5
refs/heads/master
<file_sep>from node import * import util import math from random import * from hiddenlayer import * class OutLayer: def __init__(self,inLayer,legalLabels): self.inLayer = inLayer; self.legalLabels = legalLabels; self.nodes = self.makeOutputNodes(); self.outputList = util.Counter(); def makeOutputNodes(self): outNodes = util.Counter(); for i in self.legalLabels: outNodes[i] = self.outNode(i); return outNodes; def outNode(self,num): newNode = Node(2,0); newWeights = util.Counter(); m = 0; for key in self.inLayer.nodes.keys(): newWeights[key] = uniform(0,0.01); #if m % 2 == 0: # newWeights[key] = uniform(-0.5,0); #else: # newWeights[key] = uniform(0,0.5); #m+=1; newNode.updateWeights(newWeights); return newNode; def activateLayer(self): for i in self.legalLabels: self.nodes[i].activate(self.inLayer); self.outputList[i] = self.nodes[i].output; def updateBiases(self, new_biases_vector): for key in new_biases_vector: self.nodes[key].bias = new_biases_vector[key]; def outputValue(self): return self.outputList.argMax(); def updateLayerWeights(self, new_weights_vector): for i in new_weights_vector.keys(): self.nodes[i].updateWeights(new_weights_vector[i]); <file_sep>import util import math from random import * class Node: def __init__(self,layer,bias=-1): self.layer=layer; self.weights=util.Counter(); self.activation=0; self.output=0; self.bias = bias; def updateWeights(self,newWeights): self.weights = newWeights; def act(self,inLayer = None,take_derivative = False): ret_vector = []; if self.layer == 1: L = 2; k = 0.07; b = self.bias; "***ACTIVATION FUNCTION FOR HIDDEN LAYER NODES***" if take_derivative == True: val = self.activation; numerator = k*L*math.exp(k*(val)); denominator = (1+math.exp(k*(val)))**2; ret_vector.append(numerator/denominator); #print "derivative taken: ", ret_vector[0], " " return ret_vector; else: ret_vector.append(self.weights * inLayer + self.bias); denom = 1 + math.exp(-k*(ret_vector[0])); ret_vector.append(L/denom - L/2); return ret_vector; else: "***ACTIVATION FUNCTION FOR OUTPUT LAYER NODES***" L = 2; k = 2; b = self.bias; if take_derivative == True: val = self.activation; numerator = k*L*math.exp(k*(val)); denominator = (1+math.exp(k*(val)))**2; ret_vector.append(numerator/denominator); #print "derivative taken: ", ret_vector[0], " " return ret_vector; else: ret_vector.append(self.weights * inLayer.outputGrid + self.bias); denom = 1 + math.exp(-k*(ret_vector[0])); ret_vector.append(L/denom - L/2); return ret_vector; def activate(self,inLayer): if self.layer == 1: "***ACTIVATION FUNCTION FOR HIDDEN LAYER NODES***" response = self.act(inLayer); self.activation = response[0]; self.output = response[1]; else: "***ACTIVATION FUNCTION FOR OUTPUT LAYER NODES***" response = self.act(inLayer); self.activation = response[0]; self.output = response[1]; <file_sep>from node import * import util import math from random import * class HiddenLayer: def __init__(self,num): self.num = num; '''if self.num == 98: self.nodes = self.makeHiddenNodes98(num); else:''' self.nodes = self.makeHiddenNodes(num); self.outputGrid = util.Counter(); def makeHiddenNodes(self,number): '''shift = int(math.sqrt(784/number)); squares = int(28/shift);''' nodeCounter = util.Counter(); squares = int(math.sqrt(number)); for i in range(number): nodeCounter[i] = self.hiddenNode(); return nodeCounter; def hiddenNode(self): newNode = Node(1,0); newWeights = util.Counter(); for i in range(28): for j in range (28): #if the performance is bad replace with newWeights[(i,j)] = uniform(-0.5,0.5) if (j+i) % 2 == 1: newWeights[(i,j)] = uniform(-0.5,0); else: newWeights[(i,j)] = uniform(0,0.5); newNode.updateWeights(newWeights); return newNode; ''' def makeHiddenNodes98(self,number): shift = int(math.sqrt(2*784/number)); rects = int(28/shift); nodeCounter = util.Counter(); for i in range(2*rects): for j in range(rects): nodeCounter[(i,j)] = self.hiddenNode98((i,j),shift); return nodeCounter; def hiddenNode98(self,coord,shift): newNode = Node(1,-1); newWeights = util.Counter(); focusfeatures = []; for f in range(shift/2): for g in range(shift): focusfeatures.append((coord[0]+f,coord[1]+g)); for i in range(28): for j in range (28): if (i,j) in focusfeatures: newWeights[(i,j)] = uniform(0.85,0.99); else: newWeights[(i,j)] = uniform(0,0.01); newNode.updateWeights(newWeights); return newNode;''' def updateBiases(self, new_biases_vector): for key in new_biases_vector: self.nodes[key].bias = new_biases_vector[key]; def updateLayerWeights(self,new_weights_vector): for key in new_weights_vector.keys(): self.nodes[key].updateWeights(new_weights_vector[key]); def activateLayer(self,inputs): grid = int(math.sqrt(self.num)); for key in self.nodes.keys(): self.nodes[key].activate(inputs); self.outputGrid[key] = self.nodes[key].output; <file_sep># svm.py # ------------- # svm implementation import util #import numpy as np #from sklearn.svm import LinearSVC PRINT = True class SVMClassifier: """ svm classifier In train you need to make a 2d array, where the first dimension is the number of training data and the second dimension is the pixel values of that training Data Outside of the for loop within train, you use self. (Classifier name).fit (that array 2d array you just made , the training label array) Finally in classify you just use guesses=self.(Classifier name). predict(2d array like the one you needed on training) """ def __init__( self, legalLabels): self.legalLabels = legalLabels self.type = "svm" self.name = LinearSVC(1) def train( self, trainingData, trainingLabels, validationData, validationLabels ): A = np.array([[x for x in trainingData.size] for y in trainingData.winfo_pixels()]) #puzzle = np.array([[Node(0,j,i) for j in range(dim)] for i in range(dim)]) print "Starting iteration ", iteration, "..." for i in range(len(trainingData)): pass def classify(self, data ): guesses = [] for datum in data: # fill predictions in the guesses list "*** YOUR CODE HERE ***" util.raiseNotDefined() return guesses <file_sep>#perceptron.py #------------- #Perceptronimplementation import util from time import time PRINT=True class PerceptronClassifier: """ Perceptronclassifier. """ def __init__(self,legalLabels,max_iterations): self.legalLabels=legalLabels self.type="perceptron" self.max_iterations=max_iterations self.weights=util.Counter(); for label in legalLabels: self.weights[label]=util.Counter() def setWeights(self,weights): assert len(weights)==len(self.legalLabels); self.weights=weights; def train(self,trainingData,trainingLabels,validationData,validationLabels): for iteration in range(self.max_iterations): print "Starting iteration",iteration,"..."; init = time(); for i in range(len(trainingData)): y = trainingLabels[i]; y_prime = self.classify([trainingData[i]])[0]; newWeights = self.weights; if y_prime==y: pass; else: newWeights[y] = self.weights[y] + trainingData[i]; newWeights[y_prime] = self.weights[y_prime] - trainingData[i]; self.setWeights(newWeights); final = time(); print "Seconds elapsed for this iteration:", final-init; def classify(self,data): guesses=[] for datum in data: vectors = util.Counter() for l in self.legalLabels: vectors[l]=self.weights[l]*datum; guesses.append(vectors.argMax()); return guesses def findHighWeightFeatures(self,label): featuresWeights=[]; c = util.counter(); for i in range(28): for j in range(28): c[(i,j)]=self.weights[label][(i,j)]; for k in range(100): x=c.argMax(); featuresWeights.append(x); c[x]=-(self.max_iterations+1); return featuresWeights <file_sep>#mlp.py #------------- #mlpimplementation import util import math from time import time from random import * from node import * from hiddenlayer import * from outputlayer import * PRINT=True class MLPClassifier: def __init__(self,legalLabels,max_iterations): self.legalLabels=legalLabels; self.type="mlp"; self.max_iterations=max_iterations; self.hLayer = HiddenLayer(78); self.oLayer = OutLayer(self.hLayer,self.legalLabels); def deltas_at_output_layer(self,expected_values_vector): delta_vector = util.Counter(); for i in self.oLayer.legalLabels: g_o_prime = (self.oLayer.nodes[i].act(inLayer = None,take_derivative = True)[0]); #print "value of output layer node ", i, " activation: ", self.oLayer.nodes[i].activation; delta_vector[i] = (self.oLayer.nodes[i].output-expected_values_vector[i])*g_o_prime; #print "derivative, delta of output node ",i," activation function: ", g_o_prime, ", ", delta_vector[i] ; return delta_vector #vector is a counter with 10 entries which are errors at each node; def deltas_at_hidden_layer(self,dels_at_output_layer): delta_vector = util.Counter(); for key in self.hLayer.nodes.keys(): summer = 0.0; for i in self.oLayer.legalLabels: summer += self.oLayer.nodes[i].weights[key]*dels_at_output_layer[i]; delta_vector[key] = (self.hLayer.nodes[key].act(inLayer = None,take_derivative = True)[0])*summer; return delta_vector; def new_weights_for_output_layer(self,dels_at_output_layer,eta): new_weights = util.Counter(); new_biases = util.Counter(); for i in self.oLayer.legalLabels: i_weight = util.Counter(); current = self.oLayer.nodes[i]; for key in current.weights.keys(): old = current.weights[key]; new = old - (eta*dels_at_output_layer[i]*self.hLayer.nodes[key].output); i_weight[key] = new; old_bias = current.bias; new_bias = old_bias - (eta*0.9)*dels_at_output_layer[i]; new_biases[i] = new_bias; #print "new bias for out node ", i,": ", new_bias; new_weights[i] = i_weight; self.oLayer.updateLayerWeights(new_weights); self.oLayer.updateBiases(new_biases) def new_weights_for_hidden_layer(self,dels_at_hidden_layer,inputLayer,eta): new_weights = util.Counter(); new_biases = util.Counter(); for key in self.hLayer.nodes.keys(): key_weights = util.Counter(); current = self.hLayer.nodes[key]; for key2 in self.hLayer.nodes[key].weights.keys(): old = current.weights[key2]; new = old - (eta*dels_at_hidden_layer[key]*inputLayer[key2]); key_weights[key2] = new; old_bias = current.bias; new_bias = old_bias - (eta*0.9)*dels_at_hidden_layer[key]; new_biases[key] = new_bias; new_weights[key] = key_weights; self.hLayer.updateLayerWeights(new_weights); self.hLayer.updateBiases(new_biases); def train(self,trainingData,trainingLabels,validationData,validationLabels): def learning_rate(init, final, num_decreases, num_examples): current = init; learning_rate_vector = []; decrease_interval = int(num_examples/num_decreases); decrease_size = (init-final)/num_decreases; for it in range(num_examples): if (it+1)%decrease_interval == 0: current = current-decrease_size; learning_rate_vector.append(current); return learning_rate_vector; for iteration in range(self.max_iterations): print "Starting iteration",iteration,"..." learning = learning_rate(0.1,0.08,50,int(len(trainingLabels))); init = time(); for i in range(len(trainingData)): #print "Training Item ",i," "; y=trainingLabels[i]; y_prime=self.classify([trainingData[i]])[0]; if y == y_prime: #print "CORRECT!" pass; else: #print "ERROR, t vs. f:",y, " ", y_prime; L_over_2 = 1; y_vector=[-1*L_over_2 for i in range(10)]; y_vector[y]=L_over_2; out_deltas = self.deltas_at_output_layer(y_vector); hidden_deltas = self.deltas_at_hidden_layer(out_deltas); self.new_weights_for_output_layer(out_deltas,learning[i]); self.new_weights_for_hidden_layer(hidden_deltas,trainingData[i],learning[i]); final = time(); print "Seconds elapsed for this iteration:", final-init; def classify(self,data): guesses=[]; for datum in data: self.hLayer.activateLayer(datum); self.oLayer.activateLayer(); guesses.append(self.oLayer.outputValue()); return guesses
c5f3a4c608a78e8a78a5233935630d0c9999b0ae
[ "Python" ]
6
Python
onlyhalfwaytrue/Supervised_Learning
3ca8ff0653ef278aaa1edbccc7d87347339e0f89
54a8f0bc383f0ba0cedb5e207d16212163cef68c
refs/heads/master
<file_sep># readme ## 概要 このプロジェクトはcvxgenで自動生成されたCソースコードをc++で呼び出せるようにしたものです. ### やったこと * cmakeでビルドできるようにした * cvxgenで生成したコードはライブラリとしてソースフォルダとは分離 * ついでに,ビルドスクリプトの実行だけで,cmake→makeまで行うようにした ## 実行 プロジェクトルートで`./build.sh`を実行 ## TODO * cvxgenフォルダに`CMakeLists.txt`をコピーしなくても良いようにしたい <file_sep>#! /bin/sh if [ ! -d build ]; then echo "could not find build folder" echo "create `pwd`/build \n " mkdir build fi cd build echo "\n===generating makefile===" cmake ../ echo "\n===starting make===" make <file_sep>/* Produced by CVXGEN, 2017-09-29 03:21:00 -0400. */ /* CVXGEN is Copyright (C) 2006-2012 <NAME>, <EMAIL>. */ /* The code in this file is Copyright (C) 2006-2012 <NAME>. */ /* CVXGEN, or solvers produced by CVXGEN, cannot be used for commercial */ /* applications without prior written permission from <NAME>. */ /* Filename: testsolver.c. */ /* Description: Basic test harness for solver.c. */ extern "C"{ #include "solver.h" } Vars vars; Params params; Workspace work; Settings settings; #define NUMTESTS 0 int main(int argc, char **argv) { int num_iters; #if (NUMTESTS > 0) int i; double time; double time_per; #endif set_defaults(); setup_indexing(); load_default_data(); /* Solve problem instance for the record. */ settings.verbose = 1; num_iters = solve(); #ifndef ZERO_LIBRARY_MODE #if (NUMTESTS > 0) /* Now solve multiple problem instances for timing purposes. */ settings.verbose = 0; tic(); for (i = 0; i < NUMTESTS; i++) { solve(); } time = tocq(); printf("Timed %d solves over %.3f seconds.\n", NUMTESTS, time); time_per = time / NUMTESTS; if (time_per > 1) { printf("Actual time taken per solve: %.3g s.\n", time_per); } else if (time_per > 1e-3) { printf("Actual time taken per solve: %.3g ms.\n", 1e3*time_per); } else { printf("Actual time taken per solve: %.3g us.\n", 1e6*time_per); } #endif #endif return 0; } void load_default_data(void) { params.y_0[0] = 0.20319161029830202; params.r_0[0] = 0.8325912904724193; /* Make this a diagonal PSD matrix, even though it's not diagonal. */ params.q[0] = 1.2909047389129444; /* Make this a diagonal PSD matrix, even though it's not diagonal. */ params.R[0] = 1.510827605197663; params.r_1[0] = 1.5717878173906188; params.r_2[0] = 1.5851723557337523; params.r_3[0] = -1.497658758144655; params.r_4[0] = -1.171028487447253; params.r_5[0] = -1.7941311867966805; params.r_6[0] = -0.23676062539745413; params.r_7[0] = -1.8804951564857322; params.r_8[0] = -0.17266710242115568; params.r_9[0] = 0.596576190459043; params.r_10[0] = -0.8860508694080989; params.r_11[0] = 0.7050196079205251; /* Make this a diagonal PSD matrix, even though it's not diagonal. */ params.q_final[0] = 1.5908628174163508; params.A[0] = -1.9040724704913385; params.A[1] = 0.23541635196352795; params.A[2] = -0.9629902123701384; params.A[3] = -0.3395952119597214; params.A[4] = -0.865899672914725; params.A[5] = 0.7725516732519853; params.A[6] = -0.23818512931704205; params.A[7] = -1.372529046100147; params.A[8] = 0.17859607212737894; params.x_0[0] = 1.1212590580454682; params.x_0[1] = -0.774545870495281; params.x_0[2] = -1.1121684642712744; params.B[0] = -0.44811496977740495; params.B[1] = 1.7455345994417217; params.B[2] = 1.9039816898917352; params.C[0] = 0.6895347036512547; params.C[1] = 1.6113364341535923; params.C[2] = 1.383003485172717; params.u_max[0] = 0.7559880826577783; } <file_sep># AUX_SOURCE_DIRECTORY(${CMAKE_CURRENT_SOURCE_DIR} source) # file(GLOB source "${CMAKE_CURRENT_SOURCE_DIR}/*.c") # add_executable(example testsolver.c ldl.c util.c solver.c matrix_support.c ) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../include) add_library(cvxgen testsolver.c ldl.c util.c solver.c matrix_support.c ) target_link_libraries(cvxgen m) target_include_directories(cvxgen PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) <file_sep>if(${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_BINARY_DIR}) message(FATAL_ERROR "DO NOT BUILD in-tree.") endif() cmake_minimum_required (VERSION 2.8.11) project(example) add_subdirectory(src) add_subdirectory(cvxgen)
f8d33011cadba9fb36cf0f3e73a7ae1f28388da0
[ "Markdown", "CMake", "C++", "Shell" ]
5
Markdown
shino-kei/cvxgen_test
c59e6987c1604199415e01a0229999cfa0a52ecb
b997a5d294a2e6d9f8eea18192ba500d1ffcabc1
refs/heads/master
<file_sep>Rails.application.routes.draw do devise_for :users root to: 'pages#home' # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html get '/kitchen_sink', to: 'pages#kitchen_sink' if Rails.env.development? get '/home_video', to: 'pages#home_video' if Rails.env.development? resources :songs, only: [:index, :destroy] do delete :clear_playlist, on: :collection end resources :playlist_imports, only: [:new, :create] end <file_sep>const loaderHandledInit = () => { document.querySelectorAll(".loader-handled").forEach((element) => { element.addEventListener("click", () => { $('#loading-modal').modal('show'); }); }); }; export { loaderHandledInit }; <file_sep>class UsiczPlayer { constructor(element) { this.element = element this.controls = this.queryControls() this.playing = false this.initButtonHandlers(); } switchSong(song) { window.players.youtube.loadVideoById(song.id) this.currentSong = song this.playSong() this.highlightCurrentSong() } nextSong() { const currentSongRow = document.querySelector(`tr[data-id='${this.currentSong.id}']`) const nextSongRow = currentSongRow.nextElementSibling nextSongRow.querySelector('td').click() } previousSong() { const currentSongRow = document.querySelector(`tr[data-id='${this.currentSong.id}']`) const previousSongRow = currentSongRow.previousElementSibling previousSongRow.querySelector('td').click() } playSong() { window.players.youtube.playVideo() this.element.classList.add('playing') this.playing = true this.updateTrackBar() document.getElementById("artistId").innerHTML = this.currentSong.artist + ` - ` document.getElementById("trackId").innerHTML = this.currentSong.title } pauseSong() { window.players.youtube.pauseVideo() this.element.classList.remove('playing') this.playing = false } // private highlightCurrentSong() { const songRows = document.querySelectorAll('.track-list-row') songRows.forEach((songRow) => { songRow.classList.remove('playing') }) const currentSongRow = document.querySelector(`tr[data-id='${this.currentSong.id}']`) currentSongRow.classList.add('playing') } updateTrackBar() { const duration = players.youtube.getDuration() const currentTime = players.youtube.getMediaReferenceTime() const currentPercentage = ((currentTime * 100) / duration) || 0 this.controls.trackBar.style.width = `${currentPercentage}%` if(this.playing) setTimeout(() => { this.updateTrackBar() }, 500) } queryControls() { return { play: this.element.querySelector('.u-player-play'), pause: this.element.querySelector('.u-player-pause'), previous: this.element.querySelector('.u-player-previous'), next: this.element.querySelector('.u-player-next'), trackBar: this.element.querySelector('.progress-purple') } } initButtonHandlers() { this.controls.play.addEventListener('click', () => { this.playSong() }) this.controls.pause.addEventListener('click', () => { this.pauseSong() }) this.controls.previous.addEventListener('click', () => { this.previousSong() }) this.controls.next.addEventListener('click', () => { this.nextSong() }) } } const initUsiczPlayer = () => { const usiczPlayer = document.querySelector('.usicz-player') if(usiczPlayer) { window.uPlayer = new UsiczPlayer(usiczPlayer) } } export { initUsiczPlayer } <file_sep># Returns list of songs from a given playlist-url class YoutubePlaylistImportService BASE_URL = 'https://www.googleapis.com/youtube/v3/playlistItems' KEY = '<KEY>' TRACK_URL = "https://www.googleapis.com/youtube/v3/videos" def initialize(playlist_url, user_id) @playlist_id = playlist_url.gsub(/.*(&list=)/, "") @platform = Platform.find_by_name('Youtube') @query = "?part=snippet,contentDetails&maxResults=50&playlistId=#{@playlist_id}&key=" @user_id = user_id end def call # take the pl url response = HTTParty.get(BASE_URL + @query + KEY) items = response['items'] @songs = [] # iterate over the items items.each do |song_item| # title = song_item['snippet']['title'] artist = song_item['snippet']['title'].gsub(/( - ).*/, "") title = song_item['snippet']['title'].gsub(/.*( - )/, "") video_id = song_item['contentDetails']['videoId'] track_query = "?part=contentDetails,topicDetails&id=#{video_id}&key=" # use the videoId to get the genre through iteration track_response = HTTParty.get(TRACK_URL + track_query + KEY) if track_response['items'][0] != nil if track_response['items'][0]['topicDetails'] != nil if track_response['items'][0]['topicDetails']['topicCategories'][0] != nil genre_links = track_response['items'][0]['topicDetails']['topicCategories'] genres = genre_links.map { |genre_link| genre_link.gsub(/.*(wiki\/)/, "") } @genre = genres.reject { |i| i == "Music" }.join(", ") duration = track_response['items'][0]['contentDetails']['duration'] minutes = duration.gsub(/(PT)/, "").gsub(/(M)\d*(S)/, "") seconds = duration.gsub(/(S)/, "").gsub(/(PT)\d*(M)/, "") total_duration = (minutes * 60) + seconds # binding.pry end # save the created songs to DB @songs << Song.create!(title: title, genre: @genre, artist: artist, external_id: video_id, platform: @platform, user_id: @user_id, duration: duration) end end end end end <file_sep>class PlaylistImportsController < ApplicationController def new @playlist_import = PlaylistImport.new end def create @playlist_import = PlaylistImport.new(playlist_import_params) if @playlist_import.valid? @platform = Platform.find(playlist_import_params[:platform_id]) platform_service = @platform.import_service.new(playlist_import_params[:playlist_url], current_user.id) platform_service.call redirect_to songs_path(imported: 'success') else render :new end end private def playlist_import_params params.require(:playlist_import).permit(:platform_id, :playlist_url) end end <file_sep>class Song < ApplicationRecord belongs_to :user belongs_to :platform validates :title, :external_id, presence: true def url "https://www.youtube.com/watch?v=#{external_id}" end end <file_sep>namespace :songs do desc "TODO" task destroy_all: :environment do Song.destroy_all end end <file_sep>const trackListRowInit = () => { const footerPlayer = document.querySelector('.usicz-player'); const youtubeListRows = document.querySelectorAll('.track-list-row.youtube'); youtubeListRows.forEach((trackRow) => { const tableDisplays = trackRow.querySelectorAll('td.playable') tableDisplays.forEach((td) => { td.addEventListener('click', (event) => { const externalId = trackRow.dataset.id; const platform = trackRow.dataset.platform; const artist = trackRow.dataset.artist; const title = trackRow.dataset.title; window.uPlayer.switchSong({ id: externalId, platform: platform, artist: artist, title: title }) }) }) }); }; export { trackListRowInit }; <file_sep>class PagesController < ApplicationController skip_before_action :authenticate_user!, only: [:home, :kitchen_sink] def home end def kitchen_sink end def home_video end end <file_sep># Returns list of songs from a given playlist-url class DeezerPlaylistImportService BASE_URL = 'https://api.deezer.com/playlist/' def initialize(playlist_url, user_id) @playlist_id = playlist_url.gsub(/.*(list\/)/, "") @platform = Platform.find_by_name('Deezer') @user_id = user_id end def call # take the pl url response = HTTParty.get(BASE_URL + @playlist_id) tracks = response['tracks']['data'] @songs = [] # iterate over the items tracks.each do |song_item| title = song_item['title'] artist = song_item['artist']['name'] track_id = song_item['id'] # binding.pry # save the created songs to DB @songs << Song.create!(title: title, artist: artist, external_id: track_id, platform: @platform, user_id: @user_id) end end end <file_sep>class PlaylistImport include ActiveModel::Model attr_accessor :platform_id, :playlist_url validates :platform_id, :playlist_url, presence: true end <file_sep>class SongsController < ApplicationController def index if params[:shuffle] @songs = Song.all.shuffle elsif params[:order] @songs = Song.all.order(:title) elsif params[:order_artist] @songs = Song.all.order(:artist) else @songs = Song.all end @songs = [empty_song] if @songs.empty? end def destroy @song = Song.find(params[:id]) @song.destroy respond_to do |format| format.js end end def clear_playlist current_user.songs.destroy_all redirect_to songs_path end private def empty_song Song.new(title: "Empty Playlist", artist: "-", album: "-", genre: "-") end end <file_sep>class Platform < ApplicationRecord has_many :songs validates :name, presence: true def import_service "#{name}PlaylistImportService".constantize end end <file_sep>import "bootstrap"; import { initSmoothscroll } from '../plugins/init_smoothscroll'; import { initSweetalert } from '../plugins/init_sweetalert'; import { SweetalertDelete } from '../plugins/init_sweetalert'; // import { SweetalertClearAll } from '../plugins/init_sweetalert'; import { playlistImported } from '../plugins/init_sweetalert'; import { trackListRowInit } from '../components/yt-player'; import { loaderHandledInit } from '../components/loaderHandledInit'; import { initUsiczPlayer } from '../components/usicz_player'; initSmoothscroll(); loaderHandledInit(); trackListRowInit(); initUsiczPlayer(); // SWEETALERT TRIGGERS initSweetalert('#MusicIcon', { title: "You library is empty", text: "You don’t have any songs yet.\n To play songs, import them first :)", icon: "info", buttons: { import: { text: "Import now!", value: true, }, ok: { text: "Ok", value: false, } }, closeOnClickOutside: true }, (value) => { if (value) { window.location.href = document.querySelector("#MusicIcon").dataset.link; } }); SweetalertDelete('.trashIcon', { title: "You are about to delete this song!", text: "Are you sure?", icon: "warning", buttons: { delete: { text: "Yes, delete", value: true, }, no: { text: "Cancel", value: false, } }, closeOnClickOutside: true }); // SweetalertClearAll('.clear-button', { // title: "You are about to clear your entire playlist!", // text: "This action cannot be undone. Are you sure?", // icon: "warning", // buttons: { // delete: { // text: "Yes, clear everything!", // value: true, // }, // no: { // text: "Cancel", // value: false, // } // }, // closeOnClickOutside: true // }); playlistImported('#display-import-message', { title: "Success!", text: "You have imported a playlist!", button: "Awesome!", icon: "success", timer: 2000, closeOnClickOutside: true } ); <file_sep>import swal from 'sweetalert'; const initSweetalert = (selector, options = {}, callback = () => {}) => { const swalElement = document.querySelector(selector); if (swalElement) { // protect other pages { swal(options).then(callback); }; } }; const SweetalertDelete = (selector, options = {}) => { const swalButtons = document.querySelectorAll(selector); if (swalButtons) { // protect other pages swalButtons.forEach((swalButton) => { swalButton.addEventListener('click', () => { swal(options).then((value) => { console.log(this) if (value) { Rails.ajax({ type: "DELETE", url: `/songs/${swalButton.dataset.link}`, dataType: 'js', accept: 'js', }) } }); }); }); } }; // const SweetalertClearAll = (selector, options = {}) => { // const swalButtons = document.querySelectorAll(selector); // if (swalButtons) { // protect other pages // swalButtons.forEach((swalButton) => { // swalButton.addEventListener('click', () => { // swal(options).then((value) => { // console.log(this) // if (value) { // Rails.ajax({ // type: "DELETE", // url: `/songs/${swalButton.dataset.link}`, // dataType: 'js', // accept: 'js', // }) // } // }); // }); // }); // } // }; const playlistImported = (selector, options = {}) => { const swalElement = document.querySelector(selector); if (swalElement) { // protect other pages { swal(options); }; } }; export { initSweetalert }; export { SweetalertDelete }; // export { SweetalertClearAll }; export { playlistImported }; <file_sep>class ChangeUrlToExternalIdFromSongs < ActiveRecord::Migration[5.2] def change rename_column :songs, :url, :external_id end end <file_sep># This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) puts 'Cleaning database...' Song.destroy_all Platform.destroy_all User.destroy_all puts 'Creating users...' rodrigo = User.create(email: '<EMAIL>', password: '<PASSWORD>') mahan = User.create(email: '<EMAIL>', password: '<PASSWORD>') camille = User.create(email: '<EMAIL>', password: '<PASSWORD>') daniel = User.create(email: '<EMAIL>', password: '<PASSWORD>') puts 'Creating platforms...' youtube = Platform.create(name: 'Youtube') deezer = Platform.create(name: 'Deezer') spotify = Platform.create(name: 'Spotify') soundcloud = Platform.create(name: 'SoundCloud') # puts 'Creating songs...' # song_1 = Song.create(title: "Baltimore", artist: "<NAME>", album: "Sinnerman", genre: "Jazz", external_id: "EJIVV-mnPyY", user_id: camille.id, platform_id: youtube.id) # song_2 = Song.create(title: "Don't go breaking my heart", artist: "<NAME>", album: "Crocodile Rock", genre: "Pop Rock", external_id: "z0qW9P-uYfM", user_id: rodrigo.id, platform_id: deezer.id) # song_3 = Song.create(title: "Let the music play", artist: "<NAME>", album: "Harlem 1965", genre: "Soul", external_id: "1SL9-p-m0gs", user_id: mahan.id, platform_id: deezer.id) # song_4 = Song.create(title: "Lingua", artist: "<NAME> <NAME>", album: "Velô", genre: "Hip Hop", external_id: "tX7cqBreLUY", user_id: daniel.id, platform_id: youtube.id)
5d3af8ece771d0ee5f2a871738f362b9ab9425de
[ "JavaScript", "Ruby" ]
17
Ruby
rodsimon1/usicz
b2389dfcbe3c474bd11740240912101be1db2e12
e2ab9d90eec4f51a214342eb28b3fdc4688c8b0f
refs/heads/master
<file_sep><?php return function(){ static $public = true; $hash = microtime(true); $hash = number_format($hash,6,'.',''); $hash = str_replace('.','',$hash); $hash = random_int(1,9).$hash; $hash = gmp_strval($hash, 36); return $hash; } ?> <file_sep>// ({}).apps('nameMethod',function(response){}); // ({"nameVar":"dataVar"}).apps('nameMethod',function(response){}); // // UPLOAD // EXAMPLE: e.target.files.upload(function(file){}); // FileList.prototype.upload = function(callback){ for(let i=0; i<=this.length-1; i++){ let file = this[i]; let blob = new Blob([file], {type : "application/octet-stream"}); let xhr = new XMLHttpRequest(); xhr.open("POST", "/", true); xhr.responseType = "json"; xhr.onload = function(e) { if (this.status == 200) { let res = this.response; callback(res); } }; xhr.send(blob); } }; // // APPS // EXAMPLE: (function(response){}).apps('nameApps',{'name':'value'}); // Function.prototype.apps = function(name,data){ let callback = this; let blob = new Blob([JSON.stringify(data)], {type : 'application/json'}); let xhr = new XMLHttpRequest(); xhr.open('POST', '/'+name, true); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.responseType = 'json'; xhr.onload = function(e) { if (this.status == 200) { callback(this.response); } }; xhr.send(blob); return this; }; <file_sep><?php require_once(__DIR__.'/../vendor/livesugar/kernel/kernel-zamyatin.php'); ?> <file_sep>let cookie = { set:function(name,value,hours){ let exdate=new Date(); let endH=exdate.getHours()+hours; exdate.setHours(hours); document.cookie=name+ "=" +escape(value)+((hours==null) ? "" : ";expires="+exdate.toGMTString()+"; path=/;"); }, get:function(name){ let start = document.cookie; start = start.split("; "); for(let key in start){ let check = start[key].split("="); if(check[0] == name) { return unescape(check[1]); } } } }; <file_sep><?php return function($db,$execute,$sql){ $sql = $db->prepare($sql); $sql->execute($execute); $res = $sql->fetchAll(); if(isset($res[0])) return $res; else return $sql->errorInfo(); } ?> <file_sep><?php return function($host,$base,$user,$pass) { static $singleton = true; $db = new PDO('pgsql:host='.$host.';dbname='.$base.'',$user,$pass,[PDO::ATTR_PERSISTENT => true]); $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); return $db; }; ?> <file_sep># Documentation ## Install With create directory to latest stability version ``` composer create-project livesugar/framework ``` Current directory ``` composer create-project livesugar/framework . ``` Version of develop to current directory ``` composer create-project --prefer-dist livesugar/framework . dev-master@dev ``` ## Examples Call apps to HTTP GET query ``` http://example.com?apps=uuid ``` Call view to HTTP GET query ``` http://example.com?view=page/index ``` Call apps to PHP file ```php $this->nameapps(); # or $this->namespace->nameapps(); # or $this->categoryapps->nameapps(); ``` Call apps to PHTML file ```html <div><?php echo self::$apps->nameapps() ?></div> <div><?php echo self::$apps->nameclass->namemethod() ?></div> ``` Call view to PHTML file ```html <div><?php echo self::$view->nameview(); ?></div> ``` ## History 1. [WebCMF](https://github.com/xezzus/webcmf) 2. [WebCMF2](https://github.com/xezzus/webcmf2) 3. [WebCMF3](https://github.com/xezzus/webcmf3) 4. [Humanity](https://github.com/xezzus/humanity) 5. [LiveSugar (current)](https://github.com/LiveSugar/framework) <file_sep>#!/bin/sh -e # Create commit /usr/bin/git add -A DATE=`date +%d-%m-%Y' '%H:%M:%S` /usr/bin/git commit -m "$DATE development" /usr/bin/git pull origin master /usr/bin/git push origin master
68dee913545bdab4da2a472f8bb9d7904d17a330
[ "JavaScript", "Markdown", "PHP", "Shell" ]
8
PHP
LiveSugar/framework
73104be99f0b27757e8673cd890f6f8be779ee79
46b65cec1a38ad64db57968949f5e3125ef1ab4c
refs/heads/master
<file_sep>#Import modules import picamera import picamera.array import time import cv2 #Initialize camera camera = picamera.PiCamera() camera.resolution = (640,480) rawCapture = picamera.array.PiRGBArray(camera) #Let camera warm up time.sleep(0.1) #Capture image camera.capture(rawCapture, format="bgr") img = rawCapture.array #Convert to Grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #Blur image to reduce noise blurred = cv2.GaussianBlur(gray, (9, 9), 0) ret,th1 = cv2.threshold(blurred,35,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)#using threshold remave noise ret1,th2 = cv2.threshold(th1,127,255,cv2.THRESH_BINARY_INV)# invert the pixels of the image frame # invert the pixels of the image frame # ret1,th2 = cv2.threshold(th1,127,255,cv2.THRESH_BINARY_INV) contours, hierarchy = cv2.findContours(th2,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) #find the contours # cv2.drawContours(frame,contours,-1,(0,255,0),3) # cv2.imshow('frame',frame) #show video for cnt in contours: if cnt is not None: area = cv2.contourArea(cnt)# find the area of contour if area>=500 : # find moment and centroid M = cv2.moments(cnt) cx = int(M['m10']/M['m00']) cy = int(M['m01']/M['m00']) #SET DIRECTION BASED ON CENTROID(X) ONLY if cx<=150: l=(cx*100/160) PWMR.start (0) PWML.start (0) PWMR1.ChangeDutyCycle (100) PWML1.ChangeDutyCycle (abs(l-25)) time.sleep(.08) elif cx>=170: r=((320-cx)*100/160) PWMR.start (0) PWML.start (0) PWMR1.ChangeDutyCycle (abs(r-25)) PWML1.ChangeDutyCycle (100) time.sleep(.08) elif cx>151 and cx<169: PWMR.start (0) PWML.start (0) PWMR1.ChangeDutyCycle (96) PWML1.ChangeDutyCycle (100) time.sleep(.3) else: PWMR1.start (0) PWML1.start (0) PWMR.ChangeDutyCycle (100) PWML.ChangeDutyCycle (100) time.sleep(.08) else: PWMR1.start (0) PWML1.start (0) PWMR.ChangeDutyCycle (100) PWML.ChangeDutyCycle (100) time.sleep(.08) else: PWMR1.start (0) PWML1.start (0) PWMR.ChangeDutyCycle (100) PWML.ChangeDutyCycle (100) time.sleep(.1) PWMR.start (0) PWMR1.start (0) PWML.start (0) PWML1.start (0
f509e37c61fa987ac687196ceb91c0af141b1329
[ "Python" ]
1
Python
iblack18/henry
a32b7714186c32f79d9b24ceec475e8d09caa1f5
e91c4c9ec4b951d607fa38b3760975f64a11243b
refs/heads/master
<repo_name>ddumin501/Spring<file_sep>/README.md # Spring - Spring의 기초 - mybatis와 연동하기 - Spring-MVC <file_sep>/spring/src/a/First.java package a; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; @Component public class First { private String msg; @Autowired(required = false) @Qualifier("s1") private Second second; private boolean flag; @PostConstruct public void init() { System.out.println("init()호출됨"); flag = true; } public First(String msg) { super(); this.msg = msg; } public First() { super(); // TODO Auto-generated constructor stub } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public String toString() { return "msg=" + msg + ", second.info()=" + second.info(); } } <file_sep>/spring/src/a/Second2.java package a; import org.springframework.stereotype.Component; @Component(value = "s2") public class Second2 implements Second { @Override public String info() { return "Second2객체입니다."; } }<file_sep>/spring-mybatis/src/OrderTest.java import java.sql.Timestamp; import java.util.List; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.my.dao.OrderDAO; import com.my.exception.NotFoundException; import com.my.service.OrderService; import com.my.vo.OrderInfo; import com.my.vo.OrderLine; public class OrderTest { public static void main(String[] args) { //OrderDAOOracle dao= new OrderDAOOracle(); String path = "beans.xml"; ApplicationContext ctx; ctx = new ClassPathXmlApplicationContext(path); //OrderDAO dao = ctx.getBean("orderDAO", com.my.dao.OrderDAO.class); OrderService service = ctx.getBean("orderService", com.my.service.OrderService.class); String id="id1"; try { List<OrderInfo> list = service.findById(id); for(OrderInfo info:list) { int order_no = info.getOrder_no(); Timestamp order_time = info.getOrder_time(); System.out.println("주문기본정보: "+order_no+","+order_time); List<OrderLine> lines = info.getOrderLines(); for(OrderLine line : lines) { String p_no = line.getProduct().getProd_no(); String p_name = line.getProduct().getProd_name(); int p_price = line.getProduct().getProd_price(); int quantity = line.getOrder_quantity(); System.out.println("주문상세정보: "+p_no+","+p_name+","+p_price+","+quantity); } System.out.println("--------------------"); } } catch (NotFoundException e) { System.out.println(e.getMessage()); //--출력 } //------INSERT---------- /* OrderInfo info = new OrderInfo(); Customer c = new Customer(); c.setId(id); info.setCustomer(c);//주문자 List<OrderLine> orderLines = new ArrayList<>(); OrderLine line = new OrderLine(); Product p = new Product(); p.setProd_no("10001"); line.setProduct(p); //주문상품번호 line.setOrder_quantity(2); //주문수량 orderLines.add(line); line = new OrderLine(); //★★★★★새로 객체 생성 필수! 다른 OrderLine임. p = new Product(); p.setProd_no("10003"); line.setProduct(p); //주문상품번호 line.setOrder_quantity(3); //주문수량 orderLines.add(line); info.setOrderLines(orderLines); try{ dao.insert(info); System.out.println("주문 추가 성공!"); //출력 }catch(AddException e) { e.printStackTrace(); } */ } }
728a8934f30343c02ea1a54e10e03c5ccfe0905a
[ "Markdown", "Java" ]
4
Markdown
ddumin501/Spring
35c9df4475fdae8030891bfc6477aca73393e5fa
a52bea36fe82e42f5fee780f9fbaad383c445db4
refs/heads/master
<file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <artifactId>integration</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>integration</name> <parent> <groupId>eu.webdude.movies</groupId> <artifactId>movies</artifactId> <version>0.0.1-SNAPSHOT</version> <relativePath/> </parent> <properties> <camel-spring-boot-starter.version>2.17.0</camel-spring-boot-starter.version> <camel-version>2.22.0</camel-version> <java.version>1.10</java.version> <javax.version>1.1.1</javax.version> <univocity-parsers.version>2.7.5</univocity-parsers.version> <activemq.version>5.15.5</activemq.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-spring-boot-starter</artifactId> <version>${camel-spring-boot-starter.version}</version> </dependency> <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-bindy</artifactId> <version>${camel-version}</version> </dependency> <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-http4</artifactId> <version>${camel-version}</version> </dependency> <dependency> <groupId>javax.activation</groupId> <artifactId>activation</artifactId> <version>${javax.version}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-activemq</artifactId> </dependency> <dependency> <groupId>org.apache.activemq</groupId> <artifactId>activemq-camel</artifactId> <version>${activemq.version}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.reflections</groupId> <artifactId>reflections</artifactId> <version>0.9.11</version> </dependency> <dependency> <groupId>eu.webdude.movies</groupId> <artifactId>model</artifactId> <version>${project.version}</version> <scope>compile</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> <file_sep># Movies Expose the IMDB movies database ### 1. Create db and user: ### The required database is mysql. CREATE DATABASE movies CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; CREATE USER 'movies'@'localhost' identified by 'movies'; GRANT INDEX, ALTER, CREATE, DROP, SELECT, INSERT, DELETE, UPDATE, REFERENCES, LOCK TABLES ON movies.* TO 'movies'@'localhost'; <file_sep>package eu.webdude.movies.integration.imdbimport.route; import eu.webdude.movies.integration.aggregator.ArrayListAggregationStrategy; import org.apache.camel.Processor; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.spi.DataFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class ImdbImportRoute extends RouteBuilder { private static final String BASE_DOWNLOAD_URI = "http4://datasets.imdbws.com/"; private final ImdbImportRouteMetaInformation routeMetaInfo = this.getClass().getAnnotationsByType(ImdbImportRouteMetaInformation.class)[0]; private Logger logger = LoggerFactory.getLogger(ImportJmsRoute.class); public abstract DataFormat getOutputFormat(); @Override public void configure() { var newLine = "\n"; var bindyFormat = getOutputFormat(); var aggregationStrategy = new ArrayListAggregationStrategy(); var downloadFileName = routeMetaInfo.downloadFileName(); var isNotHeader = simple("${property.CamelSplitIndex} > 0"); from(routeMetaInfo.sourceComponent()) .log("Import data from IMDB. Using file " + downloadFileName) .to(BASE_DOWNLOAD_URI + downloadFileName) .log("File " + downloadFileName + " downloaded") .process(preImportHook()) .unmarshal().gzip() .onCompletion() .split(body().tokenize(newLine)).streaming() .choice() .when(isNotHeader) .unmarshal(bindyFormat) .aggregate(constant(true), aggregationStrategy).completionSize(1000).completionTimeout(2000) .bean(routeMetaInfo.destinationBean()); } Processor preImportHook() { return exchange -> logger.info("Running pre import hook!"); } }<file_sep>package eu.webdude.movies.integration.imdb.service; import eu.webdude.movies.integration.imdbimport.dto.PersonInfoDTO; import eu.webdude.movies.integration.imdbimport.service.NameImportService; import eu.webdude.movies.model.Person; import eu.webdude.movies.model.Profession; import eu.webdude.movies.model.repository.PersonRepository; import eu.webdude.movies.model.repository.ProfessionRepository; import org.junit.Before; import org.junit.Test; import org.mockito.MockitoAnnotations; import org.mockito.Spy; import java.lang.reflect.InvocationTargetException; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.IntStream; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.*; public class NameImportServiceTest { @Spy private PersonRepository personRepository; @Spy private ProfessionRepository professionRepository; private NameImportService nameImportProcessor; private List<PersonInfoDTO> testPeople; private Profession testProfession = new Profession("actor"); @Before public void setUp() { MockitoAnnotations.initMocks(this); nameImportProcessor = new NameImportService(personRepository, professionRepository); testPeople = getMockData(10); } private List<PersonInfoDTO> getMockData(int count) { return IntStream.range(0, count) .mapToObj(this::getMockPersonInfoDTO) .collect(Collectors.toList()); } private PersonInfoDTO getMockPersonInfoDTO(int seed) { var person = new PersonInfoDTO(); person.setBirthYear("194" + seed); person.setDeathYear("200" + seed); person.setKnownForTitles("Die Hard " + seed); person.setName("<NAME>"); person.setNameRelation("s20123" + seed); person.setPrimaryProfession("actor"); return person; } @Test public void testHandleImport() { when(professionRepository.save(testProfession)).thenReturn(testProfession); when(professionRepository.findByName(testProfession.getName())).thenReturn(Optional.of(testProfession)); nameImportProcessor.handleImport(testPeople); verify(personRepository, only()).saveAll(anyList()); verifyNoMoreInteractions(personRepository); } @Test public void testMapToPerson() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { var personInfoDTO = testPeople.get(0); var method = nameImportProcessor.getClass().getDeclaredMethod("mapToPerson", PersonInfoDTO.class); method.setAccessible(true); var resultPerson = (Person) method.invoke(nameImportProcessor, personInfoDTO); assertEquals(personInfoDTO.getName(), resultPerson.getFullName()); assertEquals(personInfoDTO.getBirthYear(), resultPerson.getBirthYear()); assertEquals(personInfoDTO.getDeathYear(), resultPerson.getDeathYear()); assertEquals(personInfoDTO.getNameRelation(), resultPerson.getExternalKey()); } @Test public void newPersonShouldBeCreatedIfSuchDoesNotExist() { when(professionRepository.save(testProfession)).thenReturn(testProfession); when(professionRepository.findByName(testProfession.getName())).thenReturn(Optional.empty()); nameImportProcessor.handleImport(testPeople); verify(personRepository, only()).saveAll(anyList()); verify(professionRepository, times(testPeople.size())).save(any(Profession.class)); verify(professionRepository, times(testPeople.size())).findByName(testProfession.getName()); verifyNoMoreInteractions(personRepository, professionRepository); } }<file_sep>package eu.webdude.movies.web.rest; import eu.webdude.movies.web.service.IntegrationService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(value = "/integration/import") public class IntegrationImportController { private final IntegrationService service; @Autowired public IntegrationImportController(IntegrationService service) { this.service = service; } @RequestMapping(value = "/names", method = RequestMethod.POST) public ResponseEntity<?> importNames() { service.importData(); return ResponseEntity.accepted().build(); } } <file_sep>package eu.webdude.movies.web.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jms.core.JmsTemplate; import org.springframework.stereotype.Service; @Service public class IntegrationServiceImpl implements IntegrationService { private final JmsTemplate jmsTemplate; private static final Logger logger = LoggerFactory.getLogger(IntegrationServiceImpl.class); @Autowired public IntegrationServiceImpl(JmsTemplate jmsTemplate) { this.jmsTemplate = jmsTemplate; } @Override public void importData() { logger.debug("Sending the import data start command!"); jmsTemplate.convertAndSend(""); } } <file_sep>package eu.webdude.movies.integration.imdbimport.route; import eu.webdude.movies.integration.imdbimport.dto.TitleDTO; import org.apache.camel.dataformat.bindy.csv.BindyCsvDataFormat; import org.apache.camel.spi.DataFormat; import org.springframework.stereotype.Component; @Component @ImdbImportRouteMetaInformation( sourceComponent = "direct:import-titles", downloadFileName = "title.akas.tsv.gz", destinationBean = "titleImportService" ) public class TitleImportRoute extends ImdbImportRoute { @Override public DataFormat getOutputFormat() { return new BindyCsvDataFormat(TitleDTO.class); } } <file_sep>package eu.webdude.movies.model; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import javax.persistence.*; import java.util.HashSet; import java.util.Set; @Entity @Table(name = "profession", uniqueConstraints = {@UniqueConstraint(columnNames = {"name"})}) public class Profession extends BaseModel { static final String ID_NAME = "profession_id"; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = ID_NAME) private Long id; @Column(name = "name") private String name; @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.MERGE) @JoinTable(name = "person_profession", joinColumns = @JoinColumn(name = ID_NAME), inverseJoinColumns = @JoinColumn(name = Person.ID_NAME)) private Set<Person> people = new HashSet<>(); public Profession(String name) { this.name = name; } public Profession() { } 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 Set<Person> getPeople() { return people; } public void setPeople(Set<Person> people) { this.people = people; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Profession)) return false; Profession that = (Profession) o; return new EqualsBuilder() .append(getId(), that.getId()) .append(getName(), that.getName()) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(17, 37) .append(getId()) .append(getName()) .toHashCode(); } } <file_sep>package eu.webdude.movies.web.dto; public class ExceptionDTO { private String userMessage; private String developerMessage; public ExceptionDTO(String userMessage) { this(userMessage, null); } public ExceptionDTO(String userMessage, String developerMessage) { this.userMessage = userMessage; this.developerMessage = developerMessage; } public String getUserMessage() { return userMessage; } public void setUserMessage(String userMessage) { this.userMessage = userMessage; } public String getDeveloperMessage() { return developerMessage; } public void setDeveloperMessage(String developerMessage) { this.developerMessage = developerMessage; } } <file_sep>package eu.webdude.movies.integration.imdbimport.route; import eu.webdude.movies.integration.imdbimport.dto.PersonInfoDTO; import eu.webdude.movies.model.repository.PersonRepository; import org.apache.camel.Processor; import org.apache.camel.dataformat.bindy.csv.BindyCsvDataFormat; import org.apache.camel.spi.DataFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component @ImdbImportRouteMetaInformation( sourceComponent = "direct:import-people", downloadFileName = "name.basics.tsv.gz", destinationBean = "nameImportService" ) public class PeopleImportRoute extends ImdbImportRoute { private final Processor processor; private Logger logger = LoggerFactory.getLogger(PeopleImportRoute.class); @Autowired public PeopleImportRoute(PersonRepository repository) { processor = exchange -> { logger.info("Deleted all of the people previously added in the database."); repository.deleteAll(); }; } @Override public DataFormat getOutputFormat() { return new BindyCsvDataFormat(PersonInfoDTO.class); } @Override Processor preImportHook() { return processor; } } <file_sep>package eu.webdude.movies.model; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import javax.persistence.*; import java.util.HashSet; import java.util.Set; @Entity(name = "person") public class Person extends RemoteReferencedModel { static final String ID_NAME = "person_id"; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = ID_NAME) private Long id; @Column(name = "full_name") private String fullName; @Column(name = "birth_year") private String birthYear; @Column(name = "death_year") private String deathYear; @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.MERGE) @JoinTable(name = "person_profession", joinColumns = @JoinColumn(name = ID_NAME), inverseJoinColumns = @JoinColumn(name = Profession.ID_NAME)) private Set<Profession> professions = new HashSet<>(); public static String getIdName() { return ID_NAME; } public Set<Profession> getProfessions() { return professions; } public void setProfessions(Set<Profession> professions) { this.professions = professions; } public void addProfession(Profession profession) { professions.add(profession); } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public String getBirthYear() { return birthYear; } public void setBirthYear(String birthYear) { this.birthYear = birthYear; } public String getDeathYear() { return deathYear; } public void setDeathYear(String deathYear) { this.deathYear = deathYear; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Person)) return false; Person person = (Person) o; return new EqualsBuilder() .append(getId(), person.getId()) .append(getFullName(), person.getFullName()) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(17, 37) .append(getId()) .append(getFullName()) .toHashCode(); } }
f57de966dd56c478e2aa9b1b37276e1ed3071315
[ "Markdown", "Java", "Maven POM" ]
11
Maven POM
webdude21/movies
532012d5d307edd0ca766b0bc61498617a34cab5
24bb0383feeec28056f8db59f7c618f464f0e832
refs/heads/master
<repo_name>untael/partysearcher-backend<file_sep>/src/connect.js import Axios from 'axios' import Qs from 'qs' const connect = Axios.create({ baseURL: `${HTTPS ? 'https' : 'http'}://${API_URL}`, paramsSerializer: (params) => { return Qs.stringify(params) }, }) export default axiosInstance <file_sep>/routes/router.js const express = require('express') const router = express.Router() const User = require('../schemas/user') const Game = require('../schemas/game') const GameRoom = require('../schemas/gameRoom') //USER ACTIONS // GET route for reading data router.get('/', function (req, res, next) { console.log(req.session.userId) User.findById(req.session.userId) .exec(function (error, user) { if (error) { return next(error) } else { if (user === null) { var err = new Error('Not authorized! Go back!') err.status = 400 return next(err) } else { } } }) }) //Save registered user to database router.post('/register', function (req, res) { const user = new User({ username: req.body.user.username, password: <PASSWORD>, }) user.save(function (err) { if (err) return handleError(err) }) res.send(user) }) router.get('/check-user', function (req, res, next) { console.log(req.session.userId) User.findById(req.session.userId) .exec(function (error, user) { if (error) { return next(error) } else { if (user === null) { var err = new Error('Not authorized! Go back!') err.status = 400 return next(err) } else { console.log(user) res.send(user) } } }) }) router.post('/login', function (req, res, next) { User.authenticate(req.body.user.username, req.body.user.password, function (error, user) { if (error || !user) { var err = new Error('Wrong username or password.') err.status = 401 return next(err) } else { console.log(req.session) req.session.userId = user._id res.redirect('/check-user') } }) }) // GET route after registering // router.get('/profile', function (req, res, next) { // User.findById(req.session.userId) // .exec(function (error, user) { // if (error) { // return next(error) // } else { // if (user === null) { // var err = new Error('Not authorized! Go back!') // err.status = 400 // return next(err) // } else { // console.log(req.session) // } // } // }) // }) // GET for logout logout router.get('/logout', function (req, res, next) { // console.log(req.session) if (req.session) { // delete session object req.session.destroy(function (err) { if (err) { return next(err) } else { res.send('Session destroyed') // return res.redirect('/') } }) } }) //GAMEROOM ACTIONS router.post('/create-gameroom', function (req, res) { const gameRoom = new GameRoom({ username: req.body.gameRoom.username, game: req.body.gameRoom.game, description: req.body.gameRoom.description, }) gameRoom.save(function (err) { if (err) return handleError(err) }) res.send(gameRoom) }) router.get('/gameroomlist', function (req, res) { GameRoom.find({}).then(gameRooms => { // Presenter const gameRoomsToPresent = gameRooms.map(gameRoom => { return { id: gameRoom._id, username: gameRoom.username, game: gameRoom.game, description: gameRoom.description, } }) res.send(gameRoomsToPresent) // console.log(gameRooms) }) }) router.get('/gameroomexplorer', function (req, res) { GameRoom.find({}).then(gameRooms => { // Presenter const gameRoomsToPresent = gameRooms.map(gameRoom => { return { id: gameRoom._id, username: gameRoom.username, game: gameRoom.game, description: gameRoom.description, } }) res.send(gameRoomsToPresent) // console.log(gameRooms) }) }) //GAME ACTIONS router.get('/gamelist', function (req, res) { Game.find({}).then(games => { // Presenter const gamesToPresent = games.map(game => { return { id: game._id, name: game.name, description: game.description, } }) res.send(gamesToPresent) // console.log(games) }) }) router.post('/create-game', function (req, res) { const game = new Game({ name: req.body.game.name, description: req.body.game.description, }) game.save(function (err) { if (err) return handleError(err) }) res.send(game) }) router.post('/delete-game', function (req, res) { const game = new Game({ id: req.body.game.id, name: req.body.game.name, description: req.body.game.description, }) Game.find({ _id: game.id, }) .remove().then(_ => console.log('Removed')) res.send(game) }) router.post('/update-game', function (req, res) { const game = new Game({ id: req.body.game.id, name: req.body.game.name, description: req.body.game.description, }) Game.findByIdAndUpdate(game.id, { $set: { name: req.body.game.name, description: req.body.game.description, }, }, { new: true }, function (err, game) { if (err) return handleError(err) res.send(game) }) }) module.exports = router<file_sep>/src/Game/GameActions.js //-----------todo To Module const mongoose = require('mongoose') //connect to db by URL mongoose.connect('mongodb://localhost/psdb') //to succesful start .then(() => console.log('MongoDB has started ...')) //to errors .catch(e => console.log(e)) //----------------- let express = require('express') let cors = require('cors') let app = express() let router = express.Router(); app.use(cors()) const bodyParser = require('body-parser') app.use(bodyParser.json()) app.use(bodyParser.urlencoded({ extended: true })) //connect model to use Schema require('../../schemas/game') const Game = mongoose.model('games') require('../../schemas/gameRoom') const GameRoom = mongoose.model('gameRooms') app.get('/gamelist', function (req, res) { Game.find({}).then(games => { // Presenter const gamesToPresent = games.map(game => { return { id: game._id, name: game.name, description: game.description } }) res.send(gamesToPresent) console.log(games) }) }); app.get('/gameroomlist', function (req, res) { GameRoom.find({}).then(gameRooms => { // Presenter const gameRoomsToPresent = gameRooms.map(gameRoom => { return { id: gameRoom._id, username: gameRoom.username, game: gameRoom.game, description: gameRoom.description } }) res.send(gameRoomsToPresent) console.log(gameRooms) }) }); app.get('/gameroomexplorer', function (req, res) { GameRoom.find({}).then(gameRooms => { // Presenter const gameRoomsToPresent = gameRooms.map(gameRoom => { return { id: gameRoom._id, username: gameRoom.username, game: gameRoom.game, description: gameRoom.description } }) res.send(gameRoomsToPresent) console.log(gameRooms) }) }); app.post('/create-game', function (req, res) { const game = new Game({ name: req.body.game.name, description: req.body.game.description, }) game.save(function (err) { if (err) return handleError(err) }) res.send(game) }) app.post('/delete-game', function (req, res) { const game = new Game({ id: req.body.game.id, name: req.body.game.name, description: req.body.game.description, }) Game.find({ _id: game.id, }) .remove().then(_ => console.log('Removed')) res.send(game) }) app.post('/update-game', function (req, res) { const game = new Game({ id: req.body.game.id, name: req.body.game.name, description: req.body.game.description, }) Game.findByIdAndUpdate(game.id, { $set: { name: req.body.game.name, description: req.body.game.description, }, }, { new: true }, function (err, game) { if (err) return handleError(err) res.send(game) }) }) app.post('/create-gameroom', function (req, res) { const gameRoom = new GameRoom({ username: req.body.gameRoom.username, game: req.body.gameRoom.game, description: req.body.gameRoom.description, }) gameRoom.save(function (err) { if (err) return handleError(err) }) res.send(gameRoom) }) app.listen(3000, function () { console.log('Example app listening on port 3000!') })<file_sep>/schemas/gameRoom.js const mongoose = require('mongoose') const Schema = mongoose.Schema module.exports = mongoose.model('GameRoom', new Schema({ id: { type: String, }, username: { type: String, required: true, }, game: { type: String, required: true, }, description: { type: String, default: '', required: true, }, users: { type: Array, required: false, }, }))
9e0597a765bea11becdc9494ef3f198086c24bb8
[ "JavaScript" ]
4
JavaScript
untael/partysearcher-backend
5004e901406640a645fa751402f8d60f67a3700d
0553230cf6a2c1d071c0f100a77fa900671c06c1
refs/heads/master
<repo_name>KienHeo/csharp-tutorial-for-beginners<file_sep>/IfElse and SwitchCase/Exercises.cs using System; namespace Conditionals { public class Exercises { public static void Main(string[] argc) { /*// Exercise 1: Console.Write("Enter a number: "); var number = int.Parse(Console.ReadLine()); if (number <= 10 && number >= 1) Console.WriteLine("Valid."); else Console.WriteLine("Invalid.");*/ /*// Exercise 2: Console.WriteLine("Enter two numbers: "); Console.Write("Number 1 = "); var number1 = int.Parse(Console.ReadLine()); Console.Write("Number 2 = "); var number2 = int.Parse(Console.ReadLine()); // display maximum of two numbers var maximum = Math.Max(number2, number1); Console.WriteLine($"Maximum value = {{0}}", maximum);*/ /*// Exercise 3: Console.WriteLine("Enter the width and height of an image: "); Console.Write("Width = "); var width = int.Parse(Console.ReadLine()); Console.Write("Height = "); var height = int.Parse(Console.ReadLine()); if (width > height) { Console.WriteLine("The image is landscape."); } else if (width < height) { Console.WriteLine("The image is portrait."); } else { Console.WriteLine("I dunno what type of that image!!!"); }*/ // Exercise 4: Console.Write("Enter the speed limit: "); var speedLimit = int.Parse(Console.ReadLine()); if (speedLimit <= 0) { Console.WriteLine("Wrong input!!!. Do it again."); } Console.Write("Enter the speed of car: "); var carSpeed = int.Parse(Console.ReadLine()); if (carSpeed < speedLimit) { Console.WriteLine("Ok."); } else { if (carSpeed <= speedLimit) return; var demeritPoints = (carSpeed - speedLimit > 5) ? (carSpeed - speedLimit) / 5 : 0; if (demeritPoints > 12) { Console.WriteLine("License Suspended."); } else { Console.WriteLine($"Demerit Points = {{0}}", demeritPoints); } } } } }<file_sep>/Enums/Program.cs using System; namespace Enums { public enum ShippingMethod { RegularAirMail = 1, RegisteredAirMail = 2, Express = 3 } class Program { static void Main(string[] args) { const ShippingMethod method = ShippingMethod.Express; Console.WriteLine((int) method); const int methodId = 3; Console.WriteLine((ShippingMethod) methodId); Console.WriteLine(method.ToString()); const string methodName = "Express"; // var a = Enum.Parse<ShippingMethod>(methodName); var shippingMethod = (ShippingMethod) Enum.Parse(enumType: typeof(ShippingMethod), value: methodName); Console.WriteLine(shippingMethod); } } }<file_sep>/LiveCodingSummarisingText/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LiveCodingSummarisingText { public class Program { public static void Main(string[] args) { string sentence = "This is going to be a really really really really really really long text."; var summary = StringUltility.SummerizeText(sentence, 25); Console.WriteLine(summary); } } }<file_sep>/Strings/Program.cs using System; namespace Strings { public class Program { public static void Main(string[] args) { const string firstName = "Mosh"; const string lastName = "Hamedani"; var myFullName = string.Format("My name is {0} {1}", firstName, lastName); var names = new string[] { "John", "Jack", "Mary" }; var formmatedNames = string.Join(",", names); Console.WriteLine(formmatedNames); const string text = @"Hi John Look into the following paths c:\folder1\folder2 c:\folder3\folder4"; Console.WriteLine(text); } } }<file_sep>/Lists/Exercises.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Lists { internal class Exercises { public static void Main(string[] args) { /*// ex1: var nameList = new List<string>(); while (true) { Console.Write("Enter a name: "); var name = Console.ReadLine(); if (string.IsNullOrEmpty(name) || string.IsNullOrWhiteSpace(name)) { break; } nameList.Add(name); Console.Write("Press Enter to exit. Or type any word to continue. Your choice is: "); var choice = Console.ReadLine(); if (choice == string.Empty) { break; } } switch (nameList.Count) { case 0: Console.WriteLine(); // Console.WriteLine("Count = " + nameList.Count); break; case 1: Console.WriteLine("{0} likes your post.", nameList[0]); // Console.WriteLine("Count = " + nameList.Count); break; case 2: Console.WriteLine("{0} and {1} like your post.", nameList[0], nameList[1]); // Console.WriteLine("Count = " + nameList.Count); break; default: Console.WriteLine("{0}, {1} and {2} others like your post.", nameList[0], nameList[1], nameList.Count - 2); // Console.WriteLine("Count = " + nameList.Count); break; }*/ /*// ex2: Console.Write("Enter Your Name = "); var name = Console.ReadLine(); var c = name?.ToCharArray(); Array.Reverse(c); Console.WriteLine("Reverse the name is: " + new string(c));*/ /*// ex3: var listNumber = new List<int>(); var i = 0; while (true) { Console.WriteLine("Enter five unique numbers: "); for (; i < 5; i++) { Console.Write("Enter number {0}: ", i + 1); var testNumber = int.Parse(Console.ReadLine()); if (CheckNumberExist(listNumber, testNumber)) { listNumber.Add(testNumber); } else { Console.Write("Found duplicate number. Type \"yes\" to re-try or \"no\" to stop. Your choice: "); var choice = Console.ReadLine(); if (choice == "yes") continue; if (choice == "no") break; } } break; } listNumber.Sort(); Console.Write("Sorted List is: "); foreach (var number in listNumber) { Console.Write("\t" + number); } Console.WriteLine();*/ /*// ex4: var listNumber = new List<int>(); while (true) { Console.Write("Enter a number: "); var number = int.Parse(Console.ReadLine()); RemoveDuplicateNumber(listNumber, number); listNumber.Add(number); Console.Write("Type \"Quit\" to exit. Your choice: "); var choice = Console.ReadLine(); if (choice != "Quit") { continue; } break; } Console.Write("Unique List Number is: "); foreach (var number in listNumber) { Console.Write("\t" + number); } Console.WriteLine();*/ // ex5: /*while (true) { Console.WriteLine("Enter the list: "); var listNumber = Console.ReadLine(); var stringArray = listNumber.Split(","); if (CheckInvalid(stringArray)) { Console.Write("Invalid List. Do you want to continue. Your choice: "); } }*/ } public static bool CheckNumberExist(List<int> list, int testNumber) { foreach (var number in list) { if (testNumber == number) { return false; } } return true; } public static void RemoveDuplicateNumber(List<int> list, int testNumber) { for (var i = 0; i < list.Count; i++) { if (testNumber == list[i]) { list.Remove(list[i]); } } } public static bool CheckInvalid(string[] stringArray) { foreach (var s in stringArray) { if (string.IsNullOrEmpty(s)) { return true; } } if (stringArray.Length < 5) { return true; } return false; } } }<file_sep>/Iterations/Exercises.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Iterations { class Exercises { public static void Main(string[] argc) { /*// ex1 var j = 0; for (var i = 1; i <= 100; i++) { if (i % 3 != 0) continue; j++; } Console.WriteLine(j);*/ /* // ex2 int sum = 0; string s = ""; while (s != "ok") { Console.Write("Enter the number: "); int number = int.Parse(Console.ReadLine()); Console.Write("Enter \"ok\" to exit or keep enter number by enter nothing. Your choice: "); s = Console.ReadLine(); sum += number; } Console.WriteLine("Sum = " + sum);*/ /*// ex3 Console.Write("Enter number for calculating factorial: "); var number = int.Parse(Console.ReadLine()); Console.WriteLine(string.Format($"{{0}}! = {{1}}", number, Factorial(number)));*/ /*// ex4 var random = new Random(); var randomNumber = random.Next(1, 10); Console.WriteLine("Random Number = " + randomNumber); var count = 0; while (count < 4) { Console.Write("Enter the number to guest: "); var guestNumber = int.Parse(Console.ReadLine()); Console.WriteLine(guestNumber == randomNumber ? "Great Job." : "You SUCK."); count++; }*/ // ex5 Console.Write("Enter a series of numbers: "); var s = Console.ReadLine(); var array = s?.Split(","); var maximum = FindMaximum(array); Console.WriteLine(maximum); } public static int Factorial(int i) { if (i == 0) { return 1; } return i * Factorial(i - 1); } public static int FindMaximum(string[] strings) { var max = int.Parse(strings[0]); foreach (var s in strings) { if (int.Parse(s) >= max) { max = int.Parse(s); } } return max; } } }
53576da96f50b694c7fc23d07c4ebaf64b1eef8d
[ "C#" ]
6
C#
KienHeo/csharp-tutorial-for-beginners
db5d613fd74a7b697aa2b3f8776314ac80394a3b
b8f36341b3dc9272e3d4e77f85dc825ade9f6ac4
refs/heads/master
<repo_name>y-endo/learn-jest<file_sep>/README.md # LearnJest Jest学習用リポジトリ <file_sep>/src/VueButton/index.test.js import { mount } from '@vue/test-utils'; import VueButton from './index'; describe('VueButton', () => { const wrapper = mount(VueButton, { propsData: { text: 'テスト' } }); it('props.textが正しく表示されている', () => { expect(wrapper.html()).toContain('<p>テスト</p>'); }); it('ボタンをクリックしたときにEmitが正しく行われている', () => { const button = wrapper.find('button'); button.trigger('click'); // Emit 'clicked' が発行されたか expect(wrapper.emitted().clicked).toBeTruthy; }); });
0652b644c3bf7833624e2a39d682fe72f8609e94
[ "Markdown", "JavaScript" ]
2
Markdown
y-endo/learn-jest
face214fb5baf76b8408923d2d08b6a540857bd5
1bbf7109a06321e7adfc14d78e1142d126b8266f
refs/heads/master
<repo_name>Marcos2Junior/Trabalho1Cacao4Semestre<file_sep>/login.php <?php require('./autoloader.php'); $usuarios = new Usuarios(); $status = $usuarios->verificaStatus(); if($status != 0) { die("Você já está logado!"); } if($_POST) { $destino = $usuarios->logarUsuario($_POST['usuario'], $_POST['senha']); die("<meta http-equiv='refresh' content='0;url=$destino'>"); } ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/> <title>Lo<NAME> do Jarbas | Login</title> <link rel="stylesheet" href="style/style.css" /> <script src="https://kit.fontawesome.com/a076d05399.js"></script> </head> <body> <p><?php if(isset($_GET['msg']) && $_GET['msg']) { echo "<label style='color: red'>Usuário ou senha errados!</label>"; } ?></p> <form method="POST" action="login.php" class="form"> <div style="padding: 10px; text-align: center; font-size: 20pt;"> <a href="index.php"><i class='fas fa-times' style="float: right; cursor: pointer; font-size: 20pt;"></i></a> <label>Entre com sua conta</label> </div> <label>Login:</label><br /> <input type="text" name="usuario" placeholder="Seu usuario" /><br /> <label>Senha:</label><br /> <input type="password" name="senha" placeholder="<PASSWORD>" /> <input type="submit" value="Enviar"/> <p> Ainda não possui um cadastro? <a style="cursor: pointer;" href="registrar.php">Crie sua conta agora!</a> </p> </form> </body> </html><file_sep>/minhaloja.sql -- phpMyAdmin SQL Dump -- version 5.0.2 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Tempo de geração: 13-Jul-2020 às 00:34 -- Versão do servidor: 10.4.13-MariaDB -- versão do PHP: 7.4.7 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Banco de dados: `minhaloja` -- CREATE DATABASE IF NOT EXISTS `minhaloja` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci; USE `minhaloja`; -- -------------------------------------------------------- -- -- Estrutura da tabela `produtos` -- CREATE TABLE `produtos` ( `id` int(11) NOT NULL, `busca` varchar(45) NOT NULL, `ordem` int(11) NOT NULL, `limite` int(11) NOT NULL, `titulo` varchar(50) NOT NULL, `preco` decimal(10,2) NOT NULL, `valorold` decimal(10,2) NOT NULL, `caminho` varchar(23) NOT NULL, `grupo` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Extraindo dados da tabela `produtos` -- INSERT INTO `produtos` (`id`, `busca`, `ordem`, `limite`, `titulo`, `preco`, `valorold`, `caminho`, `grupo`) VALUES (14, '', 0, 0, 'Calça Moletom', '199.90', '400.00', '2020.07.13-00.30.40.jpg', 1), (15, '', 0, 0, 'Relógio muito bonito', '1999.90', '2000.00', '2020.07.12-22.47.33.jpg', 1), (16, '', 0, 0, 'Tênis marca boa', '300.00', '499.00', '2020.07.12-22.47.47.jpg', 1), (17, '', 0, 0, 'Tênis esportivo', '789.90', '400.00', '2020.07.12-22.47.58.jpg', 1), (18, '', 0, 0, 'Camiseta Alternativa', '70.00', '99.90', '2020.07.12-22.48.07.jpg', 1), (19, '', 0, 0, 'Camiseta Branca', '21.99', '50.00', '2020.07.12-22.48.16.jpg', 1), (20, '', 0, 0, 'Kit 6 camisetas', '300.00', '399.90', '2020.07.12-22.48.25.jpg', 2), (21, '', 0, 0, 'Camiseta Leão', '69.90', '70.00', '2020.07.12-22.48.35.jpg', 2), (22, '', 0, 0, 'Skate radical', '350.99', '299.90', '2020.07.13-00.31.44.jpg', 2); -- -------------------------------------------------------- -- -- Estrutura da tabela `usuarios` -- CREATE TABLE `usuarios` ( `id` int(11) NOT NULL, `usuario` varchar(45) NOT NULL, `senha` varchar(32) NOT NULL, `admin` char(1) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Extraindo dados da tabela `usuarios` -- INSERT INTO `usuarios` (`id`, `usuario`, `senha`, `admin`) VALUES (1, 'marcos747', '<PASSWORD>', '1'), (6, 'cacao', '81dc9bdb52d04dc20036dbd8313ed055', '1'), (7, 'cliente', '81dc9bdb52d04dc20036dbd8313ed055', '0'), (8, 'marcos123', '432f45b44c432414d2f97df0e5743818', '1'); -- -- Índices para tabelas despejadas -- -- -- Índices para tabela `produtos` -- ALTER TABLE `produtos` ADD PRIMARY KEY (`id`); -- -- Índices para tabela `usuarios` -- ALTER TABLE `usuarios` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT de tabelas despejadas -- -- -- AUTO_INCREMENT de tabela `produtos` -- ALTER TABLE `produtos` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=23; -- -- AUTO_INCREMENT de tabela `usuarios` -- ALTER TABLE `usuarios` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/conta.php <?php require('./autoloader.php'); $usuarios = new Usuarios(); $status = $usuarios->verificaStatus(); $db = new Database; $valor = ''; if($status == 0) { die('Você não possui acesso a esta área'); } if(empty($_SESSION['uid'])) { die('<meta http-equiv="refresh" content="0;url=index.php">'); } else { $id = $_SESSION['uid']; } if($_POST) { $valor = $usuarios->alterarUsuario($id, $_POST['usuario'], $_POST['senha'], $_POST['confsenha'], $_POST['senhaatual'], 0); } $usuario = $db->pegarDado("usuarios", "*", "id = $id"); ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/> <title>Loja do Marcão e do Jarbas | Minha conta</title> <link rel="stylesheet" href="style/style.css" /> <script src="https://kit.fontawesome.com/a076d05399.js"></script> </head> <body> <?php echo '<p>Olá <span style="font-size: x-large">'. $_SESSION['user'].'</span>, Seja bem vindo!'; if($status == 2) { echo '<br><br><a href="admin/index.php" style="font-size: large; color: white">Clique para acessar Administrativo</a></p>'; } else { echo '</p>'; } ?> <form method="POST" action="conta.php?id=<?php echo $id; ?>" class="form"> <div style="padding: 10px; text-align: center; font-size: 20pt;"> <a href="index.php"><i class='fas fa-times' style="float: right; cursor: pointer; font-size: 20pt;"></i></a> <label>Minha conta</label> </div> <?php if(!empty($valor)) { echo '<br><div style="text-align: center"> <label style="color: darkturquoise; font-size: x-large"> '. $valor .'</label> </div><br><br>'; } ?> <label>Alterar dados</label><br><br> <label>Seu novo Login :</label><br /> <input type="text" name="usuario" value="<?php echo $usuario['usuario']; ?>" placeholder="Seu novo login de acesso" /><br /> <label>Confirme sua senha atual:</label><br /> <input type="password" name="<PASSWORD>" placeholder="Sua senha atual" /> <label>Sua nova senha:</label><br /> <input type="<PASSWORD>" name="senha" placeholder="Sua nova senha de acesso" /> <label>Confirme sua nova senha:</label><br /> <input type="password" name="confsenha" placeholder="Sua nova senha de acesso" /> <input type="submit" value="Enviar"/> <p> Deseja deslogar? <a style="cursor: pointer;" href="logout.php">Clique aqui!</a> </p> </form> </body> </html><file_sep>/admin/criarUsuario.php <?php require('../autoloader.php'); $usuarios = new Usuarios(); $status = $usuarios->verificaStatus(); $db = new Database; if($status != 2) { die('Você não possui acesso a esta área'); } if($_POST) { $usuarios->criarUsuario($_POST['usuario'], $_POST['senha'], $_POST['admin']); die('<meta http-equiv="refresh" content="0;url=index.php">'); } ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/> <title><NAME> e do Jarbas | Criar usuário</title> <link rel="stylesheet" href="../style/style.css" /> <script src="https://kit.fontawesome.com/a076d05399.js"></script> </head> <body> <form method="POST" action="criarUsuario.php" class="form"> <div style="padding: 10px; text-align: center; font-size: 20pt;"> <a href="index.php"><i class='fas fa-times' style="float: right; cursor: pointer; font-size: 20pt;"></i></a> <label>Criar usuário</label> </div> <label>Usuário</label> <input type="text" name="usuario" /><br /><br /> <label>Senha</label> <input type="password" name="senha" /><br /><br /> <label>Administrador?</label> <select name="admin"> <option value="1">Sim</option> <option value="0">Não</option> </select><br /><br /> <input type="submit" value="Enviar" /> </form> </body> </html><file_sep>/admin/UploadImages.php <?php require('../autoloader.php'); $usuarios = new Usuarios(); $produtos = new Produtos(); $status = $usuarios->verificaStatus(); $db = new Database; if($status != 2) { die('Voce nao possui acesso a esta area'); } if(empty($_GET['id'])) { die('<meta http-equiv="refresh" content="0;url=index.php">'); } else { $id = $_GET['id']; } $produto = $db->pegarDado("produtos", "*", "id = $id"); ?> <html> <head> <title><NAME> | Upload de imagens</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet"> <link rel="stylesheet" href="../style/style.css" /> <script src="https://kit.fontawesome.com/a076d05399.js"></script> </head> <body> <div class="container form"> <form method="POST" enctype="multipart/form-data"> <div style="padding: 10px; text-align: center; font-size: 20pt;"> <a href="index.php"><i class='fas fa-times' style="float: right; cursor: pointer; font-size: 20pt;"></i></a> <h2><strong>Atualizar imagem</strong></h2><hr> </div> <label>Nome</label> <input type="text" disabled value="<?php echo $produto['titulo']; ?>"> <label>Imagem atual</label><br> <img src="../images/<?php echo $produto['caminho']; ?>" class="img img-responsive img-thumbnail" width="200"> <br> <label for="conteudo">Enviar imagem:</label> <input type="file" name="pic" accept="image/*" > <div align="center"> <button type="submit" class="btn btn-success">Enviar imagem</button> </div> </form> <hr> <?php if(isset($_FILES['pic'])) { $ext = pathinfo($_FILES['pic']['name'], PATHINFO_EXTENSION); //Pegando extensão do arquivo $new_name = date("Y.m.d-H.i.s") . '.'. $ext; //Definindo um novo nome para o arquivo $dir = '../images/'; //Diretório para uploads move_uploaded_file($_FILES['pic']['tmp_name'], $dir.$new_name); //Fazer upload do arquivo $dados = ['id' => $id, 'caminho' => $new_name]; $produtos->alterarProduto($id, $dados); echo '<div class="alert alert-success" role="alert" align="center"> <img src="../images/' . $new_name . '" class="img img-responsive img-thumbnail" width="200"> <br> Imagem enviada com sucesso! <br>'; } ?> </div> <body> </html><file_sep>/admin/alterarProduto.php <?php require('../autoloader.php'); $usuarios = new Usuarios(); $produtos = new Produtos(); $status = $usuarios->verificaStatus(); $db = new Database; if($status != 2) { die('Voce nao possui acesso a esta area'); } if(empty($_GET['id'])) { die('<meta http-equiv="refresh" content="0;url=index.php">'); } else { $id = $_GET['id']; } if($_POST) { $produtos->alterarProduto($id, $_POST); die('<meta http-equiv="refresh" content="0;url=index.php">'); } $produto = $db->pegarDado("produtos", "*", "id = $id"); ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/> <title>Loja do Marcão e do Jarbas | Alterar produto</title> <link rel="stylesheet" href="../style/style.css" /> <script src="https://kit.fontawesome.com/a076d05399.js"></script> </head> <body> <form method="POST" action="alterarProduto.php?id=<?php echo $id; ?>" class="form"> <div style="padding: 10px; text-align: center; font-size: 20pt;"> <a href="index.php"><i class='fas fa-times' style="float: right; cursor: pointer; font-size: 20pt;"></i></a> <label>Alterar produto</label> </div> <label>Titulo</label> <input type="text" name="titulo" value="<?php echo $produto['titulo']; ?>" /><br /><br /> <label>Preço</label> <input type="text" name="preco" value="<?php echo $produto['preco']; ?>" /><br /><br /> <label>Preço antigo</label> <input type="text" name="valorold" value="<?php echo $produto['valorold']; ?>" /><br /><br /> <a href="UploadImages.php?id=<?php echo $id; ?>">Alterar Imagem</a><br><br> <input type="submit" value="Enviar" /> </form> </body> </html><file_sep>/index.php <?php require('./autoloader.php'); $usuarios = new Usuarios(); $produtos = new Produtos(); $status = $usuarios->verificaStatus(); ?> <!DOCTYPE html> <html> <head> <title>Loja do Marcão e do Jarbas</title> <meta charset="UTF-8" /> <link rel="stylesheet" href="style/style.css" /> <script type="text/javascript" src="script/script.js"></script> <script src="https://kit.fontawesome.com/a076d05399.js"></script> </head> <div id="container"> <body> <div class="navbar"> <div class="logo"><label> LOJA DO MARCÃO E DO JARBAS </label><br /></div> <div class="slogan"> <label>Porque você merece o melhor, experimente!</label> </div> <ul> <li> <a href="~/../Index.php" ><i class="fas fa-home"></i> &nbsp;Inicio</a > </li> <li> <a href="#"><i class="fas fa-splotch"></i> &nbsp;Novidades</a> </li> <li> <a href="#"><i class="far fa-envelope"></i> &nbsp;Fale conosco</a> </li> <li style="float: right; margin-right: 30px; cursor: pointer;"> <?php if($status == 0) { echo '<a href="login.php"><i class="fas fa-user"></i> &nbsp;Login</a>'; } else { echo '<a href="conta.php"><i class="fas fa-user"></i> &nbsp;Minha conta</a>'; } ?> </li> <li style="float: right;"> <a href="carrinho.php" ><i class="fas fa-shopping-cart"></i> &nbsp;Meu carrinho</a > </li> <form class="nav-search" method="GET" action="buscaProduto.php"> <input type="text" name="busca" placeholder="&nbsp;O que você deseja?" /> <button> <i class="fas fa-search" style="color: white;"></i> &nbsp;Buscar </button> </form> </ul> </div> <div class="view-produtos"> <div class="view-produtos-tittle"> Confira essas ofertas que separamos para você </div> <div id="container"> <table> <?php foreach($produtos->listarProdutos('', '', '', '', '6',1) as $produto) { echo '<a href="carrinho.php?adiciona='. $produto['id']. '"<div class="view-produtos-tag box"> <div class="div-coracaozinho"> <i class="fas fa-heart" style="font-size: 30px; color: red;"></i> </div>'; echo '<img src="~/../images/'.$produto['caminho'] .'" />'; echo '<label>'. $produto['titulo'] . '</label><br />'; echo '<hr />'; echo '<strike>R$' . $produto['valorold'] . '</strike> <span>R$'.$produto['preco'].'</span> <br />'; echo '<strong>Até 10x SEM JUROS!</strong> </div></a>'; } ?> </table> </div> <div class="view-exibe-meio-produtos"> <div id="container"> <div class="box"> <i class="fas fa-shield-alt" style="font-size: 40px; margin: 10px;" ></i >Compre com segurança </div> <div class="box"> <i class="far fa-thumbs-up" style="font-size: 40px; margin: 10px;" ></i >Loja Super legal </div> <div class="box"> <i class="fas fa-truck" style="font-size: 40px; margin: 10px;"></i ><NAME> </div> </div> </div> <div class="view-produtos-tittle"> Nossos produtos mais comprados </div> <div id="container"> <table> <?php foreach($produtos->listarProdutos('', '', '', '', '6', 2) as $produto) { echo '<a href="carrinho.php?adiciona='. $produto['id']. '"<div class="view-produtos-tag box"> <div class="div-coracaozinho"> <i class="fas fa-heart" style="font-size: 30px; color: red;"></i> </div>'; echo '<img src="~/../images/'.$produto['caminho'] .'" />'; echo '<label>'. $produto['titulo'] . '</label><br />'; echo '<hr />'; echo '<strike>R$' . $produto['valorold'] . '</strike> <span>R$'.$produto['preco'].'</span> <br />'; echo '<strong>Até 10x SEM JUROS!</strong> </div></a>'; } ?> </table> </div> </div> </body> <footer> <div id="container"> <div class="box div-footer"> <label>Precida de ajuda?</label> <ul> <li><a href="#">Dúvidas frequentes</a></li> <li><a href="#">Tempo de entrega</a></li> <li><a href="#">Trocas e devoluções</a></li> <li><a href="#">Central de relacionamentos</a></li> <li><a href="#">Regras de voucher</a></li> <li><a href="#">Contrato de compra e venda</a></li> </ul> </div> <div class="box div-footer"> <label>SOBRE NÓS</label> <ul> <li><a href="#">Quem somos</a></li> <li><a href="#">Política de privacidade</a></li> <li><a href="#">Termos de uso</a></li> <li><a href="#">Seja um parceiro marketplace</a></li> <li><a href="#">Programa de afiliados</a></li> <li><a href="#">Anuncie conosco</a></li> </ul> </div> <div class="box div-footer"> <div class="div-footer-icons"> <label>FORMAS DE PAGAMENTO</label><br /><br /> <i class="fab fa-cc-paypal"></i> <i class="fab fa-cc-visa"></i> <i class="fab fa-cc-mastercard"></i> <i class="fab fa-cc-diners-club"></i> <i class="fab fa-cc-discover"></i> <i class="fab fa-cc-jcb"></i> </div> <div class="seguranca"> <i class="fas fa-user-shield"></i> <p>Seus dados seguros</p> </div> <div class="seguranca"> <i class="fas fa-shield-alt"></i> <p>Site com criptografia SSL</p> </div> </div> </div> <hr /> <div class="label-footer box"> <label> COPYRIGHT © 2020 TODOS OS DIREITOS RESERVADOS. - LOJA DO MARCÃO </label> </div> <div class="label-footer-icons box"> <a href="https://www.instagram.com/maajunioor/" target="_blank" ><i class="fab fa-instagram"></i ></a> <a href="https://github.com/Marcos2Junior" target="_blank" ><i class="fab fa-github"></i ></a> <a href="https://www.facebook.com/MarcosJuunior2/" target="_blank" ><i class="fab fa-facebook"></i ></a> <a href="https://open.spotify.com/user/gluguer" target="_blank" ><i class="fab fa-spotify"></i ></a> <a href="https://api.whatsapp.com/send?phone=5514981448487" target="_blank" ><i class="fab fa-whatsapp"></i ></a> </div> </footer> </div> </html> <file_sep>/admin/index.php <?php require('../autoloader.php'); $usuarios = new Usuarios(); $produtos = new Produtos(); $status = $usuarios->verificaStatus(); $db = new Database; if($status != 2) { die('Você não possui acesso a esta área'); } ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/> <title>Loja do Marcão e do Jarbas | Painel de Controle</title> <link rel="stylesheet" href="../style/style.css" /> <script src="https://kit.fontawesome.com/a076d05399.js"></script> </head> <body> <div class="viewindexadmin"> <h1>Usuários</h1> <a href='criarUsuario.php'>Criar usuário</a><br /><br /> <table cellspacing="2" cellpadding="5" border="1"> <tr> <th>ID</th> <th>Usuário</th> <th>Opções</th> </tr> <?php foreach($usuarios->listarUsuarios() as $usuario) { echo "<tr>"; echo "<td>" . $usuario['id'] . "</td>\n"; echo "<td>" . $usuario['usuario'] . "</td>\n"; echo "<td><a href='alterarUsuario.php?id=" . $usuario['id'] . "'>Alterar</a> - <a href='removerUsuario.php?id=" . $usuario['id'] . "'>Remover</a></td>\n"; echo "</tr>"; } ?> </table> </div> <div class="viewindexadmin"> <h1>Produtos</h1> <a href='criarProduto.php'>Criar produto</a><br /><br /> <table cellspacing="2" cellpadding="5" border="1"> <tr> <th>ID</th> <th>Produto</th> <th>Opções</th> </tr> <?php foreach($produtos->listarProdutos('', '', '', '', '') as $produto) { echo "<tr>"; echo "<td>" . $produto['id'] . "</td>\n"; echo "<td>" . $produto['titulo'] . "</td>\n"; echo "<td><a href='alterarProduto.php?id=" . $produto['id'] . "'>Alterar</a> - <a href='removerProduto.php?id=" . $produto['id'] . "'>Remover</a></td>\n"; echo "</tr>"; } ?> </table> </div> <div class="navAdmin"> <a href="../index.php">Voltar ao site</a> &nbsp;&nbsp; || &nbsp;&nbsp; <a href="../logout.php">Desconectar</a> </div> </body> </html><file_sep>/buscaProduto.php <?php require('./autoloader.php'); $usuarios = new Usuarios(); $produtos = new Produtos(); ?> <!DOCTYPE html> <html> <head> <title><NAME> e do Jarbas</title> <meta charset="UTF-8" /> <link rel="stylesheet" href="style/style.css" /> <script type="text/javascript" src="script/script.js"></script> <script src="https://kit.fontawesome.com/a076d05399.js"></script> </head> <div id="container"> <body> <div class="view-produtos"> <div style="padding: 10px; text-align: center; font-size: 20pt;"> <a href="index.php"><i class='fas fa-times' style="float: right; color: #cccccc; cursor: pointer; font-size: 30pt;"></i></a> </div> <div class="view-produtos-tittle"> Confira os produtos que encontramos para você </div> <div id="container"> <table> <?php $list = $produtos->listarProdutos('', '', '', $_GET['busca'], '6',''); foreach($list as $produto) { echo '<a href="carrinho.php?adiciona='. $produto['id']. '"<div class="view-produtos-tag box"> <div class="div-coracaozinho"> <i class="fas fa-heart" style="font-size: 30px; color: red;"></i> </div>'; echo '<img src="~/../images/'.$produto['caminho'] .'" />'; echo '<label>'. $produto['titulo'] . '</label><br />'; echo '<hr />'; echo '<strike>R$' . $produto['valorold'] . '</strike> <span>R$'.$produto['preco'].'</span> <br />'; echo '<strong>Até 10x SEM JUROS!</strong> </div></a>'; } if($list == null) { echo ' <div style="color: #cccccc; font-size: 20pt"> Poxa, sua busca não deu nenhum resultado :( </div>'; } ?> </table> </div> </div> </body> </div> </html><file_sep>/admin/criarProduto.php <?php require('../autoloader.php'); $usuarios = new Usuarios(); $produtos = new Produtos(); $status = $usuarios->verificaStatus(); $db = new Database; if($status != 2) { die('Você não possui acesso a esta área'); } if($_POST) { $uploaddir = '/images/'; $uploadfile = $uploaddir . basename($_FILES['caminho']['name']); move_uploaded_file($_FILES['caminho']['tmp_name'], $uploadfile); $produtos->criarProduto($_POST); die('<meta http-equiv="refresh" content="0;url=index.php">'); } ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/> <title>Loja do Marcão e do Jarbas | Criar produto</title> <link rel="stylesheet" href="../style/style.css" /> <script src="https://kit.fontawesome.com/a076d05399.js"></script> </head> <body> <form method="POST" action="criarProduto.php" class="form"> <div style="padding: 10px; text-align: center; font-size: 20pt;"> <a href="index.php"><i class='fas fa-times' style="float: right; cursor: pointer; font-size: 20pt;"></i></a> <label>Criar Produto</label> </div> <label>Nome</label> <input type="text" name="titulo" /><br /><br /> <label>Preço</label> <input type="text" name="preco" /><br /><br /> <label>Preço antigo</label> <input type="text" name="valorold" /><br /><br /> <label>Grupo</label> <input type="number" min="1" max="2" name="grupo" /><br /><br /> <input type="submit" value="Enviar" /> </form> </body> </html><file_sep>/registrar.php <?php require('./autoloader.php'); $usuarios = new Usuarios(); $status = $usuarios->verificaStatus(); if($status != 0) { die('Você já está registrado!'); } if($_POST) { $usuarios->criarUsuario($_POST['usuario'], $_POST['senha'], 0); die('<meta http-equiv="refresh" content="0;url=index.php">'); } ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/> <title><NAME> | Registro</title> <link rel="stylesheet" href="style/style.css" /> <script src="https://kit.fontawesome.com/a076d05399.js"></script> </head> <body> <form method="post" action="registrar.php" class="form"> <div style="padding: 10px; text-align: center; font-size: 20pt;"> <a href="index.php"> <i class='fas fa-times' style="float: right; cursor: pointer; font-size: 20pt;"></i></a> <label>Crie sua conta</label> </div> <label>Nome</label><br /> <input type="text" placeholder="Nome Completo" /><br /> <label>Login</label><br /> <input type="text" name="usuario" placeholder="Seu usuario" /><br /> <label>Telefone</label><br /> <input type="tel" placeholder="Telefone" /><br /> <label>CPF</label><br /> <input type="text" placeholder="CPF" /><br /> <label>Senha:</label><br /> <input type="<PASSWORD>" name="senha" placeholder="<PASSWORD>" /> <input type="submit" value="Registrar"/> <p> Realizando seu cadastro você concorda com todos os <a style="cursor: pointer;">termos e condições.</a> </p> </form> </body> </html><file_sep>/carrinho.php <?php require('./autoloader.php'); $usuarios = new Usuarios(); $produtos = new Produtos(); $carrinho = new Carrinho(); $status = $usuarios->verificaStatus(); $db = new Database; if($status == 0) { die('Você precisa estar logado para comprar algum produto. Portanto, <a href="login.php">Faça login</a>'); } if(isset($_GET['adiciona'])) { $carrinho->adicionarProduto($_GET['adiciona']); } if(isset($_POST['esvaziar'])) { $carrinho->esvaziarCarrinho(); } if(isset($_POST['atualizar'])) { // Para cada produto em nosso carrinho, chamaremos o método de alteração de quantidade foreach($_POST['produto'] as $chave => $produto) { $carrinho->alterarQuantidade($produto, $_POST['quantidade'][$chave]); } // Caso o checkbox de remoção tenha sido marcado if(isset($_POST['remover'])) { // Itere entre os valores marcados e chame o método de remoção com o value do checkbox foreach($_POST['remover'] as $produto) { $carrinho->removerProduto($produto); } } } if(isset($_POST['compra'])) { foreach($_POST['produto'] as $key => $value) { $quantidade = $_POST['quantidade'][$key]; $produto = $db->pegarDado("produtos", "*", "id = $value"); // Criamos um dado pré-formatado com informações da compra. A partir daqui, podemos chamar um método de uma classe de boleto, cartão ou PagSeguro $compras[] = "[". $_SESSION['user'] ."-". $quantidade ."-". $produto['id'] ."-". $produto['titulo'] ."-". $produto['preco'] ."]"; } $compras = implode(', ', $compras); // Unimos nossos dados pré-formatados, separados por vírgulas, para cada produto comprado $carrinho->esvaziarCarrinho(); die("Compramos os itens: $compras"); // Mostramos na tela os itens comprados } ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/> <title>Loja do Marcão e do Jarbas | Carrinho de compras</title> <link rel="stylesheet" href="style/style.css" /> <script src="https://kit.fontawesome.com/a076d05399.js"></script> </head> <body> <?php echo '<form method="POST" action="carrinho.php" class="form"> <div style="padding: 10px; text-align: center; font-size: 20pt;"> <a href="index.php"><i class=\'fas fa-times\' style="float: right; cursor: pointer; font-size: 20pt;"></i></a> <label>Olá '. $_SESSION['user'] .'!<br> Esse é o seu Carrinho de compras</label> </div>'; if(isset($_SESSION['compras'])) { $total = 0; echo ' <table cellspacing="2" cellpadding="4"> <tr> <th>Nome</th> <th>Quantidade</th> </tr>'; foreach($carrinho->listarProdutos() as $produto) { $total += $produto['preco'] * $produto['quantidade']; echo "<tr>"; echo "<td><strong>" . $produto['titulo'] . "</strong><input type='hidden' name='produto[]' value='" . $produto['id'] . "' /></td>\n"; echo "<td><input type='number' max='10' min='1' name='quantidade[]' value='" . $produto['quantidade'] . "' /></td>\n"; echo "<td><input type='checkbox' name='remover[]' value='" . $produto['id'] . "' /></td>\n"; echo "</tr>"; } echo "<tr><td colspan='2' align='right'><strong>Total:</strong> R$ $total</td></tr>"; echo '<tr><td colspan="2" align="right"><input type="submit" name="compra" value="Finalizar compra" /> <input type="submit" name="esvaziar" value="Esvaziar carrinho" /> <input type="submit" name="atualizar" value="Atualizar carrinho" /></td></tr></table>'; } else { echo "<p>Não há nada no carrinho.</p>"; } ?> </form> </body> </html><file_sep>/admin/alterarUsuario.php <?php require('../autoloader.php'); $usuarios = new Usuarios(); $status = $usuarios->verificaStatus(); $db = new Database; if($status != 2) { die('Você não possui acesso a esta área'); } if(empty($_GET['id'])) { die('<meta http-equiv="refresh" content="0;url=index.php">'); } else { $id = $_GET['id']; } if($_POST) { $usuarios->alterarUsuarioAdmin($id, $_POST['usuario'], $_POST['senha'], $_POST['admin']); die('<meta http-equiv="refresh" content="0;url=index.php">'); } $usuario = $db->pegarDado("usuarios", "*", "id = $id"); ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/> <title>Loja do Marcão e do Jarbas | Alterar usuário</title> <link rel="stylesheet" href="../style/style.css" /> <script src="https://kit.fontawesome.com/a076d05399.js"></script> </head> <body> <form method="POST" action="alterarUsuario.php?id=<?php echo $id; ?>" class="form"> <div style="padding: 10px; text-align: center; font-size: 20pt;"> <a href="index.php"><i class='fas fa-times' style="float: right; cursor: pointer; font-size: 20pt;"></i></a> <label>Editar usuário</label> </div> <label>Usuário</label> <input type="text" name="usuario" value="<?php echo $usuario['usuario']; ?>" /><br /><br /> <label>Senha</label> <input type="password" name="senha" value="" /><br /><br /> <label>Administrador?</label> <select name="admin"> <option value="1" <?php if($usuario['admin'] == 1) { echo 'selected="selected"'; } ?>>Sim</option> <option value="0" <?php if($usuario['admin'] == 0) { echo 'selected="selected"'; } ?>>Não</option> </select><br /><br /> <input type="submit" value="Enviar" /> </form> </body> </html><file_sep>/classes/Produtos.class.php <?php /** * Classe de controle de produtos * * Esta classe permite que sejam gerenciados os produtos da loja * * @package Livraria412 */ class Produtos { /** * propriedades da classe */ private $db; /** * A função __construct é um método mágico. Este método será executado toda vez que o objeto for instanciado. */ public function __construct() { $this->db = new Database; } /** * Neste método, simplificamos a maneira de criar novos produtos * * @param array $dados Dados a serem inseridos no banco, vindos de um POST */ public function criarProduto($dados) { $this->db->inserirDados("produtos", $dados); } /** * Neste método, simplificamos a maneira de alterar dados de produtos * * @param string $id ID do produto a ser alterado * @param array $dados Dados a serem alterados no banco, vindos de um POST */ public function alterarProduto($id, $dados) { $this->db->alterarDados("produtos", "id = $id", $dados); } /** * Neste método, simplificamos a maneira de remover produtos * * @param string $id ID do produto a ser removido */ public function removerProduto($id) { $this->db->removerDados("produtos", "id = $id"); } /** * Neste método, listamos todos os produtos em nosso banco, com algumas regras * * @param string $id Filtrar produtos por id * @param string $titulo Filtrar produtos por titulo * @param string $busca Buscar algo nos produtos * @param string $ordem Ordem de exibição dos produtos * @param string $limite Limitar a exibição de produtos * * @param string $grupo exibir por grupos * @return array Resultados da consulta ao banco de dados por produtos */ public function listarProdutos($id = null, $titulo = null, $ordem = null, $busca = null, $limite = null, $grupo = null) { if(!empty($id)) { $onde = "id = '$id'"; } else if(!empty($grupo)) { $onde = "grupo = '$grupo'"; } else { $onde = null; } if(!empty($busca)) { if(!empty($onde)) { $onde .= " AND titulo"; } else { $onde = 'titulo'; } $like = "'%". $busca ."%'"; } else { $like = null; } $resultados = $this->db->pegarDados('produtos', '*', $onde, $like, $ordem, $limite); return $resultados; } /** * Neste método, mostraremos apenas um produto * * @param string $id Produto a ser exibido * @return array Resultados da consulta ao banco de dados por um produto */ public function verProduto($id) { $resultado = $this->db->pegarDado('produtos', '*', 'id = $id'); return $resultado; } public function AlterarImagem($id, $caminho) { } }
1630790e47def9d3c99f59ebcf0719c6074ab5ce
[ "SQL", "PHP" ]
14
PHP
Marcos2Junior/Trabalho1Cacao4Semestre
b816ef4168cd7dc61bacdead9a8642a1f36d8f88
7f2ef13b06672fc191b45be6ea1094973d7c4b93
refs/heads/master
<repo_name>gissilali/java-mortgage-calculator<file_sep>/src/main/java/com/company/Main.java package com.company; import java.util.Scanner; import java.util.concurrent.TimeUnit; public class Main { public static void main(String[] args) throws InterruptedException { MortgageController mortgage = new MortgageController(); mortgage.runQuestionnaire(); } }
9f04ca4adcf89522f86ea98a04f4cf4968404f1c
[ "Java" ]
1
Java
gissilali/java-mortgage-calculator
bfd65b4630c2bb0b082ae280e72f9ede2a32f875
0db4f36610f859dfd87a2579dbf1ba33e016202e
refs/heads/master
<file_sep>// // AlarmListViewController.swift // SampleClock // // Created by 濱田一輝 on 2019/12/15. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit import UserNotifications class AlarmListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var alarmTableView: UITableView! let formatter = DateFormatter() var alarmManager = AlarmManager() override func viewDidLoad() { super.viewDidLoad() alarmTableView.delegate = self alarmTableView.dataSource = self formatter.dateFormat = "HH:mm" } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.alarmTableView.reloadData() } // MARK: - Table view data source // セクション数を返す func numberOfSections(in tableView: UITableView) -> Int { return 1 } // セクションごとの行数を返す func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return alarmManager.alarmList.count } // 各行に表示するセルを返す func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let alarmCell = tableView.dequeueReusableCell(withIdentifier: "AlarmCell", for: indexPath) let alarmData = alarmManager.alarmList[(indexPath as NSIndexPath).row] alarmCell.textLabel?.text = formatter.string(from: alarmData.date) if alarmCell.accessoryView == nil { let switchView = UISwitch() switchView.isOn = alarmData.isActive switchView.tag = indexPath.row switchView.addTarget(self, action: #selector(handleSwitch(_:)), for: UIControl.Event.valueChanged) alarmCell.accessoryView = switchView } return alarmCell } // セルをスワイプしたときの処理 func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { alarmManager.removeAlarm(at: indexPath.row) alarmTableView.deleteRows(at: [indexPath], with: .fade) } } @objc func handleSwitch(_ sender: UISwitch) { print(sender.isOn) alarmManager.alarmList[sender.tag].isActive = sender.isOn if( sender.isOn ) { alarmManager.setNotification(sender.tag) } else { alarmManager.removeNotification(sender.tag) } } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "AlarmSettingSegue" { let alarmSettingViewController = segue.destination as! AlarmSettingViewController if let indexPath = self.alarmTableView.indexPathForSelectedRow { alarmSettingViewController.alarmManager = alarmManager alarmSettingViewController.alarm = alarmManager.alarmList[(indexPath as NSIndexPath).row] } else { alarmSettingViewController.alarmManager = alarmManager alarmSettingViewController.alarm = alarmManager.getNewAlarm() } } } } <file_sep>// // AlarmManager.swift // SampleClock // // Created by 濱田一輝 on 2019/12/30. // Copyright © 2019 <NAME>. All rights reserved. // import Foundation import UserNotifications class AlarmManager { let center = UNUserNotificationCenter.current() let content = UNMutableNotificationContent() let calendar = Calendar.current let userdefault = UserDefaults.standard var alarmList: [Alarm] = [] init() { if let list = loadData() { alarmList = list } else { alarmList = [] } print(alarmList) } func loadData() -> [Alarm]? { if let loadedData = userdefault.data(forKey: "alarmList") { return try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(loadedData) as! [Alarm]? } else { return nil } } func setArchivedData() { guard let archivedData = try? NSKeyedArchiver.archivedData(withRootObject: alarmList, requiringSecureCoding: true) else { fatalError("Archive Faild") } userdefault.set(archivedData, forKey: "alarmList") } func setNewAlarm(alarm: Alarm) { alarmList.append(alarm) setArchivedData() } func getNewAlarm() -> Alarm { return Alarm() } func removeAlarm(at index: Int) { removeNotification(index) alarmList.remove(at: index) setArchivedData() } func removeNotification(_ index: Int) { center.removePendingNotificationRequests(withIdentifiers: [alarmList[index].identifier]) center.removeDeliveredNotifications(withIdentifiers: [alarmList[index].identifier]) printNotifications() } func setNotification(_ index: Int) { let alarm = alarmList[index] content.title = "アラーム" content.sound = UNNotificationSound.default let dateComponent = calendar.dateComponents([.hour, .minute], from: alarm.date) let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponent, repeats: alarm.repeats) let request = UNNotificationRequest(identifier: alarm.identifier, content: content, trigger: trigger) center.add(request, withCompletionHandler: nil) printNotifications() } func printNotifications() { center.getPendingNotificationRequests(completionHandler: {(requests) in print("==========Pending Notification============") print(requests) }) center.getDeliveredNotifications(completionHandler: {(notifications) in print("==========Delivered Notification============") print(notifications) }) } } <file_sep>// // Alarm.swift // SampleClock // // Created by 濱田一輝 on 2019/12/30. // Copyright © 2019 <NAME>. All rights reserved. // import Foundation class Alarm: NSObject, NSSecureCoding { static var supportsSecureCoding: Bool = true var identifier: String var date: Date = Date() var repeats: Bool = true var isActive: Bool = false override init() { let formatter = DateFormatter() formatter.dateStyle = .medium formatter.timeStyle = .medium self.identifier = formatter.string(from: Date()) } required init?(coder: NSCoder) { self.identifier = coder.decodeObject(forKey: "identifier") as! String self.date = coder.decodeObject(forKey: "date") as! Date self.repeats = coder.decodeObject(forKey: "repeats") as! Bool self.isActive = coder.decodeObject(forKey: "isActive") as! Bool } func encode(with coder: NSCoder) { coder.encode(identifier, forKey: "identifier") coder.encode(date, forKey: "date") coder.encode(repeats, forKey: "repeats") coder.encode(isActive, forKey: "isActive") } } <file_sep># SampleClock サンプル時計アプリ <file_sep>// // AlarmSettingViewController.swift // SampleClock // // Created by 濱田一輝 on 2019/12/29. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit class AlarmSettingViewController: UIViewController { @IBOutlet weak var alarmTimePicker: UIDatePicker! var alarmManager: AlarmManager? var alarm: Alarm? override func viewDidLoad() { super.viewDidLoad() } override func viewDidAppear(_ animated: Bool) { if let alarm = alarm { alarmTimePicker.date = alarm.date } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.presentingViewController?.beginAppearanceTransition(true, animated: animated) self.presentingViewController?.endAppearanceTransition() } // キャンセルボタン押下時の処理 @IBAction func onTapCancelButton(_ sender: Any) { self.dismiss(animated: true, completion: nil) } // 保存ボタン押下時の処理 @IBAction func onTapSaveButton(_ sender: Any) { alarm?.date = alarmTimePicker.date alarmManager?.setNewAlarm(alarm: alarm!) self.dismiss(animated: true, completion: nil) } }
bd89b215a44d2f1817548c7278057a1548d31dce
[ "Swift", "Markdown" ]
5
Swift
kzkhmd/SampleClock
1ff947a241d93b8f0c243ebe25cc035629474019
8d000e015d25ced094294a2b2a3d760f79487607
refs/heads/master
<file_sep>var scorm = pipwerks.SCORM; $( document ).ready( init ); function init() { scorm.version = "2004"; connect(); var learnerName = getValue( "cmi.learner_name" ); $( "#Name" ).html( "Bonjour " + learnerName + " !!!" ); $( "#goto1" ).click( goto1 ); $( "#goto2" ).click( goto2 ); $( "#goto3" ).click( goto3 ); $( window ).unload( disconnect ); } function goto1() { if( getValue( "adl.nav.request_valid.choice.{target=page1}" ) == "true" ) { setValue( 'adl.nav.request', '{target=page1}choice' ); disconnect(); } /* if( getValue( "adl.nav.request_valid.previous" ) == "true" ) { setValue( 'adl.nav.request', 'previous' ); disconnect(); } */ } function goto2() { if( getValue( "adl.nav.request_valid.choice.{target=page2}" ) == "true" ) { setValue( 'adl.nav.request', '{target=page2}choice' ); disconnect(); } /* if( getValue( "adl.nav.request_valid.continue" ) == "true" ) { setValue( 'adl.nav.request', 'continue' ); disconnect(); } */ } function goto3() { /* if( getValue( "adl.nav.request_valid.choice.{target=page3}" ) == "true" ) { setValue( 'adl.nav.request', '{target=page3}choice' ); disconnect(); } */ if( getValue( "adl.nav.request_valid.continue" ) == "true" ) { setValue( 'adl.nav.request', 'continue' ); setValue( 'adl.nav.request', 'continue' ); disconnect(); } } function connect() { if( !scorm.connection.isActive ) { var isSuccess = scorm.init(); var msg = "Connexion : " + ( ( isSuccess )? "succès" : "échec" ); log( msg, isSuccess ); } } function disconnect() { if( scorm.connection.isActive ) { var isSuccess = scorm.quit(); var msg = "Déconnexion : " + ( ( isSuccess )? "succès" : "échec" ); log( msg, isSuccess ); } } function save() { if( scorm.connection.isActive ) { var isSuccess = scorm.save(); var msg = "Sauvegarde : " + ( ( isSuccess )? "succès" : "échec" ); log( msg, isSuccess ); } } function getValue( parameter ) { var value = null; if( scorm.connection.isActive ) { value = scorm.get( parameter ); var msg = "Get " + parameter + " : " + ( ( value )? value : "échec" ); var isSuccess = ( value )? true : false; log( msg, isSuccess ); } return value; } function setValue( parameter, value ) { if( scorm.connection.isActive ) { var isSuccess = scorm.set( parameter, value ); var msg = "Set " + parameter + " = " + value + " : " + ( ( isSuccess )? "succès" : "échec" ); log( msg, isSuccess ); } } function log( msg, isSuccess ) { $( "#console" ).append( "<div style=\"color:" + ( ( isSuccess )? "blue" : "orangered" ) + ";\">" + msg + "</div>" ); }
f997b64333eea14763d5b8d4bef4d1f26ddcb122
[ "JavaScript" ]
1
JavaScript
tyd01/sco_navigation_test
9acdc3d2101b7fb4d73fda0e88865e3b85cf7a22
88f43b2bc5bce2cd2013208b8ed6f33704a7a24d
refs/heads/master
<repo_name>Blesfia/protractor-workshop-2017<file_sep>/src/page/ProductList.page.ts import { $, ElementFinder, promise } from 'protractor'; export class ProductListPage { private get tShirtProduct(): ElementFinder { return $('#center_column > .product_list > li .product_img_link'); } public goToTShirtProductDetail(): promise.Promise<void> { return this.tShirtProduct.click(); } } <file_sep>/src/page/PaymentStep.page.ts import { $, ElementFinder, promise } from 'protractor'; export class PaymentStepPage { private get payByBankWireButton(): ElementFinder { return $('#HOOK_PAYMENT .bankwire'); } public goToCheckPaymentStepPage(): promise.Promise<void> { return this.payByBankWireButton.click(); } } <file_sep>/src/page/ProductAddedModal.page.ts import { $, ElementFinder, ExpectedConditions, browser } from 'protractor'; export class ProductAddedModalPage { private get proceedToCheckoutButton(): ElementFinder { return $('[style*="display: block;"] .button-container > a'); } public async goToCheckoutPage(): Promise<void> { await browser.wait(ExpectedConditions.presenceOf(this.proceedToCheckoutButton), 3000); return this.proceedToCheckoutButton.click(); } } <file_sep>/test/BuyTshirt.spec.ts import { browser } from 'protractor'; import { MenuContentPage, ProductListPage, ProductDetailPage, ProductAddedModalPage, SummaryStepPage, SignInStepPage, AddressStepPage, ShippingStepPage, PaymentStepPage, BankPaymentPage, OrderResumePage } from '../src/page'; describe('Buy a t-shirt', () => { const menuContentPage: MenuContentPage = new MenuContentPage(); const productListPage: ProductListPage = new ProductListPage(); const productDetailPage: ProductDetailPage = new ProductDetailPage(); const productAddedModalPage: ProductAddedModalPage = new ProductAddedModalPage(); const summaryStepPage: SummaryStepPage = new SummaryStepPage(); const signInStepPage: SignInStepPage = new SignInStepPage(); const addressStepPage: AddressStepPage = new AddressStepPage(); const shippingStepPage: ShippingStepPage = new ShippingStepPage(); const paymentStepPage: PaymentStepPage = new PaymentStepPage(); const bankPaymentPage: BankPaymentPage = new BankPaymentPage(); const orderResumePage: OrderResumePage = new OrderResumePage(); describe('Abrir la página en el navegador', () => { it('', async () => { await browser.get('http://automationpractice.com/'); }); }); describe('Proceso de compra de la Camiseta', () => { it('', async () => { await menuContentPage.goToTShirtMenu(); await productListPage.goToTShirtProductDetail(); await productDetailPage.addToCart(); await productAddedModalPage.goToCheckoutPage(); await summaryStepPage.goToSignInPage(); }); }); describe('Logeo en la aplicación', () => { it('', async () => { await signInStepPage.goToAddressStep(); }); }); describe('Seleccionar la dirección por defecto', () => { it('', async () => { await addressStepPage.goToShippingStepPage(); }); }); describe('Pago en el banco', () => { it('', async () => { await shippingStepPage.goToPaymentStepPage(); await paymentStepPage.goToCheckPaymentStepPage(); await bankPaymentPage.goToOrderResumePage(); await expect(orderResumePage.getMessageOfAccomplish()) .toBe('Your order on My Store is complete.'); }); }); }); <file_sep>/src/page/OrderResume.page.ts import { $, ElementFinder } from 'protractor'; export class OrderResumePage { private get accomplishLabel(): ElementFinder { return $('#center_column > div > p > strong'); } public getMessageOfAccomplish() { return this.accomplishLabel.getText(); } } <file_sep>/src/page/SignInStep.page.ts import { $, ElementFinder } from 'protractor'; export class SignInStepPage { private get emailTextBox(): ElementFinder { return $('#email'); } private get passwordTextBox(): ElementFinder { return $('#passwd'); } private get signInButton(): ElementFinder { return $('#SubmitLogin'); } public async goToAddressStep(): Promise<void> { await this.emailTextBox.sendKeys('<EMAIL>'); await this.passwordTextBox.sendKeys('<PASSWORD>'); await this.signInButton.click(); } } <file_sep>/src/page/BankPayment.page.ts import { $, ElementFinder, promise } from 'protractor'; export class BankPaymentPage { private get confirmMyOrderButton(): ElementFinder { return $('#cart_navigation button'); } public goToOrderResumePage(): promise.Promise<void> { return this.confirmMyOrderButton.click(); } }
6c512f50bedf41cd29bdbe1cd1b88acc1595eb2f
[ "TypeScript" ]
7
TypeScript
Blesfia/protractor-workshop-2017
d295553ea44d1b61ef5a83d55b7b554f180ff15e
31b4ef2e6dfe3a5efe0df22859284e90e663d65a
refs/heads/master
<repo_name>roxanemomeni/mlproject<file_sep>/tests/ tool_test.py import mlproject # Import from our lib from mlproject.tools import haversine import pytest def test_haversine(): lon1, lat1, lon2, lat2 = (48.865070, 2.380009, 48.235070, 2.393409) out = haversine(lon1, lat1, lon2, lat2) assert(out) == 70.00789153218594
7f8f4d50b5c66666efc9a8ad45864ab8f3d5878a
[ "Python" ]
1
Python
roxanemomeni/mlproject
1eac8d90371052d0a46a3f64f18e4c2b613312f2
3fded64385db870d7dd4fa18a309a898f84c74de
refs/heads/master
<repo_name>Estein21/instagram-puller<file_sep>/emails.py import urllib2, ssl, json, re, sys context = ssl._create_unverified_context() response = urllib2.urlopen(url, context=context) query = 'beauty' url = 'https://www.instagram.com/web/search/topsearch/?query=' + str(query) dictUsers = [] def getEmail(account): url = 'https://www.instagram.com/' + account + '/?__a=1' for line in response: jsonContent = json.loads(line) bio = jsonContent['user']['biography'] email = re.search(r'[\w\.-]+@[\w\.-]+', bio) try: return email.group(0) except: return False for line in response: jsonContent = json.loads(line)['users'] for u in jsonContent: username = u['user']['username'] if getEmail(username): u = {} u['user'] = username u['email'] = getEmail(username) u['lead'] = False u['day'] = 0 print u dictUsers.append(u) print dictUsers <file_sep>/README.md # instagram-puller
71059e69eaba64b66edd5b6434bda344b69f4416
[ "Markdown", "Python" ]
2
Python
Estein21/instagram-puller
0ffd12337db4fafe3970bf0902009f146e306152
c9f7f18f11a0167cd3260dc1d535d85bde366cf9
refs/heads/master
<repo_name>wish899/pinpongrobots<file_sep>/bouncing_ball.py import numpy as np #Sources used to make this: #https://yyknosekai.wordpress.com/2015/10/21/losing-height-a-bouncing-ball/ #https://www.youtube.com/watch?v=Mp8bz5P1m4I class BouncingBall(): def __init__(self, mass=0, y_threshold=2.65): self.mass = mass self.y_threshold = y_threshold self.rest = .82 pass def trajectory(self, x_wall, y_wall, z_wall, v_init): """ @param x_wall (number): last recorded coordinates of the ball as it leaves the proximity sensor's vicinity @param y_wall (number): last recorded y-coordinate of the ball as it leaves the proximity sensor's vicinity @param z_wall (number): last recorded z-coordinate of the ball as it leaves the proximity sensor's vicinity @param v_init [(3,) number]: the velocity of the ball as it bounces off the wall and leaves the sensor's range @return [x_end, y_end, z_end]: predicted end position at which the robot will hit """ #Perform trajectory calculation until we reach x_rob and z_rob #Perform trajectory calculation until #So, trajectory generation takes literally forever: #How can we come up with a faster way to predict trajectory? #Also, how do we figure out the motions? y_end = y_wall x_end = x_wall z_end = z_wall y_prev = 0 x_prev = 0 v_x_init = 0 v_y_init = 0 v_z_init = 0 cnt = 0 #if(np.round(v_init[2], 2) == 0): time_bounce = (2.65-y_wall)/v_init[1] time_bounce_near = (2.85-y_wall)/v_init[1] time_bounce_far = (2.45-y_wall)/v_init[1] x_end += v_init[0] * time_bounce x_world = -1 * x_end + 0.025 if (np.abs(x_world) < 0.20): x_end += v_init[0] * (time_bounce_near - time_bounce) return [x_end, 2.85, z_wall] elif (np.abs(x_world) > 0.75): x_end += v_init[0] * (time_bounce_far - time_bounce) return [x_end, 2.45, z_wall-0.1] return [x_end, 2.65, z_wall] # while(y_end < self.y_threshold): # if cnt==0: # v_y_init = v_init[1] # v_x_init = v_init[0] # v_z_init = v_init[2] # p_init = z_wall # y_end += v_y_init * ((v_z_init + np.sqrt(v_z_init**2 + 2 * p_init * (9.81))))/(9.81) # x_end += v_x_init * ((v_z_init + np.sqrt(v_z_init**2 + 2 * p_init * (9.81))))/(9.81) # # print(y_end) # # print(x_end) # cnt += 1 # else: # v_y_init = v_init[1] * (self.rest)**cnt # v_x_init = v_init[0] * (self.rest)**cnt # v_z_init = v_init[2] * (self.rest)**cnt # y_end += v_y_init * (2 * v_z_init/(9.81)) # x_end += v_x_init * (2 * v_z_init/(9.81)) # # print(y_end) # # print(x_end) # cnt += 1 # if cnt == 1: # y_prev = y_wall # x_prev = x_wall # else: # y_prev = y_end - v_y_init * ((2 * v_z_init)/(9.81)) # x_prev = y_end - v_x_init * ((2 * v_z_init)/(9.81)) # cnt -= 1 # delta_y = self.y_threshold - y_end # target_time = 0 # if v_y_init == 0: # target_time = delta_y # else: # target_time = delta_y/v_y_init # delta_z = (v_z_init * target_time) - (1/2) * (9.81) * (target_time**2) # z_end = delta_z # y_pos = y_prev + v_y_init * (target_time) # x_pos = x_prev + v_x_init * (target_time) # return [x_pos, y_pos, delta_z] def one_bounce(self, pos_init, v_init): pass #we look at the amount traveled after one bounce. if x y velocity almost zero, we just do linear from that #so we have crossed the threshold: Now we need to see what the height is at that moment <file_sep>/stest.py # Make sure to have the server side running in CoppeliaSim: # in a child script of a CoppeliaSim scene, add following command # to be executed just once, at simulation start: # # simRemoteApi.start(19999) # # then start simulation, and run this program. # # IMPORTANT: for each successful call to simxStart, there # should be a corresponding call to simxFinish at the end! from scipy.spatial.transform import Rotation as R from scipy.linalg import expm import sys sys.path.append('./') import inverse_kinematics as ik import bouncing_ball import threading import time import math import numpy as np try: import sim except: print ('--------------------------------------------------------------') print ('"sim.py" could not be imported. This means very probably that') print ('either "sim.py" or the remoteApi library could not be found.') print ('Make sure both are in the same folder as this file,') print ('or appropriately adjust the file "sim.py"') print ('--------------------------------------------------------------') print ('') sys.exit() ball_coord = [] ball_linear = [] ball_angular = [] hit_wall = False ball_hit = True detect_handle = (0, 2) prox_handle = (0, 5) stop_prog = False #ball_hit_lock = threading.Lock() #import modern_robotics as mr def get_ball_info(clientID): """ stores the linear velocity and the position variable of the last time that the ball hit the wall stores it in the global coordinates ball_coord and ball_linear @param clientID: ID used to connect to CoppeliaSim's environment @return None """ global ball_coord global ball_linear global hit_wall global ball_hit global detect_handle global prox_handle global stop_prog print("Getting ball info: ") # while 1: # if cnt == 0: # ret, ball_handle = sim.simxGetObjectHandle(clientID, 'Sphere', sim.simx_opmode_blocking) # ret, ball_coord = sim.simxGetObjectPosition(clientID, ball_handle, -1, sim.simx_opmode_streaming) # ret, ball_linear, ball_angular = sim.simxGetObjectVelocity(clientID, ball_handle, sim.simx_opmode_streaming) # cnt += 1 # else: # ret, ball_coord = sim.simxGetObjectPosition(clientID, ball_handle, -1, sim.simx_opmode_buffer) # ret, ball_linear_new, ball_angular = sim.simxGetObjectVelocity(clientID, ball_handle, sim.simx_opmode_buffer) # if(ball_linear_new[1] < 0 and ball_linear[1] > 0): # #if we come here, then the velocity direction has changed, meaning we hit the wall # hit_wall = True # detect_handle = sim.simxGetObjectHandle(clientID, 'Sphere', sim.simx_opmode_blocking) # print("Sphere Handle: ", detect_handle[1]) # prox_handle = sim.simxGetObjectHandle(clientID, 'Proximity_sensor', sim.simx_opmode_blocking) # print("Proximity Sensor Handle: ", prox_handle[1]) y = 0 points = [] velocities = [] leave = 0 while True: if stop_prog: break if ball_hit: #print("We hit the ball, we are now processing") y = 0 #Represents if the ball is moving away from the wall or not else: #print("waiting for ball to be hit") continue while (y == 0): #While ball still coming towards wall # read prox sensor and get detected points ret, dS, dP, dOH, dSNV = sim.simxReadProximitySensor(clientID, prox_handle[1], sim.simx_opmode_buffer) ret, linear, angular = sim.simxGetObjectVelocity(clientID, detect_handle[1], sim.simx_opmode_buffer) # detecting if(dS == 1): # store all the detected points points.append(dP) velocities.append(linear) leave = 1 # not detecting and is heading away from wall elif(dS == 0 and leave == 1): y = 1 hit_wall = True #To show we have just hit the wall ball_hit = False #To show that the ball has not been hit yet. Ideally, we don't start this loop #until the ball has been hit leave = 0 print("Storing left velocity and position") if len(velocities) > 0 : ball_linear = velocities[-1] if len(points) > 0: ball_coord = points[-1] velocities = [] points = [] def hit_ball(clientID): """ Method to actually hit the ball with the robot """ global hit_wall global ball_coord global ball_linear global ball_hit print("Hitting Ball: ") # #Get handles for detecting object # detect_handle = sim.simxGetObjectHandle(clientID, 'Sphere', sim.simx_opmode_blocking) # #Get handles for detecting the proximity sensor # prox_handle = sim.simxGetObjectHandle(clientID, 'Proximity_sensor', sim.simx_opmode_blocking) #Create an instance to compute the ball trajectory b_ball = bouncing_ball.BouncingBall() #getting joint handles and initializing the joints in the simulation jointHandles=[-1,-1,-1,-1,-1,-1] for i in range(6): jointHandles[i]=sim.simxGetObjectHandle(clientID, 'UR3_joint' + str(i+1)+'#0', sim.simx_opmode_blocking) for i in range(6): print (jointHandles[i]) #Set-up some of the RML vectors: vel=90 accel=20 jerk=40 currentVel=[0,0,0,0,0,0,0] currentAccel=[0,0,0,0,0,0,0] maxVel=[vel*math.pi/180,vel*math.pi/180,vel*math.pi/180,vel*math.pi/180,vel*math.pi/180,vel*math.pi/180] maxAccel=[accel*math.pi/180,accel*math.pi/180,accel*math.pi/180,accel*math.pi/180,accel*math.pi/180,accel*math.pi/180] maxJerk=[jerk*math.pi/180,jerk*math.pi/180,jerk*math.pi/180,jerk*math.pi/180,jerk*math.pi/180,jerk*math.pi/180] targetVel=[0,0,0,0,0,0] sim.simxPauseCommunication(clientID, True) for i in range(6): sim.simxSetJointTargetPosition(clientID, jointHandles[i][1], 0, sim.simx_opmode_streaming) sim.simxSetJointTargetVelocity(clientID, jointHandles[i][1], targetVel[i], sim.simx_opmode_streaming) sim.simxPauseCommunication(clientID, False) time.sleep(2) #start the feedback loop while True: if not hit_wall: print("Ball hasn't hit wall yet") continue if hit_wall: print("Ball has hit the wall") #Predict the position of the ball from the wall and transform it to world coordinates print("Predicting Trajectory ...") pred_pos = b_ball.trajectory(ball_coord[0], ball_coord[1], ball_coord[2], ball_linear) T_prox = np.array([[-1, 0, 0, 0.025], [0, -1, 0, 2.85], [0, 0, 1, .043], [0, 0, 0, 1]]) prox_pos = np.array([[pred_pos[0]], [pred_pos[1]], [pred_pos[2]],[1]]) ball_pos = np.linalg.inv(T_prox) @ prox_pos print(ball_pos) targetPos0_ik = ik.findJointAngles(ball_pos[0, :], ball_pos[1,:]+0.1, ball_pos[2,:]+0.1) print(targetPos0_ik) #Invert joint angles if on left side of robot if ball_pos[0] < 0: for i in range(len(targetPos0_ik)): targetPos0_ik[i] = -targetPos0_ik[i] print("Applying the hitting motion") print(ball_pos) #Apply the hitting motion using the new joint angles sim.simxPauseCommunication(clientID, True) for i in range(6): #print(jointHandles[i]) #print(targetPos0[i]) sim.simxSetJointTargetPosition(clientID, jointHandles[i][1], targetPos0_ik[i], sim.simx_opmode_streaming) sim.simxSetJointTargetVelocity(clientID, jointHandles[i][1], targetVel[i], sim.simx_opmode_streaming) sim.simxPauseCommunication(clientID, False) time.sleep(2) #Now, attach a proximity sensor to the racquet and see if it detects a ball. If it does, let's start the #hitting motion #Actually, for now, let's just not worry about this. Let's make sure that the trajectory generation and the ball hitting #works targetPos0_ik[0] = targetPos0_ik[0] + (40 * np.pi/180) #To simulate a hit sim.simxPauseCommunication(clientID, True) for i in range(6): #print(jointHandles[i]) #print(targetPos0[i]) sim.simxSetJointTargetPosition(clientID, jointHandles[i][1], targetPos0_ik[i], sim.simx_opmode_streaming) sim.simxSetJointTargetVelocity(clientID, jointHandles[i][1], targetVel[i], sim.simx_opmode_streaming) sim.simxPauseCommunication(clientID, False) ball_hit=True hit_wall = False def radians(angle): return angle * (math.pi/180) def skew_symmetric(screw, theta): s_k = np.array([[0, -screw[2], screw[1], screw[3]], [screw[2], 0, -screw[0], screw[4]], [-screw[1], screw[0], 0, screw[5]], [0, 0, 0, 0]]) s_k *= theta return s_k def get_transform(M, S, theta_list): T = M for i in range(S.shape[0]): T = T @ expm(skew_symmetric(S[i,:].transpose(), theta_list[i])) return T def main(): global hit_wall global ball_coord global ball_linear global ball_hit global detect_handle global prox_handle global stop_prog print ('Program started') sim.simxFinish(-1) # just in case, close all opened connections clientID=sim.simxStart('127.0.0.1',19999,True,True,5000,5) # Connect to CoppeliaSim if clientID!=-1: print ('Connected to remote API server') # Now try to retrieve data in a blocking fashion (i.e. a service call): res,objs=sim.simxGetObjects(clientID,sim.sim_handle_all,sim.simx_opmode_blocking) if res==sim.simx_return_ok: print ('Number of objects in the scene: ',len(objs)) else: print ('Remote API function call returned with error code: ',res) time.sleep(2) #Giving an initial velocity to the ball before starting the thread detect_handle = sim.simxGetObjectHandle(clientID, 'Sphere', sim.simx_opmode_blocking) prox_handle = sim.simxGetObjectHandle(clientID, 'Proximity_sensor', sim.simx_opmode_blocking) racket_handle = sim.simxGetObjectHandle(clientID, 'Proximity_sensor0', sim.simx_opmode_blocking) dummy_handle = sim.simxGetObjectHandle(clientID, 'Cylinder', sim.simx_opmode_blocking) sim.simxSetObjectPosition(clientID, detect_handle[1], -1, [0.65, 0.47, 0.0463], sim.simx_opmode_oneshot) sim.simxPauseCommunication(clientID, True) sim.simxSetObjectFloatParameter(clientID, detect_handle[1], 3001, 1, sim.simx_opmode_oneshot) #sim.simxSetObjectFloatParameter(clientID, detect_handle[1], 3000, -0.01, sim.simx_opmode_oneshot) sim.simxSetObjectFloatParameter(clientID, detect_handle[1], 3002, 1, sim.simx_opmode_oneshot) sim.simxPauseCommunication(clientID, False) sim.simxReadProximitySensor(clientID, prox_handle[1], sim.simx_opmode_streaming) sim.simxGetObjectVelocity(clientID, detect_handle[1], sim.simx_opmode_streaming) sim.simxReadProximitySensor(clientID, racket_handle[1], sim.simx_opmode_streaming) sim.simxGetObjectPosition(clientID, dummy_handle[1], -1, sim.simx_opmode_streaming) ball_thread = threading.Thread(target=get_ball_info, args=({clientID:clientID})) try: #getting joint handles and initializing the joints in the simulation print("1. getting joint angles") jointHandles = [] for i in range(6): handle = sim.simxGetObjectHandle(clientID, 'UR3_joint' + str(i+1)+'#0', sim.simx_opmode_blocking) jointHandles.append(handle) time.sleep(0.01) for i in range(6): print (jointHandles[i]) #hit_thread = threading.Thread(target=hit_ball, args=({clientID:clientID})) ball_thread.daemon = True #hit_thread.daemon = True #hit_thread.start() ball_thread.start() # #Get handles for detecting object # detect_handle = sim.simxGetObjectHandle(clientID, 'Sphere', sim.simx_opmode_blocking) # #Get handles for detecting the proximity sensor # prox_handle = sim.simxGetObjectHandle(clientID, 'Proximity_sensor', sim.simx_opmode_blocking) #Create an instance to compute the ball trajectory print("1. Initializing bouncing trajectory function") b_ball = bouncing_ball.BouncingBall() #Set-up some of the RML vectors: vel=60 accel=10 jerk=20 currentVel=[0,0,0,0,0,0,0] currentAccel=[0,0,0,0,0,0,0] maxVel=[vel*math.pi/180,vel*math.pi/180,vel*math.pi/180,vel*math.pi/180,vel*math.pi/180,vel*math.pi/180] maxAccel=[accel*math.pi/180,accel*math.pi/180,accel*math.pi/180,accel*math.pi/180,accel*math.pi/180,accel*math.pi/180] maxJerk=[jerk*math.pi/180,jerk*math.pi/180,jerk*math.pi/180,jerk*math.pi/180,jerk*math.pi/180,jerk*math.pi/180] targetVel=[0,0,0,0,0,0] sim.simxPauseCommunication(clientID, True) for i in range(6): sim.simxSetJointTargetPosition(clientID, jointHandles[i][1], 0, sim.simx_opmode_streaming) sim.simxSetJointTargetVelocity(clientID, jointHandles[i][1], targetVel[i], sim.simx_opmode_streaming) sim.simxPauseCommunication(clientID, False) time.sleep(2) #start the feedback loop while True: if not hit_wall: #print("We haven't hit the wall yet") continue if hit_wall: print("We hit wall ....") #Predict the position of the ball from the wall and transform it to world coordinates print("Predicting Trajectory ...") pred_pos = b_ball.trajectory(ball_coord[0], ball_coord[1], ball_coord[2], ball_linear) T_prox = np.array([[-1, 0, 0, 0.025], [0, -1, 0, 2.85], [0, 0, 1, -.05], [0, 0, 0, 1]]) prox_pos = np.array([[pred_pos[0]], [pred_pos[1]], [pred_pos[2]],[1]]) ball_pos = T_prox @ prox_pos print(ball_pos) #set the left flag to true if on left side left = 0 if ball_pos[0,:] < 0: left=1 #convert to right-side coordinates for IK ball_pos[0,:] = np.abs(ball_pos[0,:]) if ball_pos[0, :] > 0.9: print("Ball too far away from robot. will not hit it ...") raise ValueError elif ball_pos[0,:] < 0.2: print("Ball too close. cannot hit it...") raise ValueError twist_angle = (-92.85) * (ball_pos[0,:]) + 90 print(ball_pos, "left?: ", left) targetPos0_ik = ik.findJointAngles(ball_pos[0,:], ball_pos[1,:], ball_pos[2,:] + 0.15) #Invert joint angles if on left side of robot for i in range(len(targetPos0_ik)): targetPos0_ik[i] = ((-2 * left) + 1) * targetPos0_ik[i] print("Applying the hitting motion") #Apply the hitting motion using the new joint angles end_pose = [] targetPos0_ik[0] = targetPos0_ik[0] + ((-2 * left) + 1) * (0 * np.pi/180) #To simulate a hit targetPos0_ik[4] = targetPos0_ik[4] + ((-2 * left) + 1) * (0 * np.pi/180) sim.simxPauseCommunication(clientID, True) for i in range(6): #print(jointHandles[i]) #print(targetPos0[i]) sim.simxSetJointTargetPosition(clientID, jointHandles[i][1], targetPos0_ik[i], sim.simx_opmode_streaming) sim.simxSetJointTargetVelocity(clientID, jointHandles[i][1], targetVel[i], sim.simx_opmode_streaming) sim.simxPauseCommunication(clientID, False) #Now read from the proximity sensor to see if it detects any ball ret, dS, dP, dOH, dSNV = sim.simxReadProximitySensor(clientID, racket_handle[1], sim.simx_opmode_buffer) while(dS == 0): _, end_pose = sim.simxGetObjectPosition(clientID, dummy_handle[1], -1, sim.simx_opmode_buffer) ret, dS, dP, dOH, dSNV = sim.simxReadProximitySensor(clientID, racket_handle[1], sim.simx_opmode_buffer) print("Status of Ball is: ", dS) #Now, attach a proximity sensor to the racquet and see if it detects a ball. If it does, let's start the #hitting motion #Actually, for now, let's just not worry about this. Let's make sure that the trajectory generation and the ball hitting #works print("Twist angle is: ", twist_angle) targetPos0_ik[0] = targetPos0_ik[0] + ((-2 * left) + 1) * ((1 * twist_angle) * np.pi/180) #To simulate a hit targetPos0_ik[4] = targetPos0_ik[4] + ((-2 * left) + 1) * (-1 * twist_angle * np.pi/180) # sim.simxPauseCommunication(clientID, True) # for i in range(6): # #print(jointHandles[i]) # #print(targetPos0[i]) # sim.simxSetJointTargetPosition(clientID, jointHandles[i][1], targetPos0_ik[i], sim.simx_opmode_buffer) # sim.simxSetJointTargetVelocity(clientID, jointHandles[i][1], targetVel[i], sim.simx_opmode_buffer) # sim.simxPauseCommunication(clientID, False) # time.sleep(2) ball_hit = True hit_wall = False sim.simxPauseCommunication(clientID, True) for i in [0,4]: sim.simxSetJointTargetPosition(clientID, jointHandles[i][1], targetPos0_ik[i], sim.simx_opmode_streaming) sim.simxSetJointTargetVelocity(clientID, jointHandles[i][1], targetVel[i], sim.simx_opmode_streaming) sim.simxPauseCommunication(clientID, False) time.sleep(2) sim.simxPauseCommunication(clientID, True) #Reset after hitting ball for i in range(6): #print(jointHandles[i]) #print(targetPos0[i]) sim.simxSetJointTargetPosition(clientID, jointHandles[i][1], 0, sim.simx_opmode_streaming) sim.simxSetJointTargetVelocity(clientID, jointHandles[i][1], targetVel[i], sim.simx_opmode_streaming) sim.simxPauseCommunication(clientID, False) ##Inverse Kinematics experiment and analysis: CAN BE COMMENTED OUT ball_pos[0,:] = (-2 * left + 1) * ball_pos[0,:] ball_pos[2,:] = ball_pos[2, :] + 0.15 end_pose = np.array(end_pose).reshape((3,1)) print("Desired position: \n", ball_pos[:3]) print("End-effector position: \n", end_pose[:3]) # print("Error (MMSE): ", np.linalg.norm(ball_pos[:3] - end_pose[:3])) # x_err = np.abs((end_pose[0,:] - ball_pos[0,:])/(ball_pos[0,:])) * 100 # y_err = np.abs((end_pose[1,:] - ball_pos[1,:])/(ball_pos[1,:])) * 100 # z_err = np.abs((end_pose[2,:] - ball_pos[2,:])/(ball_pos[2,:])) * 100 # print("Error in X (%): ", x_err) # print("Error in Y (%): ", y_err) # print("Error in Z (%): ", z_err) # print("Total Error (%): ", (x_err + y_err + z_err)/3) except: print(sys.exc_info()) #hit_thread.join() stop_prog = True print("Exception encountered, stopping program") #ball_thread.join() print("Ball thread stopped") sim.simxGetPingTime(clientID) # Now close the connection to CoppeliaSim: sim.simxFinish(clientID) else: print ('Failed connecting to remote API server') print ('Program ended') sim.simxGetPingTime(clientID) # Now close the connection to CoppeliaSim: sim.simxFinish(clientID) #print(objs) # # trying to get blob camera to detect the green ball in its line of sight # # need to replace simxReadVisionSensor with simxCheckVisionSensor so # # need to add this function to the sim.py library # blob_camera = sim.simxGetObjectHandle(clientID, 'blobDetectionCamera_camera', sim.simx_opmode_blocking) # vision_camera = sim.simxGetObjectHandle(clientID, 'Vision_sensor', sim.simx_opmode_blocking) # img_B = sim.simxGetVisionSensorImage(clientID, vision_camera[1], 0 , sim.simx_opmode_streaming) # detecting = sim.simxReadVisionSensor(clientID, vision_camera[1], sim.simx_opmode_blocking) # if(detecting[1] == 1): # print('Dectecting Ball \n') # else: # print('Not Dectecting Ball \n') # #Let's set the velocity of the ball # ball_handle = sim.simxGetObjectHandle(clientID, 'Sphere', sim.simx_opmode_blocking) # # sim.simxSetObjectPosition(clientID, ball_handle[1], -1, [-1, -1, 1], sim.simx_opmode_streaming) # # sim.simxPauseCommunication(clientID, True) # # sim.simxSetObjectFloatParameter(clientID, ball_handle[1], sim.sim_objfloatparam_abs_y_velocity, 3, sim.simx_opmode_streaming) # # sim.simxSetObjectFloatParameter(clientID, ball_handle[1], sim.sim_objfloatparam_abs_z_velocity, 5, sim.simx_opmode_streaming) # # sim.simxPauseCommunication(clientID, False) # print("Joint 1 Handles ... ") # jointHandles=[-1,-1,-1,-1,-1,-1] # for i in range(6): # jointHandles[i]=sim.simxGetObjectHandle(clientID, 'UR3_joint' + str(i+1)+'#', sim.simx_opmode_blocking) # print(jointHandles[i]) # print(" \n") # base_frame = sim.simxGetObjectHandle(clientID, 'Dummy0', sim.simx_opmode_blocking) # ee_frame = sim.simxGetObjectHandle(clientID, 'Dummy', sim.simx_opmode_blocking) # print("Base Frame handle: ", base_frame) # print("EE Frame handle: ", ee_frame) # print(" \n") # print("Joint 2 Handles ... ") # jointHandles_2 = [-1, -1, -1, -1, -1, -1] # for i in range(6): # jointHandles_2[i]=sim.simxGetObjectHandle(clientID, 'UR3_joint' + str(i+1)+'#0', sim.simx_opmode_blocking) # print(jointHandles_2[i]) # print(" ") # #Let's try getting the position and orientation of each of the joints: # ####pos0 = sim.simxGetObjectPosition(clientID, jointHandles_2[0][1], base_frame[1], sim.simx_opmode_blocking) # ####pos1 = sim.simxGetObjectPosition(clientID, jointHandles_2[0][1], base_frame[1], sim.simx_opmode_blocking) # pos_b_ee = sim.simxGetObjectPosition(clientID, ee_frame[1], base_frame[1], sim.simx_opmode_blocking) # #print(pos_b_ee[1]) # ori_b_ee = sim.simxGetObjectOrientation(clientID, ee_frame[1], base_frame[1], sim.simx_opmode_blocking) # #print(ori_b_ee) # rot_m = R.from_euler('xyz', np.array(ori_b_ee[1])) # #print(rot_m.as_dcm().shape) # M = np.zeros((4,4)) # M[3][3] = 1 # M[0:3, 0:3] = rot_m.as_dcm() # M[0:3, 3] = pos_b_ee[1] # print("Homogeneous transformation Matrix: ") # print(M) # print(" ") # ###ret_code, rot_matrix = sim.simxGetJointMatrix(clientID, jointHandles_2[5][1], sim.simx_opmode_blocking) # ###Get the joint positions and orientations with respect to base frame # np.set_printoptions(precision=3) # w = np.array([[0,0,1], [-1,0,0], [-1,0,0], [-1,0,0], [0,0,1], [1,0,0]]) # print("Angular Velocities: ") # print(w, "\n") # v = np.zeros((6,3)) # ret_code = 0 # for i in range(6): # ret_code, q = sim.simxGetObjectPosition(clientID, jointHandles_2[i][1], base_frame[1], sim.simx_opmode_blocking) # q = np.array(q) # v[i,:] = np.cross(-1 * w[i,:], q) # print("Linear Velocities: ") # print(v, "\n") # S = np.zeros((6,6)) # S[:, 0:3] = w # S[:, 3:6] = v # S_t = S.transpose() # print("Screw Matrix: ") # print(S_t, "\n") # debugging # #T = mr.FKinSpace(M, S_t, np.array([radians(90),radians(90),radians(-92),radians(233),radians(33),radians(24)])) #Fill the array with actual values later # T = get_transform(M, S_t, np.zeros((6,)))#print(type(T)) # print("New Transformation Matrix: ") # print(T, "\n") # old_pos = np.ones((4,1)) # old_pos[0:3] = 0 # old_pos.resize((4,1)) # new_pose = T @ old_pos # print("New Position: ") # print(new_pose) # new_pose.resize((4,)) # #Set-up some of the RML vectors: # vel=90 # accel=20 # jerk=40 # currentVel=[0,0,0,0,0,0,0] # currentAccel=[0,0,0,0,0,0,0] # maxVel=[vel*math.pi/180,vel*math.pi/180,vel*math.pi/180,vel*math.pi/180,vel*math.pi/180,vel*math.pi/180] # maxAccel=[accel*math.pi/180,accel*math.pi/180,accel*math.pi/180,accel*math.pi/180,accel*math.pi/180,accel*math.pi/180] # maxJerk=[jerk*math.pi/180,jerk*math.pi/180,jerk*math.pi/180,jerk*math.pi/180,jerk*math.pi/180,jerk*math.pi/180] # targetVel=[0,0,0,0,0,0] # #I'm gonna try looking at the various ways in which the ping pong ball can hit # #Right side: # #Max(Theta2): 64.1, Max(Theta3): 84.1, Theta 5: -90, Theta 6: 90 # #Left side: # #Max(Theta2): -64.1, Max(Theta3): -84.1, Theta 5: 90, Theta 6: 90 # # targetPos0 = [radians(0),radians(64.1),radians(0),radians(0),radians(-90),radians(90)] # # sim.simxPauseCommunication(clientID, True) # # for i in range(6): # # #print(jointHandles[i]) # # #print(targetPos0[i]) # # sim.simxSetJointTargetPosition(clientID, jointHandles_2[i][1], targetPos0[i], sim.simx_opmode_streaming) # # sim.simxSetJointTargetVelocity(clientID, jointHandles_2[i][1], targetVel[i], sim.simx_opmode_streaming) # # sim.simxPauseCommunication(clientID, False) # # time.sleep(1) # # targetPos0 = [radians(10),radians(64.1),radians(0),radians(0),radians(-90),radians(90)] # # sim.simxPauseCommunication(clientID, True) # # for i in range(6): # # #print(jointHandles[i]) # # #print(targetPos0[i]) # # sim.simxSetJointTargetPosition(clientID, jointHandles_2[i][1], targetPos0[i], sim.simx_opmode_streaming) # # sim.simxSetJointTargetVelocity(clientID, jointHandles_2[i][1], targetVel[i], sim.simx_opmode_streaming) # # sim.simxPauseCommunication(clientID, False) # # time.sleep(1) # sim.simxPauseCommunication(clientID, True) # for i in range(6): # #print(jointHandles[i]) # #print(targetPos0[i]) # sim.simxSetJointTargetPosition(clientID, jointHandles_2[i][1], 0, sim.simx_opmode_streaming) # sim.simxSetJointTargetVelocity(clientID, jointHandles_2[i][1], targetVel[i], sim.simx_opmode_streaming) # sim.simxPauseCommunication(clientID, False) # time.sleep(2) # # ##Now, let us set up the Position of our dummy to match the position of the end_effector # # sim.simxSetObjectPosition(clientID, ee_frame[1], base_frame[1], new_pose[0:3], sim.simx_opmode_streaming) # # ##Then, let's also setup the orientation, after converting them to euler angles # # new_rot_mat = T[0:3,0:3] # # new_rot = R.from_dcm(new_rot_mat) # # new_ori_b_ee = new_rot.as_euler('xyz') # # sim.simxSetObjectOrientation(clientID, ee_frame[1], base_frame[1], new_ori_b_ee, sim.simx_opmode_streaming # print("\n", "Now trying inverse kinematics: ") # time.sleep(2) # _, ball_pos = sim.simxGetObjectPosition(clientID, ball_handle[1], -1, sim.simx_opmode_blocking) # _, ball_ori = sim.simxGetObjectOrientation(clientID, ball_handle[1], -1, sim.simx_opmode_blocking) # ball_rot = R.from_euler('xyz', ball_ori) # ball_rot_mat = ball_rot.as_dcm() # # ball_pos[0] = ball_pos[0] # # ball_pos[1] = ball_pos[1] # world_coord = np.array([ball_pos[0], ball_pos[1]-.07, ball_pos[2]]) # world_coord = np.abs(world_coord) # guess_angles = ik.findJointAngles(world_coord[0]+.07, world_coord[1], world_coord[2]+0.1) # targetPos0_ik = guess_angles # #Invert the angles if on left side # if(ball_pos[0] < 0): # targetPos0_ik[0] = -guess_angles[0] # targetPos0_ik[1] = -guess_angles[1] # targetPos0_ik[2] = -guess_angles[2] # targetPos0_ik[3] = -guess_angles[3] # targetPos0_ik[4] = radians(90) # targetPos0_ik[5] = radians(90) # print(guess_angles) #DEBUG # sim.simxPauseCommunication(clientID, True) # for i in range(6): # #print(jointHandles[i]) # #print(targetPos0[i]) # sim.simxSetJointTargetPosition(clientID, jointHandles_2[i][1], 0, sim.simx_opmode_streaming) # sim.simxSetJointTargetVelocity(clientID, jointHandles_2[i][1], targetVel[i], sim.simx_opmode_streaming) # sim.simxPauseCommunication(clientID, False) # sim.simxPauseCommunication(clientID, True) # for i in range(6): # #print(jointHandles[i]) # #print(targetPos0[i]) # sim.simxSetJointTargetPosition(clientID, jointHandles_2[i][1], targetPos0_ik[i], sim.simx_opmode_streaming) # sim.simxSetJointTargetVelocity(clientID, jointHandles_2[i][1], targetVel[i], sim.simx_opmode_streaming) # sim.simxPauseCommunication(clientID, False) # time.sleep(2) # # sim.simxPauseCommunication(clientID, True) # # for i in range(6): # # #print(jointHandles[i]) # # #print(targetPos0[i]) # # sim.simxSetJointTargetPosition(clientID, jointHandles_2[i][1], 0, sim.simx_opmode_streaming) # # sim.simxSetJointTargetVelocity(clientID, jointHandles_2[i][1], targetVel[i], sim.simx_opmode_streaming) # # sim.simxPauseCommunication(clientID, False) # # time.sleep(2) # # T_b = np.zeros((4,4)) # # T_b[3,3] = 1 # # T_b[0:3, 0:3] = ball_rot_mat # # T_b[0:3, 3] = ball_pos # # print("Ball Position: ", ball_pos) # # print("Ball Rotation: ", ball_rot.as_dcm()) # # #theta_list_guess = np.array([radians(-70), radians(-50), radians(-50), radians(-30), radians(50), radians(0)]) # # theta_list_guess = np.array([radians(0),radians(64.1),radians(0),radians(0),radians(90),radians(90)]) # # theta_list, success = mr.IKinSpace(S, M, T_b, theta_list_guess, 0.01, 0.01) # # if success: # # print(theta_list) # # else: # # print("Not successful, but here's the guess: \n", theta_list) # #Now, let's check how close we are to the actual ball: # # sim.simxPauseCommunication(clientID, True) # # for i in range(6): # # #print(jointHandles[i]) # # #print(targetPos0[i]) # # sim.simxSetJointTargetPosition(clientID, jointHandles_2[i][1], targetPos0_ik[i], sim.simx_opmode_streaming) # # sim.simxSetJointTargetVelocity(clientID, jointHandles_2[i][1], targetVel[i], sim.simx_opmode_streaming) # # sim.simxPauseCommunication(clientID, False) # # time.sleep(2) # #sim.simxSetObjectPosition(clientID, P_ball_handle[1], -1, [-1, -1, 1], sim.simx_opmode_streaming) # Before closing the connection to CoppeliaSim, make sure that the last command sent out had time to arrive. You can guarantee this with (for example): # sim.rmlMoveToJointPositions(jointHandles, -1, currentVel, currentAccel, maxVel, maxAccel, maxJerk, targetPos0, targetVel) # time.sleep(1) # targetPos1 = [radians(90),radians(90),radians(-92),radians(233),radians(33),radians(24)] # sim.simxPauseCommunication(clientID, True) # for i in range(6): # #print(jointHandles[i]) # #print(targetPos0[i]) # if(i==0): # sim.simxSetJointTargetPosition(clientID, jointHandles_2[i][1], targetPos1[i], sim.simx_opmode_streaming) # sim.simxSetJointTargetVelocity(clientID, jointHandles_2[i][1], targetVel[i], sim.simx_opmode_streaming) # else: # sim.simxSetJointTargetPosition(clientID, jointHandles_2[i][1], targetPos1[i], sim.simx_opmode_buffer) # sim.simxSetJointTargetVelocity(clientID, jointHandles_2[i][1], targetVel[i], sim.simx_opmode_buffer) # sim.simxPauseCommunication(clientID, False) # time.sleep(1) # # sim.rmlMoveToJointPositions(jointHandles,-1,currentVel,currentAccel,maxVel,maxAccel,maxJerk,targetPos1,targetVel) # time.sleep(1) # targetPos2 = [radians(90),radians(90),radians(-92),radians(233),radians(33),radians(24)] # sim.simxPauseCommunication(clientID, True) # for i in range(6): # #print(jointHandles[i]) # #print(targetPos0[i]) # if(i==0): # sim.simxSetJointTargetPosition(clientID, jointHandles[i][1], targetPos2[i], sim.simx_opmode_streaming) # sim.simxSetJointTargetVelocity(clientID, jointHandles[i][1], targetVel[i], sim.simx_opmode_streaming) # else: # sim.simxSetJointTargetPosition(clientID, jointHandles[i][1], targetPos2[i], sim.simx_opmode_buffer) # sim.simxSetJointTargetVelocity(clientID, jointHandles[i][1], targetVel[i], sim.simx_opmode_buffer) # sim.simxPauseCommunication(clientID, False) # # sim.rmlMoveToJointPositions(jointHandles,-1,currentVel,currentAccel,maxVel,maxAccel,maxJerk,targetPos2,targetVel) # time.sleep(1) # targetPos3=[0,0,0,0,0,0] # #targetPos2 = [radians(90),radians(90),radians(-92),radians(233),radians(33),radians(24)] # sim.simxPauseCommunication(clientID, True) # for i in range(6): # #print(jointHandles[i]) # #print(targetPos0[i]) # if(i==0): # sim.simxSetJointTargetPosition(clientID, jointHandles[i][1], targetPos3[i], sim.simx_opmode_streaming) # sim.simxSetJointTargetVelocity(clientID, jointHandles[i][1], targetVel[i], sim.simx_opmode_streaming) # else: # sim.simxSetJointTargetPosition(clientID, jointHandles[i][1], targetPos3[i], sim.simx_opmode_buffer) # sim.simxSetJointTargetVelocity(clientID, jointHandles[i][1], targetVel[i], sim.simx_opmode_buffer) # sim.simxPauseCommunication(clientID, False) # time.sleep(1) # # sim.rmlMoveToJointPositions(jointHandles,-1,currentVel,currentAccel,maxVel,maxAccel,maxJerk,targetPos3,targetVel) # # # Now retrieve streaming data (i.e. in a non-blocking fashion): # # startTime=time.time() # # sim.simxGetIntegerParameter(clientID,sim.sim_intparam_mouse_x,sim.simx_opmode_streaming) # Initialize streaming # # while time.time()-startTime < 5: # # returnCode,data=sim.simxGetIntegerParameter(clientID,sim.sim_intparam_mouse_x,sim.simx_opmode_buffer) # Try to retrieve the streamed data # # if returnCode==sim.simx_return_ok: # After initialization of streaming, it will take a few ms before the first value arrives, so check the return code # # print ('Mouse position x: ',data) # Mouse position x is actualized when the cursor is over CoppeliaSim's window # # time.sleep(0.005) # # Now send some data to CoppeliaSim in a non-blocking fashion: # sim.simxAddStatusbarMessage(clientID,'Hello CoppeliaSim!',sim.simx_opmode_oneshot) # #Let's try reading some vision sensor data # sensor_handle = sim.simxGetObjectHandle(clientID, 'Vision_sensor', sim.simx_opmode_blocking) # #img = sim.simxGetVisionSensorImage(clientID, sensor_handle[1], 0 , sim.simx_opmode_buffer) # #print(type(img)) # #print(img) # #cv2.imshow(img) # #return_code, detection_state, aux_packets = sim.simxReadVisionSensor(clientID, sensor_handle[1], sim.simx_opmode_buffer) # img = sim.simxGetVisionSensorImage(clientID, sensor_handle[1], 0, sim.simx_opmode_streaming) # print(img) # #print(return_code) # #print(detection_state) if __name__ == '__main__': main() #https://youtu.be/l0C5E4iqqRI # Video link #https://youtu.be/Qj7Sv0V9yec <file_sep>/ur3_orig.lua -- This is a threaded script, and is just an example! --simRemoteApi.start(19999) function radians(degree_angle) return degree_angle * (math.pi/180) end function sysCall_threadmain() jointHandles={-1,-1,-1,-1,-1,-1} for i=1,6,1 do jointHandles[i]=sim.getObjectHandle('UR3_joint'..i) end -- Set-up some of the RML vectors: vel=180 accel=40 jerk=80 currentVel={0,0,0,0,0,0,0} currentAccel={0,0,0,0,0,0,0} maxVel={vel*math.pi/180,vel*math.pi/180,vel*math.pi/180,vel*math.pi/180,vel*math.pi/180,vel*math.pi/180} maxAccel={accel*math.pi/180,accel*math.pi/180,accel*math.pi/180,accel*math.pi/180,accel*math.pi/180,accel*math.pi/180} maxJerk={jerk*math.pi/180,jerk*math.pi/180,jerk*math.pi/180,jerk*math.pi/180,jerk*math.pi/180,jerk*math.pi/180} targetVel={0,0,0,0,0,0} targetPos0 = {radians(90),radians(90),radians(-92),radians(233),radians(33),radians(24)} sim.rmlMoveToJointPositions(jointHandles, -1, currentVel, currentAccel, maxVel, maxAccel, maxJerk, targetPos0, targetVel) targetPos1 = {radians(90),radians(90 ),radians(-92),radians(233),radians(33),radians(24)} sim.rmlMoveToJointPositions(jointHandles,-1,currentVel,currentAccel,maxVel,maxAccel,maxJerk,targetPos1,targetVel) targetPos2 = {radians(90),radians(90),radians(-92),radians(233),radians(33),radians(24)} sim.rmlMoveToJointPositions(jointHandles,-1,currentVel,currentAccel,maxVel,maxAccel,maxJerk,targetPos2,targetVel) targetPos3={0,0,0,0,0,0} sim.rmlMoveToJointPositions(jointHandles,-1,currentVel,currentAccel,maxVel,maxAccel,maxJerk,targetPos3,targetVel) end -- function sysCall_init() -- -- Prepare a floating view with the camera views: -- cam=sim.getObjectAssociatedWithScript(sim.handle_self) -- view=sim.floatingViewAdd(0.9,0.3,0.2,0.2,0) -- sim.adjustView(view,cam,64) -- end -- function sysCall_actuation() -- cam_handle = sim.getObjectHandle('Vision_sensor') -- sim.handleVisionSensor(cam_handle) -- result, t1, t2, t3 = sim.readVisionSensor(cam_handle) -- print(result) -- end -- function sysCall_cleanup() -- if sim.isHandleValid(cam)==1 then -- sim.floatingViewRemove(view) -- end -- end <file_sep>/forward_kinematics.py import sympy as sym import numpy as np import math from scipy.linalg import expm from sympy import * def main(): #symbolic variables for the symbolic transformation matrix theta1 = Symbol('theta1') theta2 = Symbol('theta2') theta3 = Symbol('theta3') theta4 = Symbol('theta4') theta5 = Symbol('theta5') theta6 = Symbol('theta6') # matrices that hold the symbolic thetas sym_thetas = sym.Matrix([theta1, theta2, theta3, theta4, theta5, theta6]) # change these values to test different verifications input = [-58.018, -84.526, 88.264, -3.738, -90.0, 76.982] # holds the real theta values for later subsitution real_thetas = sym.Matrix([radians(input[0]), radians(input[1]), radians(input[2]), radians(input[3]), radians(input[4]), radians(input[5])]) # stores the symbolic matrix into T_matrix T_matrix = symbolic_sol(sym_thetas) # matrix that holds the numerical value of the displacement Num_matrix = numeric_sol(T_matrix, real_thetas, sym_thetas) # debugging numerical values print("Answer to the verification values: ") print(Num_matrix) def numeric_sol(T, r_thetas, s_thetas): # T is for some reason a 1D matrix, so the x,y,z values are stored at the 3,7,11 respectively # because the row is 4 wide x = T[3] y = T[7] z = T[11] # substituting the real theta values into the symbolic x = x.subs({s_thetas[0]: r_thetas[0], s_thetas[1]: r_thetas[1], s_thetas[2]: r_thetas[2], s_thetas[3]: r_thetas[3], s_thetas[4]: r_thetas[4], s_thetas[5]: r_thetas[5]}) y = y.subs({s_thetas[0]: r_thetas[0], s_thetas[1]: r_thetas[1], s_thetas[2]: r_thetas[2], s_thetas[3]: r_thetas[3], s_thetas[4]: r_thetas[4], s_thetas[5]: r_thetas[5]}) z = z.subs({s_thetas[0]: r_thetas[0], s_thetas[1]: r_thetas[1], s_thetas[2]: r_thetas[2], s_thetas[3]: r_thetas[3], s_thetas[4]: r_thetas[4], s_thetas[5]: r_thetas[5]}) # stores x,y,z values into a single matrix numeric_sol = sym.Matrix([[x], [y], [z]]) # evaluates any remaining sins and cosines ans = numeric_sol.evalf() return ans def radians(angle): return angle * (math.pi/180) def skew_symmetric(screw): # calculates the skew matrix * theta for easy exponential matrix s_k = sym.Matrix([[0, -screw[2], screw[1]], [screw[2], 0, -screw[0]], [-screw[1], screw[0], 0]]) return s_k def exponential_matrix(w, v, theta): # Identity matrix I = sym.Matrix([[1,0,0], [0,1,0], [0,0,1]]) # upper left term of the exponential screw matrix using rodriguez's formula ex_w = simplify(I + sin(theta)*skew_symmetric(w) + (1-cos(theta))*skew_symmetric(w)**2) # upper right term of the exponential screw matrix v_new = simplify(((I*theta) + (1-cos(theta))*skew_symmetric(w) + (theta - sin(theta))*skew_symmetric(w)**2)*v) # combining the two calculated terms into a homogenous 4x4 matrix ex_screw = sym.Matrix([[ex_w[0], ex_w[1], ex_w[2], v_new[0]], [ex_w[3], ex_w[4], ex_w[5], v_new[1]], [ex_w[6], ex_w[7], ex_w[8], v_new[2]], [0,0,0,1]]) return ex_screw def symbolic_sol(theta_sym): # code is very redundant due to not being able to # figure out how to 2D cross multiply with sympy, so all the # joints have individual variables that store their zero position values w1 = sym.Matrix([[0,0,1]]) w2 = sym.Matrix([[0,1,0]]) w3 = sym.Matrix([[0,1,0]]) w4 = sym.Matrix([[0,1,0]]) w5 = sym.Matrix([[1,0,0]]) w6 = sym.Matrix([[0,1,0]]) q1 = sym.Matrix([[-0.15, 0.15, 0.01]]) q2 = sym.Matrix([[-0.15, 0.27, 0.162]]) q3 = sym.Matrix([[0.094, 0.27, 0.162]]) q4 = sym.Matrix([[0.307, 0.177, 0.162]]) q5 = sym.Matrix([[0.307, 0.260, 0.162]]) q6 = sym.Matrix([[0.390, 0.260, 0.162]]) # calculates v of (w,v) by v = -w X q v1 = -w1.cross(q1) v2 = -w2.cross(q2) v3 = -w3.cross(q3) v4 = -w4.cross(q4) v5 = -w5.cross(q5) v6 = -w6.cross(q6) # print("Velocities of calculations") # print(v1) # print(v2) # print(v3) # print(v4) # print(v5) # print(v6) # print("End of velocities") # stores the (w,v) components of each screw into a matrix for each screw s1 = sym.Matrix([[w1[0], w1[1], w1[2], v1[0], v1[1], v1[2]]]) s2 = sym.Matrix([[w2[0], w2[1], w2[2], v2[0], v2[1], v2[2]]]) s3 = sym.Matrix([[w3[0], w3[1], w3[2], v3[0], v3[1], v3[2]]]) s4 = sym.Matrix([[w4[0], w4[1], w4[2], v4[0], v4[1], v4[2]]]) s5 = sym.Matrix([[w5[0], w5[1], w5[2], v5[0], v5[1], v5[2]]]) s6 = sym.Matrix([[w6[0], w6[1], w6[2], v6[0], v6[1], v6[2]]]) # have to reorganize the v matrix from 1x3 to 3x1 so it will work with exponential matrix calculations v1 = sym.Matrix([[v1[0]],[v1[1]],[v1[2]]]) v2 = sym.Matrix([[v2[0]],[v2[1]],[v2[2]]]) v3 = sym.Matrix([[v3[0]],[v3[1]],[v3[2]]]) v4 = sym.Matrix([[v4[0]],[v4[1]],[v4[2]]]) v5 = sym.Matrix([[v5[0]],[v5[1]],[v5[2]]]) v6 = sym.Matrix([[v6[0]],[v6[1]],[v6[2]]]) # caclulates the symbolic exponential matrix of each screw * respective theta ex_1 = simplify(exponential_matrix(w1, v1, theta_sym[0])) ex_2 = simplify(exponential_matrix(w2, v2, theta_sym[1])) ex_3 = simplify(exponential_matrix(w3, v3, theta_sym[2])) ex_4 = simplify(exponential_matrix(w4, v4, theta_sym[3])) ex_5 = simplify(exponential_matrix(w5, v5, theta_sym[4])) ex_6 = simplify(exponential_matrix(w6, v6, theta_sym[5])) # print("Exponential 1") # print(ex_1) # print("Exponential 2") # print(ex_2) # print("Exponential 3") # print(ex_3) # print("Exponential 4") # print(ex_4) # print("Exponential 5") # print(ex_5) # print("Exponential 6") # print(ex_6) # homogenous transformation matrix of zero position M = sym.Matrix([[0, 0, 1, 0.390], [-1, 0, 0, 0.401], [0, -1, 0, 0.2155], [0, 0, 0, 1]]) # product of exponentials equation for calculation frame transformation matrix T = ex_1 * ex_2 * ex_3 * ex_4 * ex_5 * ex_6 * M return T # call main to run the calculations if __name__ == '__main__': main() <file_sep>/README.md # Ping Pong Robot Simulation for ECE 470 - Spring 2020 ## Objective The goal of this project is to have two robots (UR3) simulate rallying a ping-pong ball back and forth through the use of simple hits. The robots will detect the ping pong ball and calculate their position based on the ball's location and make predicative measurements to get ready to hit the ball back. ## Execute Program We are connecting remotely to coppelia through the python script, so to run the simulation, run project.ttt file and then run the python script stest.py ## Description of files stest.py is the main file for demonstrating our use of our simulator (CoppeliaSim). This file is the basis for demonstrating basic movement of the robot and the basis for collecting vision sensor data. inverse_kinematics.py contains our code for computing the joint angles of the robot using our customized elbow-up configuration given the desired world coordinates bouncing_ball.py contains our code for finding the linear trajectory of the ball. sim.py contains all of our function definitions for use with the robot. simConst.py contains all of our constant variables for use with the robot. This file groups all of them together into specific subclasses which makes it easier to find the variables. simpleTest.py is our old code for interacting with the simulator. It contains the code we used to generate the videos for the project updates. ur3_orig.lua is the original code on coppelia for the UR3. ur3_remote.lua is the most recent up to date code on coppelia for the UR3. ### Other notes The python script is written in python3 and requires numpy, scipy and the modern_robotics package. It also uses the simx API, which is used to connect remotely to the CoppeliaSim scene ## Forward Kinematics We implement our forward kinematics in simpleTest.py. In it, we convert the euler angles which we get from the simulation into the Rotation Matrix required for the model using the `scipy.spatial.transform.rotation` module. Using this and the position, we then get the original transformation matrix M. By inspection, we got the axes of rotation (w) for our joints and got the location of these joints (the qs ) through the remote API. We then calculated the cross product using `np.cross()` to get our linear velocities (v). Using w and v, we create the set of screw axes, S. From there, we use the `mr.FKinSpace()` subroutine to calculate the new transformation matrix for a certain set of joint angles. To verify our answer visually, we move a dummy object to the new calculated frame of the end-effector after setting the new joint angles. ## Inverse Kinematics We implement our inverse kinematics in inverse_kinematics.py and invoke it. We use a customized elbow-up configuration of the UR3 to generate the joint positions. ## Trajectory Generation We implement our line trajectory generation in bouncing_ball.py. In it, we take the last recorded position and velocity of the ball as it left the wall and predict the position of the ball when it reaches a position close to the robot. Here, we just use a linear approximation for the equation. ## Other files that we did not end up using in the project project_vish.ttt contains the file that Vishal used for initial simulation testing. We initially had a modern_robotics package provided by <NAME> and <NAME> as part of their software package for the textbook. However, since the package didn't work well with our simulation and we wrote our own code for inverse kineamtics, we did not actually end up using this package in the project. <file_sep>/inverse_kinematics.py import numpy as np def radians(degree): """ helper function to convert angle from degrees to radians """ return degree * (np.pi/180) def degrees(radian): """ helper function to convert angle from radians to degrees """ return radian * (180/np.pi) def findJointAngles(x_wgrip, y_wgrip, z_wgrip): """ @param x_wgrip: desired x-coordinate of end-effector in world frame @param y_wgrip: desired y-coordinate of end-effector world frame @param z_wgrip: desired z-coordinate of end-effector in world frame @return value: [theta1, theta2, theta3, theta4, theta5, theta6]: joint angles needed for desired configuration """ L01 = 0.152 L02 = 0.120 L03 = 0.244 L04 = 0.093 L05 = 0.213 L06 = 0.083 L07 = 0.083 L08 = 0.082 L09 = 0.238 L10 = 0.059 Lend = L06 + 0.027 #abstract extended link 6 to help in calculations L_link = L08 + L09 theta1 = 0 theta2 = 0 theta3 = 0 theta4 = 0 theta5 = radians(-90) theta6 = radians(-90) #Find the grip coordinates, by subtracting from the coordinates the displacement of the base frame x_grip = x_wgrip y_grip = y_wgrip z_grip = z_wgrip - 0.043 # #Find x_cen, y_cen and z_cen, the center of joint 6, to figure out the thetas # x_cen = x_grip - L09 * np.cos(yaw) # y_cen = y_grip - L09 * np.sin(yaw) # z_cen = z_grip x_cen = x_grip y_cen = y_grip z_cen = z_grip #Creating helper variables and using them to find theta1 theta_x = np.arctan2(y_cen, x_cen) theta_y = np.arcsin(Lend/np.sqrt(x_cen**2 + y_cen**2)) theta1 = theta_x - theta_y #Finding theta6 using theta1 and yaw #theta6 = radians(90) - yaw + theta1 #Finding x_3end, y_3end and z_3end, coordinates of the extension of Link 6 #used as helper variables for finding theta2, theta3 and theta4 x_3end = x_cen + Lend * np.sin(theta1) - L_link * np.cos(theta1) y_3end = y_cen - Lend * np.cos(theta1) - L_link * np.sin(theta1) z_3end = z_cen - L07 #Finding theta2, theta3 and theta4 #Using helper angles, theta_i and theta_j and helper length L_3endto find theta_2 L_3end = np.sqrt(x_3end**2 + y_3end**2 + (z_3end - L01)**2) theta_i = np.arcsin((z_3end - L01)/L_3end) theta_j = np.arccos((L05**2 - L03**2 - L_3end**2)/(-2 * L03 * L_3end)) #Calculate theta2, theta3 and theta4 theta2 = (np.pi/2) - (theta_i + theta_j) theta3 = np.arccos((L_3end**2 - L03**2 - L05**2)/(2 * L03 * L05)) theta4 = -(theta2 + theta3) return [theta1,theta2, theta3, theta4, theta5, theta6] #Function for calculating outputs for verification def main(): x_w = 0.2 y_w = 0.4 z_w = 0.05 #yaw = radians(45) theta_list = findJointAngles(x_w, y_w, z_w) print([np.round(degrees(theta),3) for theta in theta_list]) if __name__ == '__main__': main()<file_sep>/ur3_remote.lua -- This is a threaded script, and is just an example! simRemoteApi.start(19999) -- function radians(degree_angle) -- return degree_angle * (math.pi/180) -- end -- function sysCall_threadmain() -- jointHandles={-1,-1,-1,-1,-1,-1} -- for i=1,6,1 do -- jointHandles[i]=sim.getObjectHandle('UR3_joint'..i) -- end -- -- Set-up some of the RML vectors: -- vel=180 -- accel=40 -- jerk=80 -- currentVel={0,0,0,0,0,0,0} -- currentAccel={0,0,0,0,0,0,0} -- maxVel={vel*math.pi/180,vel*math.pi/180,vel*math.pi/180,vel*math.pi/180,vel*math.pi/180,vel*math.pi/180} -- maxAccel={accel*math.pi/180,accel*math.pi/180,accel*math.pi/180,accel*math.pi/180,accel*math.pi/180,accel*math.pi/180} -- maxJerk={jerk*math.pi/180,jerk*math.pi/180,jerk*math.pi/180,jerk*math.pi/180,jerk*math.pi/180,jerk*math.pi/180} -- targetVel={0,0,0,0,0,0} -- targetPos0 = {radians(90),radians(90),radians(-92),radians(233),radians(33),radians(24)} -- sim.rmlMoveToJointPositions(jointHandles, -1, currentVel, currentAccel, maxVel, maxAccel, maxJerk, targetPos0, targetVel) -- targetPos1 = {radians(90),radians(90 -- ),radians(-92),radians(233),radians(33),radians(24)} -- sim.rmlMoveToJointPositions(jointHandles,-1,currentVel,currentAccel,maxVel,maxAccel,maxJerk,targetPos1,targetVel) -- targetPos2 = {radians(90),radians(90),radians(-92),radians(233),radians(33),radians(24)} -- sim.rmlMoveToJointPositions(jointHandles,-1,currentVel,currentAccel,maxVel,maxAccel,maxJerk,targetPos2,targetVel) -- targetPos3={0,0,0,0,0,0} -- sim.rmlMoveToJointPositions(jointHandles,-1,currentVel,currentAccel,maxVel,maxAccel,maxJerk,targetPos3,targetVel) -- end -- function sysCall_threadmain() -- jointHandles={-1,-1,-1,-1,-1,-1} -- for i=1,6,1 do -- jointHandles[i]=sim.getObjectHandle('UR3_joint'..i) -- end -- -- Set-up some of the RML vectors: -- vel=180 -- accel=40 -- jerk=80 -- currentVel={0,0,0,0,0,0,0} -- currentAccel={0,0,0,0,0,0,0} -- maxVel={vel*math.pi/180,vel*math.pi/180,vel*math.pi/180,vel*math.pi/180,vel*math.pi/180,vel*math.pi/180} -- maxAccel={accel*math.pi/180,accel*math.pi/180,accel*math.pi/180,accel*math.pi/180,accel*math.pi/180,accel*math.pi/180} -- maxJerk={jerk*math.pi/180,jerk*math.pi/180,jerk*math.pi/180,jerk*math.pi/180,jerk*math.pi/180,jerk*math.pi/180} -- targetVel={0,0,0,0,0,0} -- targetPos1={90*math.pi/180,90*math.pi/180,-90*math.pi/180,90*math.pi/180,90*math.pi/180,90*math.pi/180} -- sim.rmlMoveToJointPositions(jointHandles,-1,currentVel,currentAccel,maxVel,maxAccel,maxJerk,targetPos1,targetVel) -- targetPos2={-90*math.pi/180,45*math.pi/180,90*math.pi/180,135*math.pi/180,90*math.pi/180,90*math.pi/180} -- sim.rmlMoveToJointPositions(jointHandles,-1,currentVel,currentAccel,maxVel,maxAccel,maxJerk,targetPos2,targetVel) -- targetPos3={0,0,0,0,0,0} -- sim.rmlMoveToJointPositions(jointHandles,-1,currentVel,currentAccel,maxVel,maxAccel,maxJerk,targetPos3,targetVel) -- end<file_sep>/simpleTest.py # Make sure to have the server side running in CoppeliaSim: # in a child script of a CoppeliaSim scene, add following command # to be executed just once, at simulation start: # # simRemoteApi.start(19999) # # then start simulation, and run this program. # # IMPORTANT: for each successful call to simxStart, there # should be a corresponding call to simxFinish at the end! from scipy.spatial.transform import Rotation as R from scipy.linalg import expm import sys sys.path.append('./') import inverse_kinematics as ik from bouncing_ball import BouncingBall #import modern_robotics as mr def radians(angle): return angle * (math.pi/180) def degrees(angle): return angle * (180/math.pi) def skew_symmetric(screw, theta): s_k = np.array([[0, -screw[2], screw[1], screw[3]], [screw[2], 0, -screw[0], screw[4]], [-screw[1], screw[0], 0, screw[5]], [0, 0, 0, 0]]) s_k *= theta return s_k def get_transform(M, S, theta_list): T = M for i in range(S.shape[0]): T = T @ expm(skew_symmetric(S[i,:].transpose(), theta_list[i])) return T try: import sim except: print ('--------------------------------------------------------------') print ('"sim.py" could not be imported. This means very probably that') print ('either "sim.py" or the remoteApi library could not be found.') print ('Make sure both are in the same folder as this file,') print ('or appropriately adjust the file "sim.py"') print ('--------------------------------------------------------------') print ('') import time import math import numpy as np print ('Program started') sim.simxFinish(-1) # just in case, close all opened connections clientID=sim.simxStart('127.0.0.1',19999,True,True,5000,5) # Connect to CoppeliaSim if clientID!=-1: print ('Connected to remote API server') # Now try to retrieve data in a blocking fashion (i.e. a service call): res,objs=sim.simxGetObjects(clientID,sim.sim_handle_all,sim.simx_opmode_blocking) if res==sim.simx_return_ok: print ('Number of objects in the scene: ',len(objs)) else: print ('Remote API function call returned with error code: ',res) time.sleep(2) #print(objs) # using proximity sensor to detect when the ball hits the wall (enters proximity range) detect_handle = sim.simxGetObjectHandle(clientID, 'Sphere', sim.simx_opmode_blocking) prox_handle = sim.simxGetObjectHandle(clientID, 'Proximity_sensor', sim.simx_opmode_blocking) sim.simxSetObjectPosition(clientID, detect_handle[1], -1, [0.5, 0.475, 0.0463], sim.simx_opmode_oneshot) sim.simxPauseCommunication(clientID, True) sim.simxSetObjectFloatParameter(clientID, detect_handle[1], 3001, 2, sim.simx_opmode_oneshot) sim.simxSetObjectFloatParameter(clientID, detect_handle[1], 3002, 2, sim.simx_opmode_oneshot) sim.simxPauseCommunication(clientID, False) sim.simxReadProximitySensor(clientID, prox_handle[1], sim.simx_opmode_streaming) sim.simxGetObjectVelocity(clientID, detect_handle[1], sim.simx_opmode_streaming) y = 0 points = [] velocities = [] leave = 0 # enter while loop to read proximity sensor while (y == 0): # read prox sensor and get detected points ret, dS, dP, dOH, dSNV = sim.simxReadProximitySensor(clientID, prox_handle[1], sim.simx_opmode_buffer) ret, linear, angular = sim.simxGetObjectVelocity(clientID, detect_handle[1], sim.simx_opmode_buffer) # detecting if(dS == 1): # store all the detected points points.append(dP) velocities.append(linear) leave = 1 # not detecting and is heading away from wall elif(dS == 0 and leave == 1): y = 1 print("Last Ball Detection Coordinates: ", points[-1]) print("Last Ball Velocities: ", velocities[-1]) #Let's set the velocity of the ball ball_handle = sim.simxGetObjectHandle(clientID, 'Sphere', sim.simx_opmode_blocking) # sim.simxSetObjectPosition(clientID, ball_handle[1], -1, [-1, -1, 1], sim.simx_opmode_streaming) # sim.simxPauseCommunication(clientID, True) # sim.simxSetObjectFloatParameter(clientID, ball_handle[1], sim.sim_objfloatparam_abs_y_velocity, 3, sim.simx_opmode_streaming) # sim.simxSetObjectFloatParameter(clientID, ball_handle[1], sim.sim_objfloatparam_abs_z_velocity, 5, sim.simx_opmode_streaming) # sim.simxPauseCommunication(clientID, False) print("Joint 1 Handles ... ") jointHandles=[-1,-1,-1,-1,-1,-1] for i in range(6): jointHandles[i]=sim.simxGetObjectHandle(clientID, 'UR3_joint' + str(i+1)+'#', sim.simx_opmode_blocking) print(jointHandles[i]) print(" \n") base_frame = sim.simxGetObjectHandle(clientID, 'Dummy0', sim.simx_opmode_blocking) ee_frame = sim.simxGetObjectHandle(clientID, 'Dummy', sim.simx_opmode_blocking) print("Base Frame handle: ", base_frame) print("EE Frame handle: ", ee_frame) print(" \n") print("Joint 2 Handles ... ") jointHandles_2 = [-1, -1, -1, -1, -1, -1] for i in range(6): jointHandles_2[i]=sim.simxGetObjectHandle(clientID, 'UR3_joint' + str(i+1)+'#0', sim.simx_opmode_blocking) print(jointHandles_2[i]) print(" ") #Let's try getting the position and orientation of each of the joints: ####pos0 = sim.simxGetObjectPosition(clientID, jointHandles_2[0][1], base_frame[1], sim.simx_opmode_blocking) ####pos1 = sim.simxGetObjectPosition(clientID, jointHandles_2[0][1], base_frame[1], sim.simx_opmode_blocking) # # pos_b_ee = sim.simxGetObjectPosition(clientID, ee_frame[1], base_frame[1], sim.simx_opmode_blocking) # # #print(pos_b_ee[1]) # # ori_b_ee = sim.simxGetObjectOrientation(clientID, ee_frame[1], base_frame[1], sim.simx_opmode_blocking) # # #print(ori_b_ee) # # rot_m = R.from_euler('xyz', np.array(ori_b_ee[1])) # # #print(rot_m.as_dcm().shape) # # M = np.zeros((4,4)) # # M[3][3] = 1 # # M[0:3, 0:3] = rot_m.as_dcm() # # M[0:3, 3] = pos_b_ee[1] # # print("Homogeneous transformation Matrix: ") # # print(M) # # print(" ") # # ###ret_code, rot_matrix = sim.simxGetJointMatrix(clientID, jointHandles_2[5][1], sim.simx_opmode_blocking) # # ###Get the joint positions and orientations with respect to base frame # # np.set_printoptions(precision=3) # # w = np.array([[0,0,1], [-1,0,0], [-1,0,0], [-1,0,0], [0,0,1], [1,0,0]]) # # print("Angular Velocities: ") # # print(w, "\n") # # v = np.zeros((6,3)) # # ret_code = 0 # # for i in range(6): # # ret_code, q = sim.simxGetObjectPosition(clientID, jointHandles_2[i][1], base_frame[1], sim.simx_opmode_blocking) # # q = np.array(q) # # v[i,:] = np.cross(-1 * w[i,:], q) # # print("Linear Velocities: ") # # print(v, "\n") # # S = np.zeros((6,6)) # # S[:, 0:3] = w # # S[:, 3:6] = v # # S_t = S.transpose() # # print("Screw Matrix: ") # # print(S_t, "\n") # debugging # # #T = mr.FKinSpace(M, S_t, np.array([radians(90),radians(90),radians(-92),radians(233),radians(33),radians(24)])) #Fill the array with actual values later # # T = get_transform(M, S_t, np.zeros((6,)))#print(type(T)) # # print("New Transformation Matrix: ") # # print(T, "\n") # # old_pos = np.ones((4,1)) # # old_pos[0:3] = 0 # # old_pos.resize((4,1)) # # new_pose = T @ old_pos # # print("New Position: ") # # print(new_pose) # # new_pose.resize((4,)) #Set-up some of the RML vectors: vel=90 accel=20 jerk=40 currentVel=[0,0,0,0,0,0,0] currentAccel=[0,0,0,0,0,0,0] maxVel=[vel*math.pi/180,vel*math.pi/180,vel*math.pi/180,vel*math.pi/180,vel*math.pi/180,vel*math.pi/180] maxAccel=[accel*math.pi/180,accel*math.pi/180,accel*math.pi/180,accel*math.pi/180,accel*math.pi/180,accel*math.pi/180] maxJerk=[jerk*math.pi/180,jerk*math.pi/180,jerk*math.pi/180,jerk*math.pi/180,jerk*math.pi/180,jerk*math.pi/180] targetVel=[0,0,0,0,0,0] #I'm gonna try looking at the various ways in which the ping pong ball can hit #Right side: #Max(Theta2): 64.1, Max(Theta3): 84.1, Theta 5: -90, Theta 6: 90 #Left side: #Max(Theta2): -64.1, Max(Theta3): -84.1, Theta 5: 90, Theta 6: 90 # targetPos0 = [radians(0),radians(64.1),radians(0),radians(0),radians(-90),radians(90)] # sim.simxPauseCommunication(clientID, True) # for i in range(6): # #print(jointHandles[i]) # #print(targetPos0[i]) # sim.simxSetJointTargetPosition(clientID, jointHandles_2[i][1], targetPos0[i], sim.simx_opmode_streaming) # sim.simxSetJointTargetVelocity(clientID, jointHandles_2[i][1], targetVel[i], sim.simx_opmode_streaming) # sim.simxPauseCommunication(clientID, False) # time.sleep(1) # targetPos0 = [radians(10),radians(64.1),radians(0),radians(0),radians(-90),radians(90)] # sim.simxPauseCommunication(clientID, True) # for i in range(6): # #print(jointHandles[i]) # #print(targetPos0[i]) # sim.simxSetJointTargetPosition(clientID, jointHandles_2[i][1], targetPos0[i], sim.simx_opmode_streaming) # sim.simxSetJointTargetVelocity(clientID, jointHandles_2[i][1], targetVel[i], sim.simx_opmode_streaming) # sim.simxPauseCommunication(clientID, False) # time.sleep(1) sim.simxPauseCommunication(clientID, True) for i in range(6): #print(jointHandles[i]) #print(targetPos0[i]) sim.simxSetJointTargetPosition(clientID, jointHandles_2[i][1], 0, sim.simx_opmode_streaming) sim.simxSetJointTargetVelocity(clientID, jointHandles_2[i][1], targetVel[i], sim.simx_opmode_streaming) sim.simxPauseCommunication(clientID, False) time.sleep(2) # ##Now, let us set up the Position of our dummy to match the position of the end_effector # sim.simxSetObjectPosition(clientID, ee_frame[1], base_frame[1], new_pose[0:3], sim.simx_opmode_streaming) # ##Then, let's also setup the orientation, after converting them to euler angles # new_rot_mat = T[0:3,0:3] # new_rot = R.from_dcm(new_rot_mat) # new_ori_b_ee = new_rot.as_euler('xyz') # sim.simxSetObjectOrientation(clientID, ee_frame[1], base_frame[1], new_ori_b_ee, sim.simx_opmode_streaming print("\n", "Now trying inverse kinematics: ") # time.sleep(2) # _, ball_pos = sim.simxGetObjectPosition(clientID, ball_handle[1], -1, sim.simx_opmode_blocking) # _, ball_ori = sim.simxGetObjectOrientation(clientID, ball_handle[1], -1, sim.simx_opmode_blocking) # ball_rot = R.from_euler('xyz', ball_ori) # ball_rot_mat = ball_rot.as_dcm() # ball_pos[0] = ball_pos[0] # ball_pos[1] = ball_pos print("initial velocities: ", velocities[-1]) print("position from sensor: ", points[-1]) b_ball = BouncingBall() pred_pos = b_ball.trajectory(points[-1][0], points[-1][1], points[-1][2], velocities[-1]) _, prox_dist = sim.simxGetObjectPosition(clientID, prox_handle[1], -1, sim.simx_opmode_streaming) T_prox = np.array([[-1, 0, 0, 0.025], [0, -1, 0, 2.85], [0,0,1,.043], [0,0,0,1]]) prox_pos = np.array([[pred_pos[0]], [pred_pos[1]], [pred_pos[2]],[1]]) ball_pos = T_prox @ prox_pos # prox_pos = np.array([[-pred_pos[0]+0.025], [pred_pos[1]+2.85], [pred_pos[2]], [1]]) # ball_pos = prox_pos[:3] print("Predicted Position: ", pred_pos) print("Ball pred: ", ball_pos[:3]) #Offsets are for making sure that we can hit the ball world_coord = np.array([ball_pos[0,:], ball_pos[1,:], ball_pos[2,:]]) world_coord = np.abs(world_coord) guess_angles = ik.findJointAngles(world_coord[0]+.07, world_coord[1], world_coord[2]+0.1) targetPos0_ik = guess_angles if(ball_pos[0,:] < 0): targetPos0_ik[0] = -guess_angles[0] targetPos0_ik[1] = -guess_angles[1] targetPos0_ik[2] = -guess_angles[2] targetPos0_ik[3] = -guess_angles[3] targetPos0_ik[4] = radians(90) sim.simxPauseCommunication(clientID, True) for i in range(6): #print(jointHandles[i]) #print(targetPos0[i]) sim.simxSetJointTargetPosition(clientID, jointHandles_2[i][1], targetPos0_ik[i], sim.simx_opmode_streaming) sim.simxSetJointTargetVelocity(clientID, jointHandles_2[i][1], targetVel[i], sim.simx_opmode_streaming) sim.simxPauseCommunication(clientID, False) time.sleep(1) targetPos0_ik[0] = radians(degrees(targetPos0_ik[0] + radians(50))) sim.simxPauseCommunication(clientID, True) for i in range(6): #print(jointHandles[i]) #print(targetPos0[i]) sim.simxSetJointTargetPosition(clientID, jointHandles_2[i][1], targetPos0_ik[i], sim.simx_opmode_streaming) sim.simxSetJointTargetVelocity(clientID, jointHandles_2[i][1], targetVel[i], sim.simx_opmode_streaming) sim.simxPauseCommunication(clientID, False) time.sleep(2) # world_coord = np.array([-.5, .475, .043]) # world_coord = np.abs(world_coord) # guess_angles = ik.findJointAngles(world_coord[0]+.07, world_coord[1], world_coord[2]+0.1) # targetPos0_ik = guess_angles # if(ball_pos[0,:] > 0): # targetPos0_ik[0] = -guess_angles[0] # targetPos0_ik[1] = -guess_angles[1] # targetPos0_ik[2] = -guess_angles[2] # targetPos0_ik[3] = -guess_angles[3] # targetPos0_ik[4] = radians(90) # sim.simxPauseCommunication(clientID, True) # for i in range(6): # #print(jointHandles[i]) # #print(targetPos0[i]) # sim.simxSetJointTargetPosition(clientID, jointHandles_2[i][1], targetPos0_ik[i], sim.simx_opmode_streaming) # sim.simxSetJointTargetVelocity(clientID, jointHandles_2[i][1], targetVel[i], sim.simx_opmode_streaming) # sim.simxPauseCommunication(clientID, False) # time.sleep(2) # targetPos0_ik[0] = radians(degrees(targetPos0_ik[0] + 50)) # sim.simxPauseCommunication(clientID, True) # for i in range(6): # #print(jointHandles[i]) # #print(targetPos0[i]) # sim.simxSetJointTargetPosition(clientID, jointHandles_2[i][1], 0, sim.simx_opmode_streaming) # sim.simxSetJointTargetVelocity(clientID, jointHandles_2[i][1], targetVel[i], sim.simx_opmode_streaming) # sim.simxPauseCommunication(clientID, False) # time.sleep(2) # T_b = np.zeros((4,4)) # T_b[3,3] = 1 # T_b[0:3, 0:3] = ball_rot_mat # T_b[0:3, 3] = ball_pos # print("Ball Position: ", ball_pos) # print("Ball Rotation: ", ball_rot.as_dcm()) # #theta_list_guess = np.array([radians(-70), radians(-50), radians(-50), radians(-30), radians(50), radians(0)]) # theta_list_guess = np.array([radians(0),radians(64.1),radians(0),radians(0),radians(90),radians(90)]) # theta_list, success = mr.IKinSpace(S, M, T_b, theta_list_guess, 0.01, 0.01) # if success: # print(theta_list) # else: # print("Not successful, but here's the guess: \n", theta_list) #Now, let's check how close we are to the actual ball: # sim.simxPauseCommunication(clientID, True) # for i in range(6): # #print(jointHandles[i]) # #print(targetPos0[i]) # sim.simxSetJointTargetPosition(clientID, jointHandles_2[i][1], targetPos0_ik[i], sim.simx_opmode_streaming) # sim.simxSetJointTargetVelocity(clientID, jointHandles_2[i][1], targetVel[i], sim.simx_opmode_streaming) # sim.simxPauseCommunication(clientID, False) # time.sleep(2) #sim.simxSetObjectPosition(clientID, P_ball_handle[1], -1, [-1, -1, 1], sim.simx_opmode_streaming) # Before closing the connection to CoppeliaSim, make sure that the last command sent out had time to arrive. You can guarantee this with (for example): sim.simxGetPingTime(clientID) # Now close the connection to CoppeliaSim: sim.simxFinish(clientID) # sim.rmlMoveToJointPositions(jointHandles, -1, currentVel, currentAccel, maxVel, maxAccel, maxJerk, targetPos0, targetVel) # time.sleep(1) # targetPos1 = [radians(90),radians(90),radians(-92),radians(233),radians(33),radians(24)] # sim.simxPauseCommunication(clientID, True) # for i in range(6): # #print(jointHandles[i]) # #print(targetPos0[i]) # if(i==0): # sim.simxSetJointTargetPosition(clientID, jointHandles_2[i][1], targetPos1[i], sim.simx_opmode_streaming) # sim.simxSetJointTargetVelocity(clientID, jointHandles_2[i][1], targetVel[i], sim.simx_opmode_streaming) # else: # sim.simxSetJointTargetPosition(clientID, jointHandles_2[i][1], targetPos1[i], sim.simx_opmode_buffer) # sim.simxSetJointTargetVelocity(clientID, jointHandles_2[i][1], targetVel[i], sim.simx_opmode_buffer) # sim.simxPauseCommunication(clientID, False) # time.sleep(1) # # sim.rmlMoveToJointPositions(jointHandles,-1,currentVel,currentAccel,maxVel,maxAccel,maxJerk,targetPos1,targetVel) # time.sleep(1) # targetPos2 = [radians(90),radians(90),radians(-92),radians(233),radians(33),radians(24)] # sim.simxPauseCommunication(clientID, True) # for i in range(6): # #print(jointHandles[i]) # #print(targetPos0[i]) # if(i==0): # sim.simxSetJointTargetPosition(clientID, jointHandles[i][1], targetPos2[i], sim.simx_opmode_streaming) # sim.simxSetJointTargetVelocity(clientID, jointHandles[i][1], targetVel[i], sim.simx_opmode_streaming) # else: # sim.simxSetJointTargetPosition(clientID, jointHandles[i][1], targetPos2[i], sim.simx_opmode_buffer) # sim.simxSetJointTargetVelocity(clientID, jointHandles[i][1], targetVel[i], sim.simx_opmode_buffer) # sim.simxPauseCommunication(clientID, False) # # sim.rmlMoveToJointPositions(jointHandles,-1,currentVel,currentAccel,maxVel,maxAccel,maxJerk,targetPos2,targetVel) # time.sleep(1) # targetPos3=[0,0,0,0,0,0] # #targetPos2 = [radians(90),radians(90),radians(-92),radians(233),radians(33),radians(24)] # sim.simxPauseCommunication(clientID, True) # for i in range(6): # #print(jointHandles[i]) # #print(targetPos0[i]) # if(i==0): # sim.simxSetJointTargetPosition(clientID, jointHandles[i][1], targetPos3[i], sim.simx_opmode_streaming) # sim.simxSetJointTargetVelocity(clientID, jointHandles[i][1], targetVel[i], sim.simx_opmode_streaming) # else: # sim.simxSetJointTargetPosition(clientID, jointHandles[i][1], targetPos3[i], sim.simx_opmode_buffer) # sim.simxSetJointTargetVelocity(clientID, jointHandles[i][1], targetVel[i], sim.simx_opmode_buffer) # sim.simxPauseCommunication(clientID, False) # time.sleep(1) # # sim.rmlMoveToJointPositions(jointHandles,-1,currentVel,currentAccel,maxVel,maxAccel,maxJerk,targetPos3,targetVel) # # # Now retrieve streaming data (i.e. in a non-blocking fashion): # # startTime=time.time() # # sim.simxGetIntegerParameter(clientID,sim.sim_intparam_mouse_x,sim.simx_opmode_streaming) # Initialize streaming # # while time.time()-startTime < 5: # # returnCode,data=sim.simxGetIntegerParameter(clientID,sim.sim_intparam_mouse_x,sim.simx_opmode_buffer) # Try to retrieve the streamed data # # if returnCode==sim.simx_return_ok: # After initialization of streaming, it will take a few ms before the first value arrives, so check the return code # # print ('Mouse position x: ',data) # Mouse position x is actualized when the cursor is over CoppeliaSim's window # # time.sleep(0.005) # # Now send some data to CoppeliaSim in a non-blocking fashion: # sim.simxAddStatusbarMessage(clientID,'Hello CoppeliaSim!',sim.simx_opmode_oneshot) # #Let's try reading some vision sensor data # sensor_handle = sim.simxGetObjectHandle(clientID, 'Vision_sensor', sim.simx_opmode_blocking) # #img = sim.simxGetVisionSensorImage(clientID, sensor_handle[1], 0 , sim.simx_opmode_buffer) # #print(type(img)) # #print(img) # #cv2.imshow(img) # #return_code, detection_state, aux_packets = sim.simxReadVisionSensor(clientID, sensor_handle[1], sim.simx_opmode_buffer) # img = sim.simxGetVisionSensorImage(clientID, sensor_handle[1], 0, sim.simx_opmode_streaming) # print(img) # #print(return_code) # #print(detection_state) else: print ('Failed connecting to remote API server') print ('Program ended') #https://youtu.be/l0C5E4iqqRI # Video link #https://youtu.be/Qj7Sv0V9yec
7593bde6f1c6020cb25a96071a72d0e22e5097c4
[ "Markdown", "Python", "Lua" ]
8
Python
wish899/pinpongrobots
31ba237587590a7a3d01dc861309e1d665ffa171
3ee1c0b8f4e3a39638a7e04d6cf28a8677c9e1b1
refs/heads/master
<repo_name>DrewTAJ/wordpress-theme<file_sep>/single.php <?php // If comments are open or we have at least one comment, load up the comment template. get_header(); ?> <div class="container-fluid"> <div class="row"> <div class="col-sm-9"> <?php if( have_posts() ) : ?> <?php while(have_posts()) : the_post(); ?> <?php get_template_part( 'templates/content', 'single' ); ?> <?php if ( comments_open() || get_comments_number() ) : ?> <?php comments_template(); ?> <?php endif; ?> <div class="col-sm-9"> <button class="btn btn-default" type="button" data-toggle="collapse" data-target="#commentForm" aria-expanded="false" aria-controls="commentForm"> <span class="glyphicon glyphicon-plus"></span> Add Comment </button> </div> <div class="collapse col-sm-9 post" id="commentForm"> <?php comment_form(); ?> </div> <?php endwhile; ?> <?php endif; ?> </div> <?php get_template_part('inc/content','sidebar'); ?> </div> </div> <?php get_footer(); ?><file_sep>/sidebar.php <?php if ( has_nav_menu( 'primary' ) || has_nav_menu( 'social' ) || is_active_sidebar( 'sidebar-1' ) ) : ?> <div id="sidebar"> </div> <?php endif; ?><file_sep>/index.php <?php get_header(); ?> <div class="container-fluid"> <div class="row"> <div class="col-md-9"> <?php if( have_posts() ) : ?> <?php while(have_posts()) : the_post(); ?> <?php get_template_part( 'templates/content', get_post_format() ); ?> <?php endwhile; ?> <?php endif; ?> </div> <?php get_template_part('inc/content','sidebar'); ?> </div> </div> <?php get_footer(); ?><file_sep>/templates/content.php <?php $archive_year = get_the_time('Y'); $archive_month = get_the_time('m'); $archive_day = get_the_time('d'); ?> <div class="row"> <section id="post-<?php the_ID(); ?>" class="col-sm-12 post"> <header class="post-header" id="header"> <div class="col-xs-6"> <time><a href="<?php echo get_day_link($archive_year, $archive_month, $archive_day); ?>"> <span class="glyphicon glyphicon-calendar"></span> <?php the_date('F, j, Y'); ?> </a></time> </div> <div class="col-xs-6 text-right"> <span><?php edit_post_link("<span class='glyphicon glyphicon-edit'></span> Edit"); ?></span> </div> </header> <div class="post-content"> <div class="content_header"> <h2 class="post_title"><?php the_title(); ?></h2> </div> <div><?php the_content(); ?></div> </div> <footer class="post-footer" id="footer"> <a href=" <?php comments_link(); ?> " class="col-xs-6"><span class="glyphicon glyphicon-comment"></span> <?php comments_number("0 Comments", "1 Comment", "% Comments"); ?></a> <a href="#" class="col-xs-6 text-right"><span class="glyphicon glyphicon-new-window"></span> Share</a> </footer> </section> </div><file_sep>/functions.php <?php function add_theme_styles() { //echo get_template_directory_uri(); // wp_register_style( 'style', get_stylesheet_uri()); // wp_register_style( 'bootstrap.min', get_template_directory_uri() . '/styles/bootstrap.min.css'); // wp_register_style( 'bootstrap-theme.min', get_template_directory_uri() . '/styles/bootstrap-theme.min.css'); // wp_register_style( 'index', get_template_directory_uri() . '/styles/index.css'); wp_enqueue_style( 'style', get_stylesheet_uri() ); wp_enqueue_style( 'bootstrap', get_template_directory_uri() . '/styles/bootstrap.min.css'); wp_enqueue_style( 'bootstrap-theme', get_template_directory_uri() . '/styles/bootstrap-theme.min.css', array('bootstrap')); wp_enqueue_style( 'index', get_template_directory_uri() . '/styles/index.css'); wp_enqueue_script('jquery',get_template_directory_uri().'/scripts/jquery-1.12.2.min.js'); wp_enqueue_script('bootstrap-script',get_template_directory_uri() . '/scripts/bootstrap.min.js'); wp_enqueue_script( 'comment-reply' ); wp_enqueue_script('index-script',get_template_directory_uri() . '/scripts/index.js',array('style')); } add_action( 'wp_enqueue_scripts',add_theme_styles ); //add_action( 'wp_enqueue_scripts', add_theme_scripts ); ?><file_sep>/README.md ### A wordpress theme This is a wordpress theme I created using PHP, CSS, Javascript and Bootstrap.<file_sep>/header.php <!DOCTYPE html> <html <?php language_attributes(); ?> class="no-js"> <head> <meta charset="<?php bloginfo( 'charset' ); ?>"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- <link href="styles/bootstrap.min.css" rel="stylesheet" /> --> <!--<link href="styles/bootstap-theme.min.css" rel="stylesheet" /> <link href="styles/index.css" rel="stylesheet" /> <link href="style.css" rel="stylesheet" />--> <?php if ( is_singular() && pings_open( get_queried_object() ) ) : ?> <link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>"> <?php endif; ?> <?php wp_head(); ?> </head> <body <?php body_class(); ?>> <div id="container"> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="<?php bloginfo('url'); ?>">Home</a></li> <li><a href="<?php bloginfo('url'); ?>/archive">Archive</a></li> <li><a href="#">About</a></li> <li><a href="#">Contact</a></li> </ul> </div> </div> </nav> <file_sep>/footer.php <nav class="navbar navbar-default navbar-static-bottom text-left" id="footer"> <div class="container text-left navbar-left"> <p class="navbar-text">Created By <NAME></p> </div> </nav> </div> <!--<script type="text/javascript" src="scripts/bootstrap.min.js"></script> <script type="text/javascript" src="scripts/index.js"></script>--> <?php wp_footer(); ?> </body> </html><file_sep>/inc/content-sidebar.php <div id="sidebar" class="hidden-xs col-sm-3"> <div class="sidebar-container container-fluid"> <div id="sidebar-header"> <h2 class="text-center"><a href="<?php bloginfo('url'); ?>"><?php bloginfo("name"); ?></a></h2> </div> <div class="sidebar-description"> <p><?php bloginfo("description"); ?></p> </div> <div class="sidebar-about"> </div> <?php get_sidebar(); ?> </div> </div><file_sep>/comments.php <div id="comments" class="comments-container"> <?php if(have_comments()): ?> <div class="col-sm-12"> <?php the_comments_navigation(); ?> <ol id="comments-list"> <?php wp_list_comments(array( 'style' => 'ol', 'short_ping' => true, 'avatar_size' => 42, ) ); ?> </ol> <?php the_comments_navigation(); ?> </div> <?php endif; ?> </div>
9bb89c7e62dde9752ef6797d8394b6d0e4b75397
[ "Markdown", "PHP" ]
10
PHP
DrewTAJ/wordpress-theme
cdd8777a352b1cbb6262ed23c226b550b36b50f8
e727c73483309473b6ffd1c65beea66fd356058d
refs/heads/master
<repo_name>dgusaas/pthread<file_sep>/fib.c #include <stdio.h> #include <stdlib.h> #include <pthread.h> struct args_s { int n; int result; }; void *iterative_fib(void *ptr); void *recursive_fib(void *ptr); int main(int argc, char *argv[]) { pthread_t thread1; struct args_s args; long status; args.n = atoi(argv[1]); if (status = pthread_create(&thread1, NULL, iterative_fib, (void *)&args)) { fprintf(stderr, "Error: pthread_create returned: %ld\n", status); exit(EXIT_FAILURE); } pthread_join(thread1, (void *)status); printf("Fib of %d: %d\n", args.n, args.result); exit(EXIT_SUCCESS); } // using a tail-recursive function with pthreads may be very memory intensive // http://stackoverflow.com/questions/5086040/recursive-fib-with-threads-segmentation-fault void *iterative_fib(void *ptr) { struct args_s *args = ptr; if (args->n == 0 || args->n == 1) { args->result = args->n; } int s1 = 0, s2 = 1, n = args->n; int tmp; while (--n > 0) { tmp = s1 + s2; s1 = s2; s2 = tmp; } args->result = tmp; pthread_exit(EXIT_SUCCESS); } void *recursive_fib(void *ptr) { struct args_s *args = ptr; pthread_exit(EXIT_SUCCESS); }
9232fb1d329cf9fc04abcd75027b24233af38191
[ "C" ]
1
C
dgusaas/pthread
2504988fbe8acb51c91f50d59742db11b012a860
fe25b3afcd09ec4e6b40e38bd2d17ae3fad88562
refs/heads/master
<repo_name>weizai118/receiver-meow<file_sep>/qqpet/qqpet/Program.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Xml.Linq; namespace qqpet { class Program { static void Main(string[] args) { try { while (true) { //if(DateTime.Now.Minute%5 == 0 && DateTime.Now.Second == 0) //{ Console.WriteLine("开始时间:" + DateTime.Now); XElement uin = XElement.Load(path + "11.xml"); foreach (XElement mm in uin.Elements("msginfo")) { if (mm.Element("msg").Value == "初始问题") continue; Console.WriteLine("-------------------\r\n当前账号:" + mm.Element("msg").Value); AutoFeed(mm.Element("ans").Value, replay_get(12, mm.Element("msg").Value), mm.Element("msg").Value); } Console.WriteLine("定时程序执行结束:" + DateTime.Now + "\r\n==========================================="); //} //Console.WriteLine("not run,"+ DateTime.Now.Minute + "," + DateTime.Now.Second); System.Threading.Thread.Sleep(10000); } } catch(Exception e) { Console.WriteLine(e.ToString()); Console.ReadLine(); } } static string path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase; public static string replay_get(long group, string msg) { XElement root = XElement.Load(path + group + ".xml"); string[] replay_str = new string[50]; int count = 0; Random ran = new Random(System.DateTime.Now.Millisecond); int RandKey; string ansall = ""; foreach (XElement mm in root.Elements("msginfo")) { if (msg.IndexOf(mm.Element("msg").Value) != -1 && count < 50) { replay_str[count] = mm.Element("ans").Value; count++; } } if (count != 0) { RandKey = ran.Next(0, count); ansall = replay_str[RandKey]; } return ansall; } public static void del(long group, string msg) { dircheck(group); string gg = group.ToString(); XElement root = XElement.Load(path + group + ".xml"); var element = from ee in root.Elements() where (string)ee.Element("msg") == msg select ee; if (element.Count() > 0) { //element.First().Remove(); element.Remove(); } root.Save(path + group + ".xml"); } public static void insert(long group, string msg, string ans) { if (msg.IndexOf("\r\n") < 0 & msg != "") { dircheck(group); XElement root = XElement.Load(path + group + ".xml"); XElement read = root.Element("msginfo"); read.AddBeforeSelf(new XElement("msginfo", //new XElement("group", group), new XElement("msg", msg), new XElement("ans", ans) )); root.Save(path + group + ".xml"); } } public static void createxml(long group) { XElement root = new XElement("Categories", new XElement("msginfo", //new XElement("group", 123), new XElement("msg", "初始问题"), new XElement("ans", "初始回答") ) ); root.Save(path + group + ".xml"); } public static void dircheck(long group) { if (File.Exists(path + group + ".xml")) { //MessageBox.Show("存在文件"); //File.Delete(dddd);//删除该文件 } else { //MessageBox.Show("不存在文件"); createxml(group);//创建该文件,如果路径文件夹不存在,则报错。 } } public static string pleaseLogin = "请设置登陆信息!"; public static string petMore = "更多宠物命令请回复“宠物助手”"; public static void AutoFeed(string uin, string skey, string qq) { string state = GetPetState(uin, skey); int growNow = 0, growMax = 0, cleanNow = 0, cleanMax = 0, level = 0; try { growNow = int.Parse(Reg_get(state, "饥饿值:(?<w>\\d+)/", "w")); growMax = int.Parse(Reg_get(state, "饥饿值:\\d+/(?<w>\\d+)", "w")); cleanNow = int.Parse(Reg_get(state, "清洁值:(?<w>\\d+)/", "w")); cleanMax = int.Parse(Reg_get(state, "清洁值:\\d+/(?<w>\\d+)", "w")); level = int.Parse(Reg_get(state, "等级:(?<w>\\d+)", "w")); } catch { } if (level == 0) { int failCount = 0; try { failCount = int.Parse(replay_get(14, qq.ToString())); } catch { } failCount++; del(14, qq.ToString()); insert(14, qq.ToString(), failCount.ToString()); Console.WriteLine($"连续失败{failCount}次"); return; } else { del(14, qq.ToString()); insert(14, qq.ToString(), "0"); } Console.WriteLine($"饥饿值:{growNow}/{growMax},清洁值:{cleanNow}/{cleanMax}"); if (growMax - growNow > 1500) { string grow = FeedPetSelect(uin, skey, "1"); string goodid = Reg_get(grow, "物品id:(?<w>\\d+)", "w"); if (goodid == "") { HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/phone_pet", "cmd=3&feed=5&goodid=5629937620877313", uin, skey); goodid = "5629937620877313"; Console.WriteLine($"购买了物品{goodid},进行饥饿值补充"); } else { Console.WriteLine($"选取了物品{goodid},进行饥饿值补充"); } UsePet(uin, skey, goodid); } if (cleanMax - cleanNow > 1500) { string grow = WashPetSelect(uin, skey, "1"); string goodid = Reg_get(grow, "物品id:(?<w>\\d+)", "w"); if(goodid == "") { HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/phone_pet", "cmd=3&feed=5&goodid=3378137807192066", uin, skey); goodid = "3378137807192066"; Console.WriteLine($"购买了物品{goodid},进行清洁值值补充"); } else { Console.WriteLine($"选取了物品{goodid},进行清洁值值补充"); } UsePet(uin, skey, goodid); } if(HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/farm", "cmd=10", uin, skey).IndexOf("一键收获") == -1) { Console.WriteLine("开始播种植物"); if (level >= 20) while (HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/farm", "cmd=10&prc=81&seedid=14&subcmd=5&sname=s8jX0w", uin, skey).IndexOf("系统繁忙") != -1); if (level >= 18) while (HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/farm", "cmd=10&prc=57&seedid=13&subcmd=12&sname=z*O9tg", uin, skey).IndexOf("系统繁忙") != -1) ; if (level >= 14) while (HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/farm", "cmd=10&prc=34&seedid=11&subcmd=12&sname=st3drg", uin, skey).IndexOf("系统繁忙") != -1) ; if (level >= 12) while (HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/farm", "cmd=10&prc=24&seedid=10&subcmd=12&sname=xru5*w", uin, skey).IndexOf("系统繁忙") != -1) ; if (level >= 10) while (HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/farm", "cmd=10&prc=24&seedid=9&subcmd=5&sname=xM*5zw", uin, skey).IndexOf("系统繁忙") != -1) ; if (level >= 5) while (HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/farm", "cmd=10&prc=14&seedid=6&subcmd=5&sname=t6zH0Q", uin, skey).IndexOf("系统繁忙") != -1) ; if (level >= 4) while (HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/farm", "cmd=10&prc=12&seedid=5&subcmd=12&sname=x9HX0w", uin, skey).IndexOf("系统繁忙") != -1) ; if (level >= 1) while (HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/farm", "cmd=10&prc=4&seedid=1&subcmd=12&sname=xMGy3Q", uin, skey).IndexOf("系统繁忙") != -1) ; Console.WriteLine("植物播种完成"); } else { Console.WriteLine("尝试收获植物"); HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/farm", "cmd=10&subcmd=10", uin, skey); } if (HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/fish", "cmd=11", uin, skey).IndexOf("一键收获") == -1) { Console.WriteLine("开始投放鱼苗"); if (level >= 55) while (HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/fish", "cmd=11&fish_sub=12&fryid=32&prc=140&sname=sNTN9dPj", uin, skey).IndexOf("系统繁忙") != -1); if (level >= 50) while (HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/fish", "cmd=11&fish_sub=12&fryid=31&prc=120&sname=zuXJq9Pj", uin, skey).IndexOf("系统繁忙") != -1); if (level >= 34) while (HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/fish", "cmd=11&fish_sub=12&fryid=23&prc=81&sname=tPPA9rrszrLT4w", uin, skey).IndexOf("系统繁忙") != -1); if (level >= 32) while (HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/fish", "cmd=11&fish_sub=12&fryid=28&prc=73&sname=wt66utPj", uin, skey).IndexOf("系统繁忙") != -1); if (level >= 30) while (HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/fish", "cmd=11&fish_sub=12&fryid=21&prc=65&sname=y-PT4w", uin, skey).IndexOf("系统繁忙") != -1); if (level >= 25) while (HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/fish", "cmd=11&fish_sub=12&fryid=20&prc=63&sname=0KHB*s*6", uin, skey).IndexOf("系统繁忙") != -1); if (level >= 16) while (HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/fish", "cmd=11&fish_sub=12&fryid=16&prc=32&sname=yq*w39Pj", uin, skey).IndexOf("系统繁忙") != -1); if (level >= 14) while (HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/fish", "cmd=11&fish_sub=12&fryid=11&prc=40&sname=u6LGpNPj", uin, skey).IndexOf("系统繁忙") != -1); if (level >= 12) while (HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/fish", "cmd=11&fish_sub=12&fryid=15&prc=27&sname=vaPT4w", uin, skey).IndexOf("系统繁忙") != -1); if (level >= 4) while (HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/fish", "cmd=11&fish_sub=12&fryid=5&prc=8&sname=tMzQ6-bz0*M", uin, skey).IndexOf("系统繁忙") != -1); if (level >= 2) while (HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/fish", "cmd=11&fish_sub=12&fryid=1&prc=4&sname=x**1ttPj", uin, skey).IndexOf("系统繁忙") != -1); Console.WriteLine("鱼苗投放完成"); } else { Console.WriteLine("尝试收获鱼苗"); HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/fish", "cmd=11&fish_sub=10&fryid=1", uin, skey); } if (Reg_get(state, "状态:(?<w>..)", "w") == "空闲") { bool can_study = false; int c = 1; try { c = int.Parse(replay_get(13, qq)); } catch { } if(c < 28) { if (c == 0) c = 1; Console.WriteLine($"宠物状态发现为空闲,从第{c}课开始尝试"); for (int i = c; i <= 27; i++) { int r = 4; while (r == 4) { r = StudyPet(uin, skey, i.ToString()); //Console.WriteLine($"正在尝试,返回值为{r}"); } if(r == 1 || r == 3) { can_study = true; Console.WriteLine($"宠物已开始学习{i}课"); //del(13, qq); //insert(13, qq, i.ToString()); break; } else if(r == 2) { Console.WriteLine($"无法上{i}课,尝试下一课"); } else if(r == 5) { Console.WriteLine($"请求被拦截,下次再试"); break; } } } if(!can_study) { Console.WriteLine($"发现没课能上了,去旅游"); HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/phone_pet", "g_f=0&cmd=7&tour=4", uin, skey); } } } /// <summary> /// 获取宠物基本信息 /// </summary> /// <param name="uin"></param> /// <param name="skey"></param> /// <returns></returns> public static string GetPetState(string uin, string skey) { string result = ""; string html = HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/phone_pet", "", uin, skey); html = html.Replace("\r", ""); html = html.Replace("\n", ""); if (html.IndexOf("手机统一登录") != -1) return pleaseLogin; result += Reg_get(html, "alt=\"QQ宠物\"/></p><p>(?<say>.*?)<", "say").Replace(" ", "") + "\r\n" + "宠物名:" + Reg_get(html, "昵称:(?<level>.*?)<", "level").Replace(" ", "") + "\r\n" + "等级:" + Reg_get(html, "等级:(?<level>.*?)<", "level").Replace(" ", "") + "\r\n" + "状态:" + Reg_get(html, "状态:(?<now>.*?)<", "now").Replace(" ", "") + "\r\n" + "成长值:" + Reg_get(html, "成长值:(?<now>.*?)<", "now").Replace(" ", "") + "\r\n" + "饥饿值:" + Reg_get(html, "饥饿值:(?<now>.*?)<", "now").Replace(" ", "") + "\r\n" + "清洁值:" + Reg_get(html, "清洁值:(?<now>.*?)<", "now").Replace(" ", "") + "\r\n" + "心情:" + Reg_get(html, "心情:(?<now>.*?)<", "now").Replace(" ", "") + "\r\n" + petMore; return result; } /// <summary> /// 获取宠物详细信息 /// </summary> /// <param name="uin"></param> /// <param name="skey"></param> /// <returns></returns> public static string GetPetMore(string uin, string skey) { string result = ""; string html = HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/phone_pet", "cmd=2", uin, skey); html = html.Replace("\r", ""); html = html.Replace("\n", ""); if (html.IndexOf("手机统一登录") != -1) return pleaseLogin; result += "主人昵称:" + Reg_get(html, "主人昵称:(?<name>.*?)&nbsp;", "name").Replace(" ", "") + "\r\n" + "宠物性别:" + Reg_get(html, "宠物性别:(?<level>.*?)<", "level").Replace(" ", "") + "\r\n" + "生日:" + Reg_get(html, "生日:(?<now>.*?)<", "now").Replace(" ", "") + "\r\n" + "等级:" + Reg_get(html, "等级:(?<now>.*?)<", "now").Replace(" ", "") + "\r\n" + "年龄:" + Reg_get(html, "年龄:(?<now>.*?)<", "now").Replace(" ", "") + "\r\n" + "代数:" + Reg_get(html, "代数:(?<now>.*?)<", "now").Replace(" ", "") + "\r\n" + "成长值:" + Reg_get(html, "成长值:(?<now>.*?)<", "now").Replace(" ", "") + "\r\n" + "武力值:" + Reg_get(html, "武力值:(?<now>.*?)<", "now").Replace(" ", "") + "\r\n" + "智力值:" + Reg_get(html, "智力值:(?<now>.*?)<", "now").Replace(" ", "") + "\r\n" + "魅力值:" + Reg_get(html, "魅力值:(?<now>.*?)<", "now").Replace(" ", "") + "\r\n" + "活跃度:" + Reg_get(html, "活跃度:(?<now>.*?)<", "now").Replace(" ", "") + "\r\n" + "配偶:" + Reg_get(html, "配偶:(?<now>.*?)<", "now").Replace(" ", "") + "\r\n" + petMore; return result; } /// <summary> /// 喂养宠物选择页面 /// </summary> /// <param name="uin"></param> /// <param name="skey"></param> /// <returns></returns> public static string FeedPetSelect(string uin, string skey,string page) { string result = ""; string html = HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/phone_pet", "cmd=3&page=" + page, uin, skey); html = html.Replace("\r", ""); html = html.Replace("\n", ""); if (html.IndexOf("手机统一登录") != -1) return pleaseLogin; result += "我的账户:" + Reg_get(html, "我的账户:(?<name>.*?)<", "name").Replace(" ", "") + "\r\n"; int i = 0; MatchCollection matchs = Reg_solve(Reg_get(html, "元宝(?<name>.*?)上页", "name").Replace(" ", ""), "<p>(?<name>.*?)<br"); string[] name = new string[matchs.Count]; string[] id = new string[matchs.Count]; foreach (Match item in matchs) { if (item.Success) { name[i++] += item.Groups["name"].Value; } } i = 0; matchs = Reg_solve(Reg_get(html, "元宝(?<name>.*?)上页", "name").Replace(" ", ""), "goodid=(?<id>.*?)\""); foreach (Match item in matchs) { if (item.Success) { id[i++] += "物品id:" + item.Groups["id"].Value; } } for(int j = 0; j < i;j++) { result += name[j] + "\r\n" + id[j] + "\r\n"; } if(Reg_get(html, "上页</a>(?<name>.*?)/", "name").Replace(" ", "") != "") { result += "第" + Reg_get(html, "上页</a>(?<name>.*?)/", "name").Replace(" ", "") + "页,共" + Reg_get(html, "上页</a>(.*?)/(?<name>\\d+)", "name").Replace(" ", "") + "页" + "\r\n"; } else { result += "第" + Reg_get(html, "上页(?<name>.*?)/", "name").Replace(" ", "") + "页,共" + Reg_get(html, "上页(.*?)/(?<name>\\d+)", "name").Replace(" ", "") + "页" + "\r\n"; } return result + petMore; } /// <summary> /// 清洁宠物选择页面 /// </summary> /// <param name="uin"></param> /// <param name="skey"></param> /// <returns></returns> public static string WashPetSelect(string uin, string skey, string page) { string result = ""; string html = HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/phone_pet", "cmd=3&page=" + page + "&eatwash=1", uin, skey); html = html.Replace("\r", ""); html = html.Replace("\n", ""); if (html.IndexOf("手机统一登录") != -1) return pleaseLogin; result += "我的账户:" + Reg_get(html, "我的账户:(?<name>.*?)<", "name").Replace(" ", "") + "\r\n"; int i = 0; MatchCollection matchs = Reg_solve(Reg_get(html, "元宝(?<name>.*?)上页", "name").Replace(" ", ""), "<p>(?<name>.*?)<br"); string[] name = new string[matchs.Count]; string[] id = new string[matchs.Count]; foreach (Match item in matchs) { if (item.Success) { name[i++] += item.Groups["name"].Value; } } i = 0; matchs = Reg_solve(Reg_get(html, "元宝(?<name>.*?)上页", "name").Replace(" ", ""), "goodid=(?<id>.*?)\""); foreach (Match item in matchs) { if (item.Success) { id[i++] += "物品id:" + item.Groups["id"].Value; } } for (int j = 0; j < i; j++) { result += name[j] + "\r\n" + id[j] + "\r\n"; } if (Reg_get(html, "上页</a>(?<name>.*?)/", "name").Replace(" ", "") != "") { result += "第" + Reg_get(html, "上页</a>(?<name>.*?)/", "name").Replace(" ", "") + "页,共" + Reg_get(html, "上页</a>(.*?)/(?<name>\\d+)", "name").Replace(" ", "") + "页" + "\r\n"; } else { result += "第" + Reg_get(html, "上页(?<name>.*?)/", "name").Replace(" ", "") + "页,共" + Reg_get(html, "上页(.*?)/(?<name>\\d+)", "name").Replace(" ", "") + "页" + "\r\n"; } return result + petMore; } /// <summary> /// 治疗宠物选择页面 /// </summary> /// <param name="uin"></param> /// <param name="skey"></param> /// <returns></returns> public static string CurePetSelect(string uin, string skey, string page) { string result = ""; string html = HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/phone_pet", "cmd=3&page=" + page + "&eatwash=2", uin, skey); html = html.Replace("\r", ""); html = html.Replace("\n", ""); if (html.IndexOf("手机统一登录") != -1) return pleaseLogin; result += "我的账户:" + Reg_get(html, "我的账户:(?<name>.*?)<", "name").Replace(" ", "") + "\r\n"; int i = 0; MatchCollection matchs = Reg_solve(Reg_get(html, "元宝(?<name>.*?)上页", "name").Replace(" ", ""), "<p>(?<name>.*?)<br"); string[] name = new string[matchs.Count]; string[] id = new string[matchs.Count]; foreach (Match item in matchs) { if (item.Success) { name[i++] += item.Groups["name"].Value; } } i = 0; matchs = Reg_solve(Reg_get(html, "元宝(?<name>.*?)上页", "name").Replace(" ", ""), "goodid=(?<id>.*?)\""); foreach (Match item in matchs) { if (item.Success) { id[i++] += "物品id:" + item.Groups["id"].Value; } } for (int j = 0; j < i; j++) { result += name[j] + "\r\n" + id[j] + "\r\n"; } if (Reg_get(html, "上页</a>(?<name>.*?)/", "name").Replace(" ", "") != "") { result += "第" + Reg_get(html, "上页</a>(?<name>.*?)/", "name").Replace(" ", "") + "页,共" + Reg_get(html, "上页</a>(.*?)/(?<name>\\d+)", "name").Replace(" ", "") + "页" + "\r\n"; } else { result += "第" + Reg_get(html, "上页(?<name>.*?)/", "name").Replace(" ", "") + "页,共" + Reg_get(html, "上页(.*?)/(?<name>\\d+)", "name").Replace(" ", "") + "页" + "\r\n"; } return result + petMore; } /// <summary> /// 使用宠物物品 /// </summary> /// <param name="uin"></param> /// <param name="skey"></param> /// <returns></returns> public static string UsePet(string uin, string skey, string goodid) { string result = ""; string html = HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/phone_pet", "cmd=3&feed=3&goodid=" + goodid, uin, skey); html = html.Replace("\r", ""); html = html.Replace("\n", ""); if (html.IndexOf("手机统一登录") != -1) return pleaseLogin; if (html.IndexOf("不合法") != -1) return "你没有这个东西,使用失败\r\n" + petMore; result += "物品使用结果:\r\n" + Reg_get(html, "值:(?<name>.*?)<br", "name").Replace(" ", "").Replace("</b>", "") + "\r\n" + petMore; return result; } /// <summary> /// 宠物学习选择页面 /// </summary> /// <param name="uin"></param> /// <param name="skey"></param> /// <returns></returns> public static string StudyPetSelect() { return "课程id:\r\n小学体育:1\r\n小学劳技:2\r\n小学武术:5\r\n小学语文:4\r\n小学数学:5\r\n小学政治:6\r\n小学美术:7\r\n小学音乐:8\r\n小学礼仪:9\r\n\r\n中学体育:10\r\n中学劳技:11\r\n中学武术:12\r\n中学语文:13\r\n中学数学:14\r\n中学政治:15\r\n中学美术:16\r\n中学音乐:17\r\n中学礼仪:18\r\n\r\n大学体育:19\r\n大学劳技:20\r\n大学武术:21\r\n大学语文:22\r\n大学数学:23\r\n大学政治:24\r\n大学美术:25\r\n大学音乐:26\r\n大学礼仪:27\r\n" + petMore; } /// <summary> /// 学习宠物课程 /// </summary> /// <param name="uin"></param> /// <param name="skey"></param> /// <returns></returns> public static int StudyPet(string uin, string skey, string classid) { string html = HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/phone_pet", "cmd=5&courseid=" + classid + "&study=2", uin, skey); html = html.Replace("\r", ""); html = html.Replace("\n", ""); if (html.IndexOf("手机统一登录") != -1) return 0; if (html.IndexOf("亲爱的") != -1 && html.IndexOf("很抱歉") == -1) { //上课成功 return 1; } else if (html.IndexOf("您已经完成了") != -1 || html.IndexOf("很抱歉") != -1) { //已经上过这个课了 return 2; } else if (html.IndexOf("你的宠物") != -1) { //正在上课 return 3; } else if (html.IndexOf("不合法") != -1) { //不合法 return 5; } else { //获取失败 return 4; } //return "课程学习结果:\r\n" + result + petMore; } /// <summary> /// 直接获取正则表达式的最后一组匹配值 /// </summary> /// <param name="str"></param> /// <param name="regstr"></param> /// <param name="name"></param> /// <returns></returns> public static string Reg_get(string str, string regstr, string name) { string result = ""; MatchCollection matchs = Reg_solve(str, regstr); foreach (Match item in matchs) { if (item.Success) { result = item.Groups[name].Value; } } return result; } public static MatchCollection Reg_solve(string str, string regstr) { Regex reg = new Regex(regstr, RegexOptions.IgnoreCase); return reg.Matches(str); } /// <summary> /// GET 请求与获取结果 /// </summary> public static string HttpGetPet(string Url, string postDataStr, string uin, string skey) { try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr); request.Method = "GET"; request.ContentType = "text/html;charset=UTF-8"; request.Headers.Add("cookie", "uin=" + uin + "; skey=" + skey); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); return retString; } catch { } return ""; } } } <file_sep>/Newbe.Mahua.Receiver.Meow/Newbe.Mahua.Receiver.Meow/MahuaApis/MinecraftSolve.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Newbe.Mahua.Receiver.Meow.MahuaApis { class MinecraftSolve { //命令文件位置 private static string codeFile = @"D:\server1.12\plugins\CommandCode\Codes.yml"; /// <summary> /// 新增命令 /// </summary> /// <param name="player"></param> private static string AddNewCode(string player) { string result = Tools.GetRandomString(40, true, false, false, false, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"); //在将文本写入文件前,处理文本行 //StreamWriter一个参数默认覆盖 //StreamWriter第二个参数为false覆盖现有文件,为true则把文本追加到文件末尾 using (System.IO.StreamWriter file = new System.IO.StreamWriter(codeFile, true)) { file.WriteLine(result + ": /manuadd " + player + " builder world");// 直接追加文件末尾,换行 } return result; } /// <summary> /// 删除白名单命令 /// </summary> /// <param name="player"></param> public static string DelNewCode(string player) { string result = Tools.GetRandomString(40, true, false, false, false, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"); //在将文本写入文件前,处理文本行 //StreamWriter一个参数默认覆盖 //StreamWriter第二个参数为false覆盖现有文件,为true则把文本追加到文件末尾 using (System.IO.StreamWriter file = new System.IO.StreamWriter(codeFile, true)) { file.WriteLine(result + ": /manudel " + player);// 直接追加文件末尾,换行 } return result; } /// <summary> /// 处理玩家群消息 /// </summary> /// <param name="qq"></param> /// <param name="msg"></param> /// <param name="_mahuaApi"></param> /// <returns></returns> public static string SolvePlayer(string qq,string msg, IMahuaApi _mahuaApi) { bool wait = true; string player = XmlSolve.xml_get("bind_qq_wait", qq); if(player == "") { player = XmlSolve.xml_get("bind_qq", qq); wait = false; } if(player == "") { if(msg.IndexOf("绑定") != 0) { return Tools.At(qq) + "检测到你还没有绑定游戏账号,请发送“绑定”加自己的游戏id来绑定账号"; } else { if (!CheckID(msg.Replace("绑定", ""))) { return Tools.At(qq) + "你绑定的id为“" + msg.Replace("绑定", "") + "”,不符合规范,请换一个id绑定"; } else { XmlSolve.insert("bind_qq_wait", qq, msg.Replace("绑定", "")); _mahuaApi.SendGroupMessage("567145439", "接待喵糖拌管理:\r\n玩家id:" + msg.Replace("绑定", "") + "\r\n已成功绑定QQ:" + qq + "\r\n请及时检查该玩家是否已经提交白名单申请https://wj.qq.com/mine.html" + "\r\n如果符合要求,请回复“通过”+qq来给予白名单" + "\r\n如果不符合要求,请回复“不通过”+qq+空格+原因来给打回去重填"); return Tools.At(qq) + "绑定id:" + msg.Replace("绑定", "") + "成功!" + "\r\n请耐心等待管理员审核白名单申请哟~" + "\r\n如未申请请打开此链接:https://wj.qq.com/s/1308067/143c" + "\r\n如果过去24小时仍未被审核,请回复“催促审核”来进行催促"; } } } else //绑定过的情况下 { if(msg == "激活") { if(wait) { return Tools.At(qq) + "你还没通过审核呢,想什么呢"; } else { return Tools.At(qq) + "请在服务器输入命令/code " + AddNewCode(player) + "来激活本账号\r\n" + "命令只能使用一次,请尽快使用,失效可重新获取"; } } else if(msg=="催促审核") { if (wait) { return Tools.At(qq) + "你还不如直接at管理员呢,自己去问吧"; } else { return Tools.At(qq) + "你已经有权限了,发送“激活”来获取权限吧"; } } } return ""; } /// <summary> /// 处理管理群消息 /// </summary> /// <param name="qq"></param> /// <param name="msg"></param> /// <param name="_mahuaApi"></param> /// <returns></returns> public static string SolveAdmin(string qq, string msg, IMahuaApi _mahuaApi) { if (msg.IndexOf("删除") == 0) { if (msg.Replace("删除", "") != "") { XmlSolve.del("bind_qq_wait", msg.Replace("删除", "")); XmlSolve.del("bind_qq", msg.Replace("删除", "")); return "已删除QQ:" + msg.Replace("删除", "") + "所绑定的id。"; } } else if (msg.IndexOf("通过") == 0) { string player = XmlSolve.xml_get("bind_qq_wait", msg.Replace("通过", "")); if (player != "") { XmlSolve.del("bind_qq_wait", msg.Replace("通过", "")); XmlSolve.insert("bind_qq", msg.Replace("通过", ""), player); _mahuaApi.SendGroupMessage("241464054", Tools.At(msg.Replace("通过", "")) + "你的白名单申请已经通过了哟~" + "\r\n在群里发送“激活”即可获取激活账号的方法哦~" + "\r\n你的id:" + player); return "已通过QQ:" + msg.Replace("通过", "") + ",id:" + player + "的白名单申请"; } else { return "参数不对或该玩家不在待审核玩家数据中"; } } else if (msg.IndexOf("不通过") == 0) { if (msg.IndexOf("不通过 ") == 0) { return "命令关键字后不要加空格,直接加玩家id"; } string player = ""; string reason = ""; string qq_get = ""; string[] str2; int count_temp = 0; str2 = msg.Replace("不通过", "").Split(' '); foreach (string i in str2) { if (count_temp == 0) { player = XmlSolve.xml_get("bind_qq_wait", i); qq_get = i; count_temp++; } else if (count_temp == 1) { reason += i + " "; } } if (player != "") { _mahuaApi.SendGroupMessage("241464054", Tools.At(qq_get) + "你的白名单申请并没有通过。" + "\r\n原因:" + reason + "\r\n请按照原因重新填写白名单:https://wj.qq.com/s/1308067/143c" + "\r\n你的id:" + player); return "已不通过QQ:" + qq_get + ",id:" + player + "的白名单申请,原因:" + reason; } else { return "参数不对或该玩家不在待审核玩家数据中"; } } else if (msg == "空间") { return "服务器盘剩余空间:" + ((float)GetHardDiskFreeSpace("D") / 1024).ToString(".00") + "GB\r\n" + "备份盘剩余空间:" + ((float)GetHardDiskFreeSpace("E") / 1024).ToString(".00") + "GB"; } else if (msg == "即时备份" && qq == "961726194") { System.Diagnostics.Process.Start(@"D:\backup.bat"); return "备份任务已开始"; //567145439 } return ""; } /// <summary> /// 检查id合法性 /// </summary> /// <param name="t"></param> /// <returns></returns> public static bool CheckID(string t) { t = t.ToUpper(); if (t == "" || t == "ID") return false; t = t.Replace("A", ""); t = t.Replace("B", ""); t = t.Replace("C", ""); t = t.Replace("D", ""); t = t.Replace("E", ""); t = t.Replace("F", ""); t = t.Replace("G", ""); t = t.Replace("H", ""); t = t.Replace("I", ""); t = t.Replace("J", ""); t = t.Replace("K", ""); t = t.Replace("L", ""); t = t.Replace("M", ""); t = t.Replace("N", ""); t = t.Replace("O", ""); t = t.Replace("P", ""); t = t.Replace("Q", ""); t = t.Replace("R", ""); t = t.Replace("S", ""); t = t.Replace("T", ""); t = t.Replace("U", ""); t = t.Replace("V", ""); t = t.Replace("W", ""); t = t.Replace("X", ""); t = t.Replace("Y", ""); t = t.Replace("Z", ""); t = t.Replace("_", ""); t = t.Replace("1", ""); t = t.Replace("2", ""); t = t.Replace("3", ""); t = t.Replace("4", ""); t = t.Replace("5", ""); t = t.Replace("6", ""); t = t.Replace("7", ""); t = t.Replace("8", ""); t = t.Replace("9", ""); t = t.Replace("0", ""); if (t == "") { return true; } else { return false; } } /// <summary> /// 获取指定驱动器的剩余空间总大小(单位为MB) /// </summary> /// <param name="str_HardDiskName">只需输入代表驱动器的字母即可 </param> /// <returns> </returns> public static long GetHardDiskFreeSpace(string str_HardDiskName) { long freeSpace = new long(); str_HardDiskName = str_HardDiskName + ":\\"; System.IO.DriveInfo[] drives = System.IO.DriveInfo.GetDrives(); foreach (System.IO.DriveInfo drive in drives) { if (drive.Name == str_HardDiskName) { freeSpace = drive.TotalFreeSpace / (1024 * 1024); } } return freeSpace; } } } <file_sep>/README.md # receiver-meow 接待喵的qq号:751323264 --- 已实现的功能: - 手动点赞 - 自定义指定关键字词,并进行回复 - 点金坷垃歌曲 - 查询每日运势 - 抽奖禁言功能 - 查快递 - 查询空气质量 - 自助获取词条修改权限 - 5%复读群消息 --- 如借用本项目,请自行将所有api key改成自己的 基于[酷Q](https://cqp.cc/)与[Newbe.Mahua](https://github.com/newbe36524/Newbe.Mahua.Framework/)框架,重新编写的接待喵qq机器人 <file_sep>/Newbe.Mahua.Receiver.Meow/Newbe.Mahua.Receiver.Meow/MahuaApis/LotteryEvent.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Newbe.Mahua.Receiver.Meow.MahuaApis { class LotteryEvent { /// <summary> /// 抽奖方法,获取抽奖结果并执行禁言 /// </summary> /// <param name="qq"></param> /// <param name="_mahuaApi"></param> /// <param name="group"></param> /// <returns></returns> public static string Lottery(string qq, IMahuaApi _mahuaApi,string group) { if (CheckCount(qq)) { return Tools.At(qq) + "今日抽奖次数已用完!"; } string result = ""; int need_add = 0; Random ran = new Random(System.DateTime.Now.Millisecond); int RandKey = ran.Next(1, 22); int RandKey2 = ran.Next(0, 10); if (RandKey > 12) { result += Tools.At(qq) + "\r\n恭喜你!什么也没有抽中!"; } else if (RandKey == 1 && RandKey2 != 0) { need_add += 10; TimeSpan span = new TimeSpan(0, 10, 0, 0); _mahuaApi.BanGroupMember(group, qq, span); result += Tools.At(qq) + "\r\n恭喜你抽中了超豪华禁言套餐,并附赠10张禁言卡!奖励已发放!"; } else if (RandKey == 1 && RandKey2 == 0) { need_add += 200; TimeSpan span = new TimeSpan(30, 0, 0, 0); _mahuaApi.BanGroupMember(group, qq, span); result += Tools.At(qq) + "\r\n恭喜你抽中了顶级豪华月卡禁言套餐,并附赠200张禁言卡!奖励已发放!"; } else if (RandKey < 11) { TimeSpan span = new TimeSpan(0, RandKey, 0, 0); _mahuaApi.BanGroupMember(group, qq, span); result += Tools.At(qq) + "\r\n恭喜你抽中了禁言" + RandKey + "小时!奖励已发放到你的QQ~"; } else { need_add += 1; result += Tools.At(qq) + "\r\n恭喜你抽中了一张禁言卡,回复“禁言卡”可以查看使用帮助。"; } if(need_add != 0) { int fk = 0; string fks = XmlSolve.xml_get("ban_card", qq); if (fks != "") { fk = int.Parse(fks); } fk += need_add; XmlSolve.del("ban_card", qq); XmlSolve.insert("ban_card", qq, fk.ToString()); } return result; } /// <summary> /// 获取禁言卡数量方法 /// </summary> /// <param name="qq"></param> /// <returns></returns> public static string GetBanCard(string qq) { int fk = 0; string fks = XmlSolve.xml_get("ban_card", qq); if (fks != "") { fk = int.Parse(fks); } return Tools.At(qq) + "\r\n禁言卡可用于禁言或解禁他人,如果接待权限足够。\r\n" + "使用方法:发送禁言或解禁加上@那个人\r\n" + "禁言时长将为1分钟-10分钟随机\r\n" + "获取方式:抽奖时有十分之一的概率获得\r\n" + "你当前剩余的禁言卡数量:" + fk.ToString(); } /// <summary> /// 禁言某人 /// </summary> /// <param name="fromqq"></param> /// <param name="banqq"></param> /// <param name="group"></param> /// <param name="_mahuaApi"></param> /// <returns></returns> public static string BanSomebody(string fromqq, string banqq, string group, IMahuaApi _mahuaApi) { int fk = 0; string fks = XmlSolve.xml_get("ban_card", fromqq); if (fks != "") { fk = int.Parse(fks); } if (fk > 0) { try { Random ran = new Random(System.DateTime.Now.Millisecond); int RandKey = ran.Next(0, 60); TimeSpan span = new TimeSpan(0, 0, RandKey, 0); _mahuaApi.BanGroupMember(group, banqq, span); fk--; XmlSolve.del("ban_card", fromqq); XmlSolve.insert("ban_card", fromqq, fk.ToString()); return Tools.At(fromqq) + "\r\n已将" + banqq + "禁言" + RandKey + "分钟"; } catch { return Tools.At(fromqq) + "\r\n执行失败。"; } } else { return Tools.At(fromqq) + "\r\n你哪儿有禁言卡?"; } } /// <summary> /// 解禁某人 /// </summary> /// <param name="fromqq"></param> /// <param name="banqq"></param> /// <param name="group"></param> /// <param name="_mahuaApi"></param> /// <returns></returns> public static string UnbanSomebody(string fromqq, string banqq, string group, IMahuaApi _mahuaApi) { int fk = 0; string fks = XmlSolve.xml_get("ban_card", fromqq); if (fks != "") { fk = int.Parse(fks); } if (fk > 0) { try { TimeSpan span = new TimeSpan(0, 0, 0, 0); _mahuaApi.BanGroupMember(group, banqq, span); fk--; XmlSolve.del("ban_card", fromqq); XmlSolve.insert("ban_card", fromqq, fk.ToString()); return Tools.At(fromqq) + "\r\n已将" + banqq + "解除禁言"; } catch { return Tools.At(fromqq) + "\r\n执行失败。"; } } else { return Tools.At(fromqq) + "\r\n你哪儿有禁言卡?"; } } /// <summary> /// 检查今日抽奖次数有没有用完 /// </summary> /// <param name="qq"></param> /// <returns></returns> public static bool CheckCount(string qq) { string last_time = XmlSolve.xml_get("daily_sign_in_time", qq); if(last_time == System.DateTime.Today.ToString()) //今天抽过奖了 { int count = 0; try { count = int.Parse(XmlSolve.xml_get("lottery_count", qq)); } catch { } if (count == 0) return true; else { XmlSolve.del("lottery_count", qq); XmlSolve.insert("lottery_count", qq, (count - 1).ToString()); return false; } } else //今天没抽奖 { XmlSolve.del("daily_sign_in_time", qq); XmlSolve.insert("daily_sign_in_time", qq, System.DateTime.Today.ToString()); XmlSolve.del("lottery_count", qq); XmlSolve.insert("lottery_count", qq, "4"); return false; } } } } <file_sep>/Newbe.Mahua.Receiver.Meow/Newbe.Mahua.Receiver.Meow/MahuaApis/Tools.cs using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Newbe.Mahua.Receiver.Meow.MahuaApis { class Tools { public static int messageCount = 0; public static string now = DateTime.Now.ToString(); /// <summary> /// 判断是否发消息,消息速率限制函数 /// </summary> /// <returns></returns> public static bool MessageControl(int count) { if (now == DateTime.Now.ToString()) { if (messageCount < count) { messageCount++; return false; } else { return true; } } else { now = DateTime.Now.ToString(); messageCount = 0; return false; } } /// <summary> /// 获取at某人的整合格式 /// </summary> /// <param name="qq"></param> /// <returns></returns> public static string At(string qq) { return "[CQ:at,qq=" + qq + "]"; } /// <summary> /// 获取复读语句 /// </summary> /// <param name="msg"></param> /// <param name="group"></param> /// <returns></returns> public static string GetRepeatString(string msg, string group) { int sum = 0; try { sum = int.Parse(XmlSolve.xml_get("repeat_settings", group)); if (GetRandomNumber(0, 100) < sum) { if (sum <= 100) return msg; else { string result = ""; for (int i = 0; i < sum / 100; i++) result += msg; if (GetRandomNumber(0, 100) < sum % 100) return result + msg; else return result; } } else return ""; } catch { return ""; } } /// <summary> /// 设置复读概率 /// </summary> /// <param name="input"></param> /// <param name="group"></param> /// <returns></returns> public static string SetRepeat(string input, string group) { int sum = 0; try { sum = int.Parse(input); if (sum > 1000) sum = 1000; XmlSolve.del("repeat_settings", group); XmlSolve.insert("repeat_settings", group, sum.ToString()); return "设置完成,复读概率更改为" + sum + "%"; } catch { return "设置失败,请检查参数"; } } /// <summary> /// 获取随机数 /// </summary> /// <param name="min"></param> /// <param name="max"></param> /// <returns></returns> public static int GetRandomNumber(int min, int max) { Random ran = new Random(System.DateTime.Now.Millisecond); return ran.Next(min, max); } /// <summary> /// GET 请求与获取结果(qq宠物专用,带cookie参数) /// </summary> public static string HttpGetPet(string Url, string postDataStr, string uin, string skey) { try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr); request.Method = "GET"; request.ContentType = "text/html;charset=UTF-8"; request.Headers.Add("cookie", "uin=" + uin + "; skey=" + skey); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); return retString; } catch { } return ""; } /// <summary> /// 简化正则的操作 /// </summary> /// <param name="str"></param> /// <param name="regstr"></param> /// <returns></returns> public static MatchCollection Reg_solve(string str, string regstr) { Regex reg = new Regex(regstr, RegexOptions.IgnoreCase); return reg.Matches(str); } /// <summary> /// 直接获取正则表达式的最后一组匹配值 /// </summary> /// <param name="str"></param> /// <param name="regstr"></param> /// <param name="name"></param> /// <returns></returns> public static string Reg_get(string str, string regstr, string name) { string result = ""; MatchCollection matchs = Reg_solve(str, regstr); foreach (Match item in matchs) { if (item.Success) { result = item.Groups[name].Value; } } return result; } /// <summary> /// 获取字符串中的数字 /// </summary> /// <param name="str">字符串</param> /// <returns>数字</returns> public static string GetNumber(string str) { string result = ""; if (str != null && str != string.Empty) { // 正则表达式剔除非数字字符(不包含小数点.) str = Regex.Replace(str, @"[^\d.\d]", ""); // 如果是数字,则转换为decimal类型 if (Regex.IsMatch(str, @"^[+-]?\d*[.]?\d*$")) { result = str; } } return result; } /// <summary> /// 获取CMD执行结果 /// </summary> /// <param name="command">命令</param> /// <returns></returns> public static string execCMD(string command) { System.Diagnostics.Process pro = new System.Diagnostics.Process(); pro.StartInfo.FileName = "cmd.exe"; pro.StartInfo.UseShellExecute = false; pro.StartInfo.RedirectStandardError = true; pro.StartInfo.RedirectStandardInput = true; pro.StartInfo.RedirectStandardOutput = true; pro.StartInfo.CreateNoWindow = true; //pro.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; pro.Start(); pro.StandardInput.WriteLine(command); pro.StandardInput.WriteLine("exit"); pro.StandardInput.AutoFlush = true; //获取cmd窗口的输出信息 string output = pro.StandardOutput.ReadToEnd(); pro.WaitForExit();//等待程序执行完退出进程 pro.Close(); return output; } /// <summary> /// GET 请求与获取结果 /// </summary> public static string HttpGet(string Url, string postDataStr) { try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr); request.Method = "GET"; request.ContentType = "text/html;charset=UTF-8"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); return retString; } catch { } return ""; } ///<summary> ///生成随机字符串 ///</summary> ///<param name="length">目标字符串的长度</param> ///<param name="useNum">是否包含数字,1=包含,默认为包含</param> ///<param name="useLow">是否包含小写字母,1=包含,默认为包含</param> ///<param name="useUpp">是否包含大写字母,1=包含,默认为包含</param> ///<param name="useSpe">是否包含特殊字符,1=包含,默认为不包含</param> ///<param name="custom">要包含的自定义字符,直接输入要包含的字符列表</param> ///<returns>指定长度的随机字符串</returns> public static string GetRandomString(int length, bool useNum, bool useLow, bool useUpp, bool useSpe, string custom) { byte[] b = new byte[4]; new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(b); Random r = new Random(BitConverter.ToInt32(b, 0)); string s = null, str = custom; if (useNum == true) { str += "0123456789"; } if (useLow == true) { str += "abcdefghijklmnopqrstuvwxyz"; } if (useUpp == true) { str += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; } if (useSpe == true) { str += "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"; } for (int i = 0; i < length; i++) { s += str.Substring(r.Next(0, str.Length - 1), 1); } return s; } /// <summary> /// 获取指定驱动器的剩余空间总大小(单位为MB) /// </summary> /// <param name="str_HardDiskName">只需输入代表驱动器的字母即可 </param> /// <returns> </returns> public static long GetHardDiskFreeSpace(string str_HardDiskName) { long freeSpace = new long(); str_HardDiskName = str_HardDiskName + ":\\"; System.IO.DriveInfo[] drives = System.IO.DriveInfo.GetDrives(); foreach (System.IO.DriveInfo drive in drives) { if (drive.Name == str_HardDiskName) { freeSpace = drive.TotalFreeSpace / (1024 * 1024); } } return freeSpace; } /// <summary> /// 获取快递信息 /// </summary> /// <param name="expressNo"></param> /// <param name="qq"></param> /// <returns></returns> public static string GetExpress(string expressNo, string qq) { if (expressNo == "") { expressNo = XmlSolve.xml_get("express", qq); if (expressNo == "") { return At(qq) + "你没有查询过任何快递,请输入要查询的单号"; } } else { XmlSolve.del("express", qq); XmlSolve.insert("express", qq, expressNo); } string result_msg = ""; try { string html = HttpGet("https://www.kuaidi100.com/autonumber/autoComNum", "text=" + expressNo); JObject jo = (JObject)JsonConvert.DeserializeObject(html); string comCode = jo["auto"][0]["comCode"].ToString(); result_msg = comCode + "\r\n"; html = HttpGet("https://www.kuaidi100.com/query", "type=" + comCode + "&postid=" + expressNo); jo = (JObject)JsonConvert.DeserializeObject(html); foreach (var i in jo["data"]) { result_msg += i["time"].ToString() + " "; result_msg += i["context"].ToString() + " 地点:"; result_msg += i["location"].ToString() + "\r\n"; } if (result_msg == comCode + "\r\n") { result_msg = ""; } } catch { } if (result_msg == "") { return At(qq) + "无此单号的数据"; } else { return At(qq) + result_msg + "下次查询该快递可直接发送“查快递”命令,无需在输入单号"; } } private static int[] pyValue = new int[] { -20319,-20317,-20304,-20295,-20292,-20283,-20265,-20257,-20242,-20230,-20051,-20036, -20032,-20026,-20002,-19990,-19986,-19982,-19976,-19805,-19784,-19775,-19774,-19763, -19756,-19751,-19746,-19741,-19739,-19728,-19725,-19715,-19540,-19531,-19525,-19515, -19500,-19484,-19479,-19467,-19289,-19288,-19281,-19275,-19270,-19263,-19261,-19249, -19243,-19242,-19238,-19235,-19227,-19224,-19218,-19212,-19038,-19023,-19018,-19006, -19003,-18996,-18977,-18961,-18952,-18783,-18774,-18773,-18763,-18756,-18741,-18735, -18731,-18722,-18710,-18697,-18696,-18526,-18518,-18501,-18490,-18478,-18463,-18448, -18447,-18446,-18239,-18237,-18231,-18220,-18211,-18201,-18184,-18183, -18181,-18012, -17997,-17988,-17970,-17964,-17961,-17950,-17947,-17931,-17928,-17922,-17759,-17752, -17733,-17730,-17721,-17703,-17701,-17697,-17692,-17683,-17676,-17496,-17487,-17482, -17468,-17454,-17433,-17427,-17417,-17202,-17185,-16983,-16970,-16942,-16915,-16733, -16708,-16706,-16689,-16664,-16657,-16647,-16474,-16470,-16465,-16459,-16452,-16448, -16433,-16429,-16427,-16423,-16419,-16412,-16407,-16403,-16401,-16393,-16220,-16216, -16212,-16205,-16202,-16187,-16180,-16171,-16169,-16158,-16155,-15959,-15958,-15944, -15933,-15920,-15915,-15903,-15889,-15878,-15707,-15701,-15681,-15667,-15661,-15659, -15652,-15640,-15631,-15625,-15454,-15448,-15436,-15435,-15419,-15416,-15408,-15394, -15385,-15377,-15375,-15369,-15363,-15362,-15183,-15180,-15165,-15158,-15153,-15150, -15149,-15144,-15143,-15141,-15140,-15139,-15128,-15121,-15119,-15117,-15110,-15109, -14941,-14937,-14933,-14930,-14929,-14928,-14926,-14922,-14921,-14914,-14908,-14902, -14894,-14889,-14882,-14873,-14871,-14857,-14678,-14674,-14670,-14668,-14663,-14654, -14645,-14630,-14594,-14429,-14407,-14399,-14384,-14379,-14368,-14355,-14353,-14345, -14170,-14159,-14151,-14149,-14145,-14140,-14137,-14135,-14125,-14123,-14122,-14112, -14109,-14099,-14097,-14094,-14092,-14090,-14087,-14083,-13917,-13914,-13910,-13907, -13906,-13905,-13896,-13894,-13878,-13870,-13859,-13847,-13831,-13658,-13611,-13601, -13406,-13404,-13400,-13398,-13395,-13391,-13387,-13383,-13367,-13359,-13356,-13343, -13340,-13329,-13326,-13318,-13147,-13138,-13120,-13107,-13096,-13095,-13091,-13076, -13068,-13063,-13060,-12888,-12875,-12871,-12860,-12858,-12852,-12849,-12838,-12831, -12829,-12812,-12802,-12607,-12597,-12594,-12585,-12556,-12359,-12346,-12320,-12300, -12120,-12099,-12089,-12074,-12067,-12058,-12039,-11867,-11861,-11847,-11831,-11798, -11781,-11604,-11589,-11536,-11358,-11340,-11339,-11324,-11303,-11097,-11077,-11067, -11055,-11052,-11045,-11041,-11038,-11024,-11020,-11019,-11018,-11014,-10838,-10832, -10815,-10800,-10790,-10780,-10764,-10587,-10544,-10533,-10519,-10331,-10329,-10328, -10322,-10315,-10309,-10307,-10296,-10281,-10274,-10270,-10262,-10260,-10256,-10254 }; private static string[] pyName = new string[] { "A","Ai","An","Ang","Ao","Ba","Bai","Ban","Bang","Bao","Bei","Ben", "Beng","Bi","Bian","Biao","Bie","Bin","Bing","Bo","Bu","Ba","Cai","Can", "Cang","Cao","Ce","Ceng","Cha","Chai","Chan","Chang","Chao","Che","Chen","Cheng", "Chi","Chong","Chou","Chu","Chuai","Chuan","Chuang","Chui","Chun","Chuo","Ci","Cong", "Cou","Cu","Cuan","Cui","Cun","Cuo","Da","Dai","Dan","Dang","Dao","De", "Deng","Di","Dian","Diao","Die","Ding","Diu","Dong","Dou","Du","Duan","Dui", "Dun","Duo","E","En","Er","Fa","Fan","Fang","Fei","Fen","Feng","Fo", "Fou","Fu","Ga","Gai","Gan","Gang","Gao","Ge","Gei","Gen","Geng","Gong", "Gou","Gu","Gua","Guai","Guan","Guang","Gui","Gun","Guo","Ha","Hai","Han", "Hang","Hao","He","Hei","Hen","Heng","Hong","Hou","Hu","Hua","Huai","Huan", "Huang","Hui","Hun","Huo","Ji","Jia","Jian","Jiang","Jiao","Jie","Jin","Jing", "Jiong","Jiu","Ju","Juan","Jue","Jun","Ka","Kai","Kan","Kang","Kao","Ke", "Ken","Keng","Kong","Kou","Ku","Kua","Kuai","Kuan","Kuang","Kui","Kun","Kuo", "La","Lai","Lan","Lang","Lao","Le","Lei","Leng","Li","Lia","Lian","Liang", "Liao","Lie","Lin","Ling","Liu","Long","Lou","Lu","Lv","Luan","Lue","Lun", "Luo","Ma","Mai","Man","Mang","Mao","Me","Mei","Men","Meng","Mi","Mian", "Miao","Mie","Min","Ming","Miu","Mo","Mou","Mu","Na","Nai","Nan","Nang", "Nao","Ne","Nei","Nen","Neng","Ni","Nian","Niang","Niao","Nie","Nin","Ning", "Niu","Nong","Nu","Nv","Nuan","Nue","Nuo","O","Ou","Pa","Pai","Pan", "Pang","Pao","Pei","Pen","Peng","Pi","Pian","Piao","Pie","Pin","Ping","Po", "Pu","Qi","Qia","Qian","Qiang","Qiao","Qie","Qin","Qing","Qiong","Qiu","Qu", "Quan","Que","Qun","Ran","Rang","Rao","Re","Ren","Reng","Ri","Rong","Rou", "Ru","Ruan","Rui","Run","Ruo","Sa","Sai","San","Sang","Sao","Se","Sen", "Seng","Sha","Shai","Shan","Shang","Shao","She","Shen","Sheng","Shi","Shou","Shu", "Shua","Shuai","Shuan","Shuang","Shui","Shun","Shuo","Si","Song","Sou","Su","Suan", "Sui","Sun","Suo","Ta","Tai","Tan","Tang","Tao","Te","Teng","Ti","Tian", "Tiao","Tie","Ting","Tong","Tou","Tu","Tuan","Tui","Tun","Tuo","Wa","Wai", "Wan","Wang","Wei","Wen","Weng","Wo","Wu","Xi","Xia","Xian","Xiang","Xiao", "Xie","Xin","Xing","Xiong","Xiu","Xu","Xuan","Xue","Xun","Ya","Yan","Yang", "Yao","Ye","Yi","Yin","Ying","Yo","Yong","You","Yu","Yuan","Yue","Yun", "Za", "Zai","Zan","Zang","Zao","Ze","Zei","Zen","Zeng","Zha","Zhai","Zhan", "Zhang","Zhao","Zhe","Zhen","Zheng","Zhi","Zhong","Zhou","Zhu","Zhua","Zhuai","Zhuan", "Zhuang","Zhui","Zhun","Zhuo","Zi","Zong","Zou","Zu","Zuan","Zui","Zun","Zuo" }; /// <summary> /// 把汉字转换成拼音(全拼) /// </summary> /// <param name="hzString">汉字字符串</param> /// <returns>转换后的拼音(全拼)字符串</returns> public static string PinyinConvert(string hzString) { // 匹配中文字符 Regex regex = new Regex("^[\u4e00-\u9fa5]$"); byte[] array = new byte[2]; string pyString = ""; int chrAsc = 0; int i1 = 0; int i2 = 0; char[] noWChar = hzString.ToCharArray(); for (int j = 0; j < noWChar.Length; j++) { // 中文字符 if (regex.IsMatch(noWChar[j].ToString())) { array = System.Text.Encoding.Default.GetBytes(noWChar[j].ToString()); i1 = (short)(array[0]); i2 = (short)(array[1]); chrAsc = i1 * 256 + i2 - 65536; if (chrAsc > 0 && chrAsc < 160) { pyString += noWChar[j]; } else { // 修正部分文字 if (chrAsc == -9254) // 修正“圳”字 pyString += "Zhen"; else { for (int i = (pyValue.Length - 1); i >= 0; i--) { if (pyValue[i] <= chrAsc) { pyString += pyName[i]; break; } } } } } // 非中文字符 else { pyString += noWChar[j].ToString(); } } return pyString; } public static string GetAir(string msg,string qq) { if (msg == "空气质量") { return At(qq) + "\r\n使用帮助:\r\n发送空气质量加城市名称,即可查询\r\n如:空气质量New York"; } string city = PinyinConvert(msg.Replace("空气质量", "")); string html; int city_code = 0; try { city_code = int.Parse(PinyinConvert(msg.Replace("空气质量", ""))); try { html = HttpGet("http://api.waqi.info/feed/@" + city_code + "/", "token=<KEY>"); JObject jo = (JObject)JsonConvert.DeserializeObject(html); string station = (string)jo["data"]["city"]["name"]; string result = ""; string from = ""; try { result += "\r\n空气质量指数:" + (int)jo["data"]["aqi"]; } catch { } try { result += "\r\npm2.5:" + (float)jo["data"]["iaqi"]["pm25"]["v"]; } catch { } try { result += "\r\npm10:" + (float)jo["data"]["iaqi"]["pm10"]["v"]; } catch { } try { result += "\r\nco:" + (float)jo["data"]["iaqi"]["co"]["v"]; } catch { } try { result += "\r\nno2:" + (float)jo["data"]["iaqi"]["no2"]["v"]; } catch { } try { result += "\r\no3:" + (float)jo["data"]["iaqi"]["o3"]["v"]; } catch { } try { result += "\r\nso2:" + (float)jo["data"]["iaqi"]["so2"]["v"]; } catch { } try { from = (string)jo["data"]["attributions"][0]["name"]; } catch { } return At(qq) + "\r\n" + station + "的空气质量如下:" + result + "\r\n数据来源:" + from + "\r\n数据更新时间:" + (string)jo["data"]["time"]["s"]; } catch (Exception err) { string aa = err.Message.ToString(); return At(qq) + "\r\n机器人在查询数据时爆炸了,原因:" + aa; } } catch { try { int station_count = 0; string result = ""; html = HttpGet("http://api.waqi.info/search/", "keyword=" + city + "&token=<KEY>"); JObject jo = (JObject)JsonConvert.DeserializeObject(html); foreach (var i in jo["data"]) { result += (int)i["uid"] + ":" + (string)i["station"]["name"] + "\r\n"; station_count++; } return At(qq) + "\r\n共找到" + station_count + "个监测站:" + "\r\n" + result + "\r\n使用指令“空气质量”加监测站编号查看数据"; } catch (Exception err) { string aa = err.Message.ToString(); return At(qq) + "\r\n机器人在查找监测站时爆炸了,原因:" + aa; } } } public static string Get163Music(string songName, string qq) { int songID = 0; try { songID = int.Parse(songName); } catch { try { string html = HttpGet("http://s.music.163.com/search/get/", "type=1&s=" + songName); JObject jo = (JObject)JsonConvert.DeserializeObject(html); string idGet = jo["result"]["songs"][0]["id"].ToString(); songID = int.Parse(idGet); } catch { return At(qq) + "\r\n机器人爆炸了,原因:根本没这首歌"; } } return "[CQ:music,type=163,id=" + songID + "]"; } } } <file_sep>/Newbe.Mahua.Receiver.Meow/Newbe.Mahua.Receiver.Meow/MahuaApis/MessageSolve.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newbe.Mahua.MahuaEvents; using Newbe.Mahua.Receiver.Meow.MahuaApis; using Newbe.Mahua.Receiver.Meow; namespace Newbe.Mahua.Receiver.Meow.MahuaApis { class MessageSolve { private static string prem = "你没有权限调教接待喵,权限获取方法请去问开发者"; public static string GetReplay(string fromqq,string msg, IMahuaApi _mahuaApi, string fromgroup = "common") { if (Tools.MessageControl(5)) return ""; string result = ""; if (msg == "赞我" || msg == "点赞") { _mahuaApi.SendLike(fromqq); result += Tools.At(fromqq) + "已为你点赞"; } else if (msg.ToUpper() == "HELP" || msg == "帮助" || msg == "菜单") { result += "命令帮助:\r\n!add 词条:回答\r\n!del 词条:回答\r\n!list 词条\r\n!delall 词条\r\n" + "所有符号均为中文全角符号\r\n" + "发送“坷垃金曲”+数字序号即可点金坷垃歌(如坷垃金曲21,最大71)\r\n" + "发送“点赞”可使接待给你点赞\r\n" + "发送“今日运势”可以查看今日运势\r\n" + "发送“查快递”和单号即可搜索快递物流信息\r\n" + "发送“空气质量”可查询当前时间的空气质量\r\n" + "发送“点歌”加网易云id或歌名可点歌\r\n" + "发送“宠物助手”可查询QQ宠物代挂的帮助信息\r\n" + "发送“复读”加百分比可更改复读概率\r\n" + "每秒最多响应5条消息\r\n" + "如有建议请到https://git.io/fNmBc反馈,欢迎star"; } else if (msg == "宠物助手") { result += "宠物助手:\r\n" + "发送“宠物状态”可查看宠物状态\r\n" + "发送“宠物资料”可查看宠物详细资料\r\n" + "发送“宠物喂养”加页码数可查看宠物喂养物品列表\r\n" + "发送“宠物清洁”加页码数可查看宠物清洁物品列表\r\n" + "发送“宠物治疗”加页码数可查看宠物药物物品列表\r\n" + "发送“宠物使用”加物品代码可使用宠物物品\r\n" + "发送“宠物学习开启”可开启自动学习\r\n" + "发送“宠物学习关闭”可关闭自动学习\r\n" + "发送“宠物解绑”可解除绑定,停止代挂\r\n" + "挂机时会自动喂养与清洗,并且自动种菜收菜\r\n" + "测试功能,如有bug请反馈"; } else if (msg.IndexOf("宠物") == 0) { //获取uin和skey string uin = XmlSolve.replay_get("qq_pet_uin", fromqq); string skey = XmlSolve.replay_get("qq_pet_skey", fromqq); if (msg == "宠物状态") { result += Tools.At(fromqq) + "\r\n" + QQPet.GetPetState(uin, skey); } else if (msg == "宠物资料") { result += Tools.At(fromqq) + "\r\n" + QQPet.GetPetMore(uin, skey); } else if (msg.IndexOf("宠物喂养") == 0) { result += Tools.At(fromqq) + "\r\n" + QQPet.FeedPetSelect(uin, skey, msg.Replace("宠物喂养", "")); } else if (msg.IndexOf("宠物清洁") == 0) { result += Tools.At(fromqq) + "\r\n" + QQPet.WashPetSelect(uin, skey, msg.Replace("宠物清洁", "")); } else if (msg.IndexOf("宠物治疗") == 0) { result += Tools.At(fromqq) + "\r\n" + QQPet.CurePetSelect(uin, skey, msg.Replace("宠物治疗", "")); } else if (msg.IndexOf("宠物使用") == 0) { result += Tools.At(fromqq) + "\r\n" + QQPet.UsePet(uin, skey, msg.Replace("宠物使用", "")); } else if (msg == "宠物学习开启") { XmlSolve.del("qq_pet_study", fromqq); XmlSolve.insert("qq_pet_study", fromqq, "0"); result += Tools.At(fromqq) + "\r\n" + "已开启自动学习(自动上课与换课程)"; } else if (msg == "宠物学习关闭") { XmlSolve.del("qq_pet_study", fromqq); XmlSolve.insert("qq_pet_study", fromqq, "28"); result += Tools.At(fromqq) + "\r\n" + "已关闭自动学习(学习完后不会自动继续学)"; } else if (msg == "宠物解绑") { XmlSolve.del("qq_pet_study", fromqq); XmlSolve.del("qq_pet_study", fromqq); result += Tools.At(fromqq) + "\r\n" + "\r\n解绑成功!"; } else if (msg == "宠物绑定方法") { result += Tools.At(fromqq) + "\r\n" + "[CQ:image,file=7CE7991F3D714978606B41C816FBC549.jpg]"; } } else if (msg.IndexOf("坷垃金曲") == 0) { int song = 0; try { song = int.Parse(msg.Replace("坷垃金曲", "")); } catch { } if (song >= 1 && song <= 71) { result += "[CQ:record,file=CoolQ 语音时代!\\坷垃金曲\\" + song.ToString().PadLeft(3, '0') + ".mp3]"; } else { result += Tools.At(fromqq) + "编号不对哦,编号只能是1-71"; } } else if (msg.IndexOf("!list ") == 0) { result += string.Format("当前词条回复如下:\r\n{0}\r\n全局词库内容:\r\n{1}", XmlSolve.list_get(fromgroup, msg.Replace("!list ", "")), XmlSolve.list_get("common", msg.Replace("!list ", ""))); } else if (msg.IndexOf("!add ") == 0) { if ((XmlSolve.AdminCheck(fromqq) >= 1 && fromgroup != "common") || (fromgroup == "common" && fromqq == "961726194")) { string get_msg = msg.Replace("!add ", ""), tmsg = "", tans = ""; if (get_msg.IndexOf(":") >= 1 && get_msg.IndexOf(":") != get_msg.Length - 1) { string[] str2; int count_temp = 0; str2 = get_msg.Split(':'); foreach (string i in str2) { if (count_temp == 0) { tmsg = i.ToString(); count_temp++; } else { tans += i.ToString(); } } XmlSolve.insert(fromgroup, tmsg, tans); result += "添加完成!\r\n词条:" + tmsg + "\r\n回答为:" + tans; } else { result += "格式错误!"; } } else { result += prem; } } else if (msg.IndexOf("!del ") == 0) { if ((XmlSolve.AdminCheck(fromqq) >= 1 && fromgroup != "common") || (fromgroup == "common" && fromqq == "961726194")) { string get_msg = msg.Replace("!del ", ""), tmsg = "", tans = ""; if (get_msg.IndexOf(":") >= 1 && get_msg.IndexOf(":") != get_msg.Length - 1) { string[] str2; int count_temp = 0; str2 = get_msg.Split(':'); foreach (string i in str2) { if (count_temp == 0) { tmsg = i.ToString(); count_temp++; } else { tans += i.ToString(); } } XmlSolve.remove(fromgroup, tmsg, tans); result += "删除完成!\r\n词条:" + tmsg + "\r\n回答为:" + tans; } else { result += "格式错误!"; } } else { result += prem; } } else if (msg.IndexOf("!delall ") == 0) { if ((XmlSolve.AdminCheck(fromqq) >= 1 && fromgroup != "common") || (fromgroup == "common" && fromqq == "961726194")) { string get_msg = msg.Replace("!delall ", ""); if (get_msg.Length > 0) { XmlSolve.del(fromgroup, get_msg); result += "删除完成!\r\n触发词:" + get_msg; } else { result += "格式错误!"; } } else { result += prem; } } else if (msg.IndexOf("[CQ:hb,title=") != -1 && msg.IndexOf("]") != -1 && fromgroup == "common") { XmlSolve.insert("admin_list", "给我列一下狗管理", fromqq); result += "已给予" + fromqq + "词条编辑权限。"; } else if (msg.IndexOf("!addadmin ") == 0 && fromqq == "961726194") { XmlSolve.insert("admin_list", "给我列一下狗管理", msg.Replace("!addadmin ", "")); result += "已添加一位狗管理"; } else if (msg.IndexOf("!deladmin ") == 0 && fromqq == "961726194") { XmlSolve.remove("admin_list", "给我列一下狗管理", msg.Replace("!deladmin ", "")); result += "已删除一位狗管理"; } else if (msg == "给我列一下狗管理") { result += "当前狗管理如下:\r\n" + XmlSolve.list_get("admin_list", "给我列一下狗管理"); } else if (msg == "今日黄历" || msg == "今日运势" || msg == "今天运势" || msg == "今天黄历") { result += TodaysAlmanac.GetAlmanac(fromqq, DateTime.Now.DayOfYear); } else if (msg == "昨日黄历" || msg == "昨日运势" || msg == "昨天运势" || msg == "昨天黄历") { result += TodaysAlmanac.GetAlmanac(fromqq, DateTime.Now.DayOfYear - 1); } else if (msg == "明日黄历" || msg == "明日运势" || msg == "明天运势" || msg == "明天黄历") { result += TodaysAlmanac.GetAlmanac(fromqq, DateTime.Now.DayOfYear + 1); } else if (msg == "抽奖" && fromgroup != "common") { result += LotteryEvent.Lottery(fromqq, _mahuaApi, fromgroup); } else if (msg == "禁言卡") { result += LotteryEvent.GetBanCard(fromqq); } else if (msg.IndexOf("禁言") == 0 && msg.Length > 2 && fromgroup != "common") { result += LotteryEvent.BanSomebody(fromqq, Tools.GetNumber(msg), fromgroup, _mahuaApi); } else if (msg.IndexOf("解禁") == 0 && msg.Length > 2 && fromgroup != "common") { result += LotteryEvent.UnbanSomebody(fromqq, Tools.GetNumber(msg), fromgroup, _mahuaApi); } else if (msg.IndexOf("查快递") == 0) { result += Tools.GetExpress(Tools.GetNumber(msg), fromqq); } else if (msg == "开车") { result += "magnet:?xt=urn:btih:" + Tools.GetRandomString(40, true, false, false, false, "ABCDEF"); } else if (msg.IndexOf("空气质量") == 0) { result += Tools.GetAir(msg, fromqq); } else if (msg.IndexOf("cmd ") == 0 && fromqq == "961726194") { result += Tools.execCMD(msg.Replace("cmd ", "")); } else if (msg.IndexOf("复读") == 0 && fromgroup != "common") { if (XmlSolve.AdminCheck(fromqq) >= 1) result += Tools.At(fromqq) + Tools.SetRepeat(Tools.GetNumber(msg), fromgroup); else result += prem; } else if (msg.IndexOf("点歌") == 0) { result += Tools.Get163Music(msg.Replace("点歌", ""), fromqq); } else if (fromgroup == "241464054") //糖拌群 result += MinecraftSolve.SolvePlayer(fromqq, msg, _mahuaApi); else if (fromgroup == "567145439") //分赃群 result += MinecraftSolve.SolveAdmin(fromqq, msg, _mahuaApi); else result += Tools.GetRepeatString(msg, fromgroup); if(result == "") { result += XmlSolve.ReplayGroupStatic(fromgroup, msg); } return result; } } } <file_sep>/Newbe.Mahua.Receiver.Meow/Newbe.Mahua.Receiver.Meow/MahuaApis/XmlSolve.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace Newbe.Mahua.Receiver.Meow.MahuaApis { class XmlSolve { public static string path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "data/";//AppDomain.CurrentDomain.SetupInformation.ApplicationBase public static string ReplayGroupStatic(string fromGroup, string msg) { string replay_ok = replay_get(fromGroup, msg); string replay_common = replay_get("common", msg); if (replay_ok != "") { if (replay_common != "") { Random ran = new Random(System.DateTime.Now.Millisecond); int RandKey = ran.Next(0, 2); if (RandKey == 0) { return replay_ok; } else { return replay_common; } } else { return replay_ok; } } else if (replay_common != "") { return replay_common; } return ""; } public static string replay_get(string group, string msg) { dircheck(group); XElement root = XElement.Load(path + group + ".xml"); string[] replay_str = new string[50]; int count = 0; Random ran = new Random(System.DateTime.Now.Millisecond); int RandKey; string ansall = ""; foreach (XElement mm in root.Elements("msginfo")) { if (msg.IndexOf(mm.Element("msg").Value) != -1 && count < 50) { replay_str[count] = mm.Element("ans").Value; count++; } } if (count != 0) { RandKey = ran.Next(0, count); ansall = replay_str[RandKey]; } return ansall; } public static string qq_get(string msg) { string group = "bind_qq"; dircheck(group); XElement root = XElement.Load(path + group + ".xml"); string ansall = "0"; foreach (XElement mm in root.Elements("msginfo")) { if (msg == mm.Element("ans").Value) { ansall = mm.Element("msg").Value; break; } } return ansall; } public static string qq_get_unregister(string msg) { string group = "bind_qq_wait"; dircheck(group); XElement root = XElement.Load(path + group + ".xml"); string ansall = "0"; foreach (XElement mm in root.Elements("msginfo")) { if (msg == mm.Element("ans").Value) { ansall = mm.Element("msg").Value; break; } } return ansall; } public static string xml_get(string group, string msg) { dircheck(group); XElement root = XElement.Load(path + group + ".xml"); string ansall = ""; foreach (XElement mm in root.Elements("msginfo")) { if (msg == mm.Element("msg").Value) { ansall = mm.Element("ans").Value; break; } } return ansall; } public static string xml_dic_get(string num) { XElement root = XElement.Load(path + "dic.xml"); string ans = ""; foreach (XElement mm in root.Elements("msginfo")) { if (num == mm.Element("sum").Value) { ans = mm.Element("word").Value + "\r\n" + mm.Element("translate").Value; break; } } return ans; } public static string list_get(string group, string msg) { dircheck(group); XElement root = XElement.Load(path + group + ".xml"); int count = 0; string ansall = ""; foreach (XElement mm in root.Elements("msginfo")) { if (msg == mm.Element("msg").Value) { ansall = ansall + mm.Element("ans").Value + "\r\n"; count++; } } ansall = ansall + "一共有" + count.ToString() + "条回复"; return ansall; } public static void del(string group, string msg) { dircheck(group); string gg = group.ToString(); XElement root = XElement.Load(path + group + ".xml"); var element = from ee in root.Elements() where (string)ee.Element("msg") == msg select ee; if (element.Count() > 0) { //element.First().Remove(); element.Remove(); } root.Save(path + group + ".xml"); } public static void remove(string group, string msg, string ans) { dircheck(group); string gg = group.ToString(); XElement root = XElement.Load(path + group + ".xml"); var element = from ee in root.Elements() where (string)ee.Element("msg") == msg && (string)ee.Element("ans") == ans select ee; if (element.Count() > 0) { element.First().Remove(); } root.Save(path + group + ".xml"); } public static void insert(string group, string msg, string ans) { if (msg.IndexOf("\r\n") < 0 & msg != "") { dircheck(group); XElement root = XElement.Load(path + group + ".xml"); XElement read = root.Element("msginfo"); read.AddBeforeSelf(new XElement("msginfo", //new XElement("group", group), new XElement("msg", msg), new XElement("ans", ans) )); root.Save(path + group + ".xml"); } } public static void createxml(string group) { XElement root = new XElement("Categories", new XElement("msginfo", //new XElement("group", 123), new XElement("msg", "初始问题"), new XElement("ans", "初始回答") ) ); root.Save(path + group + ".xml"); } public static void dircheck(string group) { if (File.Exists(path + group + ".xml")) { //MessageBox.Show("存在文件"); //File.Delete(dddd);//删除该文件 } else { //MessageBox.Show("不存在文件"); createxml(group);//创建该文件,如果路径文件夹不存在,则报错。 } } public static int AdminCheck(string fromQQ) { dircheck("admin_list"); XElement root = XElement.Load(path + "admin_list.xml"); int count = 0; foreach (XElement mm in root.Elements("msginfo")) { if (mm.Element("ans").Value == fromQQ.ToString()) { count = 1; } } return count; } } } <file_sep>/Newbe.Mahua.Receiver.Meow/Newbe.Mahua.Receiver.Meow/MahuaApis/QQPet.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Newbe.Mahua.Receiver.Meow.MahuaApis { class QQPet { public static string pleaseLogin = "信息获取失败,请重新发送再试\r\n如果没有绑定宠物信息,请绑定!\r\n绑定方法请回复“宠物绑定方法”查看"; public static string petMore = "更多宠物命令请回复“宠物助手”"; /// <summary> /// 获取宠物基本信息 /// </summary> /// <param name="uin"></param> /// <param name="skey"></param> /// <returns></returns> public static string GetPetState(string uin, string skey) { string result = ""; string html = Tools.HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/phone_pet", "", uin, skey); html = html.Replace("\r", ""); html = html.Replace("\n", ""); if (html.IndexOf("手机统一登录") != -1 || html == "") return pleaseLogin; result += Tools.Reg_get(html, "alt=\"QQ宠物\"/></p><p>(?<say>.*?)<", "say").Replace(" ", "") + "\r\n" + "宠物名:" + Tools.Reg_get(html, "昵称:(?<level>.*?)<", "level").Replace(" ", "") + "\r\n" + "等级:" + Tools.Reg_get(html, "等级:(?<level>.*?)<", "level").Replace(" ", "") + "\r\n" + "状态:" + Tools.Reg_get(html, "状态:(?<now>.*?)<", "now").Replace(" ", "") + "\r\n" + "成长值:" + Tools.Reg_get(html, "成长值:(?<now>.*?)<", "now").Replace(" ", "") + "\r\n" + "饥饿值:" + Tools.Reg_get(html, "饥饿值:(?<now>.*?)<", "now").Replace(" ", "") + "\r\n" + "清洁值:" + Tools.Reg_get(html, "清洁值:(?<now>.*?)<", "now").Replace(" ", "") + "\r\n" + "心情:" + Tools.Reg_get(html, "心情:(?<now>.*?)<", "now").Replace(" ", "") + "\r\n" + petMore; return result; } /// <summary> /// 获取宠物详细信息 /// </summary> /// <param name="uin"></param> /// <param name="skey"></param> /// <returns></returns> public static string GetPetMore(string uin, string skey) { string result = ""; string html = Tools.HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/phone_pet", "cmd=2", uin, skey); html = html.Replace("\r", ""); html = html.Replace("\n", ""); if (html.IndexOf("手机统一登录") != -1 || html == "") return pleaseLogin; result += "主人昵称:" + Tools.Reg_get(html, "主人昵称:(?<name>.*?)&nbsp;", "name").Replace(" ", "") + "\r\n" + "宠物性别:" + Tools.Reg_get(html, "宠物性别:(?<level>.*?)<", "level").Replace(" ", "") + "\r\n" + "生日:" + Tools.Reg_get(html, "生日:(?<now>.*?)<", "now").Replace(" ", "") + "\r\n" + "等级:" + Tools.Reg_get(html, "等级:(?<now>.*?)<", "now").Replace(" ", "") + "\r\n" + "年龄:" + Tools.Reg_get(html, "年龄:(?<now>.*?)<", "now").Replace(" ", "") + "\r\n" + "代数:" + Tools.Reg_get(html, "代数:(?<now>.*?)<", "now").Replace(" ", "") + "\r\n" + "成长值:" + Tools.Reg_get(html, "成长值:(?<now>.*?)<", "now").Replace(" ", "") + "\r\n" + "武力值:" + Tools.Reg_get(html, "武力值:(?<now>.*?)<", "now").Replace(" ", "") + "\r\n" + "智力值:" + Tools.Reg_get(html, "智力值:(?<now>.*?)<", "now").Replace(" ", "") + "\r\n" + "魅力值:" + Tools.Reg_get(html, "魅力值:(?<now>.*?)<", "now").Replace(" ", "") + "\r\n" + "活跃度:" + Tools.Reg_get(html, "活跃度:(?<now>.*?)<", "now").Replace(" ", "") + "\r\n" + "配偶:" + Tools.Reg_get(html, "配偶:(?<now>.*?)<", "now").Replace(" ", "") + "\r\n" + petMore; return result; } /// <summary> /// 喂养宠物选择页面 /// </summary> /// <param name="uin"></param> /// <param name="skey"></param> /// <returns></returns> public static string FeedPetSelect(string uin, string skey, string page) { string result = ""; string html = Tools.HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/phone_pet", "cmd=3&page=" + page, uin, skey); html = html.Replace("\r", ""); html = html.Replace("\n", ""); if (html.IndexOf("手机统一登录") != -1 || html == "") return pleaseLogin; result += "我的账户:" + Tools.Reg_get(html, "我的账户:(?<name>.*?)<", "name").Replace(" ", "") + "\r\n"; int i = 0; MatchCollection matchs = Tools.Reg_solve(Tools.Reg_get(html, "元宝(?<name>.*?)上页", "name").Replace(" ", ""), "<p>(?<name>.*?)<br"); string[] name = new string[matchs.Count]; string[] id = new string[matchs.Count]; foreach (Match item in matchs) { if (item.Success) { name[i++] += item.Groups["name"].Value; } } i = 0; matchs = Tools.Reg_solve(Tools.Reg_get(html, "元宝(?<name>.*?)上页", "name").Replace(" ", ""), "goodid=(?<id>.*?)\""); foreach (Match item in matchs) { if (item.Success) { id[i++] += "物品id:" + item.Groups["id"].Value; } } for (int j = 0; j < i; j++) { result += name[j] + "\r\n" + id[j] + "\r\n"; } if (Tools.Reg_get(html, "上页</a>(?<name>.*?)/", "name").Replace(" ", "") != "") { result += "第" + Tools.Reg_get(html, "上页</a>(?<name>.*?)/", "name").Replace(" ", "") + "页,共" + Tools.Reg_get(html, "上页</a>(.*?)/(?<name>\\d+)", "name").Replace(" ", "") + "页" + "\r\n"; } else { result += "第" + Tools.Reg_get(html, "上页(?<name>.*?)/", "name").Replace(" ", "") + "页,共" + Tools.Reg_get(html, "上页(.*?)/(?<name>\\d+)", "name").Replace(" ", "") + "页" + "\r\n"; } return result + petMore; } /// <summary> /// 清洁宠物选择页面 /// </summary> /// <param name="uin"></param> /// <param name="skey"></param> /// <returns></returns> public static string WashPetSelect(string uin, string skey, string page) { string result = ""; string html = Tools.HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/phone_pet", "cmd=3&page=" + page + "&eatwash=1", uin, skey); html = html.Replace("\r", ""); html = html.Replace("\n", ""); if (html.IndexOf("手机统一登录") != -1 || html == "") return pleaseLogin; result += "我的账户:" + Tools.Reg_get(html, "我的账户:(?<name>.*?)<", "name").Replace(" ", "") + "\r\n"; int i = 0; MatchCollection matchs = Tools.Reg_solve(Tools.Reg_get(html, "元宝(?<name>.*?)上页", "name").Replace(" ", ""), "<p>(?<name>.*?)<br"); string[] name = new string[matchs.Count]; string[] id = new string[matchs.Count]; foreach (Match item in matchs) { if (item.Success) { name[i++] += item.Groups["name"].Value; } } i = 0; matchs = Tools.Reg_solve(Tools.Reg_get(html, "元宝(?<name>.*?)上页", "name").Replace(" ", ""), "goodid=(?<id>.*?)\""); foreach (Match item in matchs) { if (item.Success) { id[i++] += "物品id:" + item.Groups["id"].Value; } } for (int j = 0; j < i; j++) { result += name[j] + "\r\n" + id[j] + "\r\n"; } if (Tools.Reg_get(html, "上页</a>(?<name>.*?)/", "name").Replace(" ", "") != "") { result += "第" + Tools.Reg_get(html, "上页</a>(?<name>.*?)/", "name").Replace(" ", "") + "页,共" + Tools.Reg_get(html, "上页</a>(.*?)/(?<name>\\d+)", "name").Replace(" ", "") + "页" + "\r\n"; } else { result += "第" + Tools.Reg_get(html, "上页(?<name>.*?)/", "name").Replace(" ", "") + "页,共" + Tools.Reg_get(html, "上页(.*?)/(?<name>\\d+)", "name").Replace(" ", "") + "页" + "\r\n"; } return result + petMore; } /// <summary> /// 治疗宠物选择页面 /// </summary> /// <param name="uin"></param> /// <param name="skey"></param> /// <returns></returns> public static string CurePetSelect(string uin, string skey, string page) { string result = ""; string html = Tools.HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/phone_pet", "cmd=3&page=" + page + "&eatwash=2", uin, skey); html = html.Replace("\r", ""); html = html.Replace("\n", ""); if (html.IndexOf("手机统一登录") != -1 || html == "") return pleaseLogin; result += "我的账户:" + Tools.Reg_get(html, "我的账户:(?<name>.*?)<", "name").Replace(" ", "") + "\r\n"; int i = 0; MatchCollection matchs = Tools.Reg_solve(Tools.Reg_get(html, "元宝(?<name>.*?)上页", "name").Replace(" ", ""), "<p>(?<name>.*?)<br"); string[] name = new string[matchs.Count]; string[] id = new string[matchs.Count]; foreach (Match item in matchs) { if (item.Success) { name[i++] += item.Groups["name"].Value; } } i = 0; matchs = Tools.Reg_solve(Tools.Reg_get(html, "元宝(?<name>.*?)上页", "name").Replace(" ", ""), "goodid=(?<id>.*?)\""); foreach (Match item in matchs) { if (item.Success) { id[i++] += "物品id:" + item.Groups["id"].Value; } } for (int j = 0; j < i; j++) { result += name[j] + "\r\n" + id[j] + "\r\n"; } if (Tools.Reg_get(html, "上页</a>(?<name>.*?)/", "name").Replace(" ", "") != "") { result += "第" + Tools.Reg_get(html, "上页</a>(?<name>.*?)/", "name").Replace(" ", "") + "页,共" + Tools.Reg_get(html, "上页</a>(.*?)/(?<name>\\d+)", "name").Replace(" ", "") + "页" + "\r\n"; } else { result += "第" + Tools.Reg_get(html, "上页(?<name>.*?)/", "name").Replace(" ", "") + "页,共" + Tools.Reg_get(html, "上页(.*?)/(?<name>\\d+)", "name").Replace(" ", "") + "页" + "\r\n"; } return result + petMore; } /// <summary> /// 使用宠物物品 /// </summary> /// <param name="uin"></param> /// <param name="skey"></param> /// <returns></returns> public static string UsePet(string uin, string skey, string goodid) { string result = ""; string html = Tools.HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/phone_pet", "cmd=3&feed=3&goodid=" + goodid, uin, skey); html = html.Replace("\r", ""); html = html.Replace("\n", ""); if (html.IndexOf("手机统一登录") != -1 || html == "") return pleaseLogin; if (html.IndexOf("不合法") != -1) return "你没有这个东西,使用失败\r\n" + petMore; result += "物品使用结果:\r\n" + Tools.Reg_get(html, "值:(?<name>.*?)<br", "name").Replace(" ", "").Replace("</b>", "") + "\r\n" + petMore; return result; } /// <summary> /// 宠物学习选择页面 /// </summary> /// <param name="uin"></param> /// <param name="skey"></param> /// <returns></returns> public static string StudyPetSelect() { return "课程id:\r\n小学体育:1\r\n小学劳技:2\r\n小学武术:5\r\n小学语文:4\r\n小学数学:5\r\n小学政治:6\r\n小学美术:7\r\n小学音乐:8\r\n小学礼仪:9\r\n\r\n中学体育:10\r\n中学劳技:11\r\n中学武术:12\r\n中学语文:13\r\n中学数学:14\r\n中学政治:15\r\n中学美术:16\r\n中学音乐:17\r\n中学礼仪:18\r\n\r\n大学体育:19\r\n大学劳技:20\r\n大学武术:21\r\n大学语文:22\r\n大学数学:23\r\n大学政治:24\r\n大学美术:25\r\n大学音乐:26\r\n大学礼仪:27\r\n" + petMore; } /// <summary> /// 学习宠物课程 /// </summary> /// <param name="uin"></param> /// <param name="skey"></param> /// <returns></returns> public static string StudyPet(string uin, string skey, string classid) { string result = ""; string html = Tools.HttpGetPet("http://qqpet.wapsns.3g.qq.com/qqpet/fcgi-bin/phone_pet", "cmd=5&courseid=" + classid + "&study=2", uin, skey); html = html.Replace("\r", ""); html = html.Replace("\n", ""); if (html.IndexOf("手机统一登录") != -1 || html == "") return pleaseLogin; if (html.IndexOf("亲爱的") != -1) { result += Tools.Reg_get(html, "同学:(?<name>.*?)<", "name").Replace(" ", "") + "\r\n"; } if (html.IndexOf("您已经完成了") != -1) { result += "您已经完成了" + Tools.Reg_get(html, "您已经完成了(?<name>.*?)<", "name").Replace(" ", "") + "\r\n"; } if (html.IndexOf("你的宠物") != -1) { result += "你的宠物" + Tools.Reg_get(html, "你的宠物(?<name>.*?)<", "name").Replace(" ", "") + "\r\n"; } return "课程学习结果:\r\n" + result + petMore; } } }
4a16bf6d32ee5c0905857f71d12def03be6988db
[ "Markdown", "C#" ]
8
C#
weizai118/receiver-meow
2fba0500a4a5175b2568f346fc838ad0937ccd50
11d873983063d2d19ae45ed9fcfb69d17c6e9b86
refs/heads/main
<repo_name>MuhammadOsama320/hello<file_sep>/home/views.py from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from home.models import Entry # Create your views here. def home(request): return render(request, "home.html") def show(request): data = Entry.objects.all() return render(request, "show.html", {'data': data}) def send(request): if request.method == 'POST': ID = request.POST['id'] data1 = request.POST['data1'] data2 = request.POST['data2'] Entry(ID=ID, data1=data1, data2=data2).save() msg = "Data Stored Successfully" return render(request, "home.html", {'msg': msg}) else: return HttpResponse("<h1> 404 Error</h1>") def delete(request): ID = request.GET['id'] Entry.objects.filter(ID=ID).delete() return HttpResponseRedirect('show') def edit(request): ID = request.GET['id'] data1 = data2 = "Not_Available" for data in Entry.objects.filter(ID=ID): data1 = data.data1 data2 = data.data2 return render(request, "edit.html", {'ID': ID, 'data1': data1, 'data2': data2}) def RecordEdited(request): if request.method == 'POST': ID = request.POST['id'] data1 = request.POST['data1'] data2 = request.POST['data2'] Entry.objects.filter(ID=ID).update(data1=data2, data2=data2) return HttpResponseRedirect("show") else: return HttpResponse("<h1> 404 Error</h1>") <file_sep>/home/urls.py from django.urls import path from home import views urlpatterns = [ path('', views.home), path('show', views.show), path('send', views.send), path('delete', views.delete), path('edit', views.edit), path('RecordEdited', views.RecordEdited) ] <file_sep>/home/models.py from django.db import models # Create your models here. class Entry(models.Model): ID = models.CharField(max_length=10, primary_key=True) data1 = models.CharField(max_length=50) data2 = models.CharField(max_length=50) def __str__(self): return self.data1 <file_sep>/home/admin.py from django.contrib import admin from home.models import Entry # Register your models here. admin.site.register(Entry)
7145191b7c5b9fd840ef18d3d972487d7756539e
[ "Python" ]
4
Python
MuhammadOsama320/hello
a253f5576d6a7d1c3303c24807963d4c1dc40d5c
33f03fa71a155e63c1ce0b4241d5ba6a1c8819f1
refs/heads/master
<repo_name>heianzhihuo/deeplearning-course-project<file_sep>/model.py import torch from torchvision import transforms, models, datasets NCHW = (4,3,224,224) NUM_EPOCHS = 10 class MetricLearningNet(torch.nn.Module): def __init__(self): super(MetricLearningNet, self).__init__() self.net1 = models.resnet18() self.net2 = models.resnet18() self.net1.fc = torch.nn.Linear(512, 100) self.net2.fc = torch.nn.Linear(512, 100) self.distance = torch.nn.Linear(200, 1) def forward(self, x1, x2): feature1 = self.net1(x1) feature2 = self.net2(x2) distance = self.distance(torch.cat((feature1, feature2), 1)) return distance def main(): device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') mlnet = MetricLearningNet().to(device) x1 = torch.rand(NCHW).to(device) x2 = torch.rand(NCHW).to(device) y = torch.randint(0,2,(NCHW[0],)).to(device) criterion = torch.nn.MSELoss() optimizer = torch.optim.Adam(mlnet.parameters()) for i in range(NUM_EPOCHS): optimizer.zero_grad() distance = mlnet(x1, x2).squeeze() loss = criterion(distance, y) print(i, loss) loss.backward() optimizer.step() if __name__ == '__main__': main()<file_sep>/README.md # deeplearning-course-project 深度学习技术 课程 作业 We are trying to learn a good metric of distance between images using deep convolutional neural netowrks, which can be then applied to image classification based on the classsic knn method. #深度学习项目 数据部分 ##orls_faces文件夹是ORL face database 人脸识别数据集 the Olivetti Research Laboratory in Cambridge, UK 40个类别,每个类别10个样本 PGM格式,92x112的8位灰度图。 参考 <NAME> and <NAME> "Parameterisation of a stochastic model for human face identification" 2nd IEEE Workshop on Applications of Computer Vision December 1994, Sarasota (Florida). 链接 http://www.cl.cam.ac.uk/research/dtg/attarchive/facedatabase.html ##load_data.py load_all_data() 返回所有的数据,返回数据是list,包含40个list元素,每个list包含同一个类别的10个np.matrix(112x92,dtype=uint8) [[np.matrix(112x92),...],...]
a2aaf40958a6deeda653b6784f3d75bb03bbb082
[ "Markdown", "Python" ]
2
Python
heianzhihuo/deeplearning-course-project
3679832f20503244afb5d3100daff0a66909075c
0781bfe3df0061dcdab9a78b4555ba04286c6662
refs/heads/master
<file_sep>#include <iostream> using namespace std; class complex { int real, imaginary; public: complex() //default constructor { real = imaginary = 0; } complex(int r, int i) //parametrized constructor { real = r; imaginary = i; } complex(complex &x) //copy constructor { real = x.real; imaginary = x.imaginary; } ~complex() //destructor { cout<<"Destructor message: It is invoked\n"; } void display () //displaying value { cout<<real<<'+'<<imaginary<<'i'<<endl; // print the value } }; int main () { complex object1; complex object2 (3,7); complex object3 (object2); object1.display (); object2.display (); object3.display (); return 0; }
a12a2207494870dd0fd8731c65f4efb0040ca297
[ "C++" ]
1
C++
nilestark10/CPP-Programs
b42b795dcfd9adf042f67ee540795a01f7be5b4b
b7ae39a5198ae75c1f374c3bc4def0a0cb847b04
refs/heads/master
<file_sep>#include"scullc.h" dev_t devno; struct scullc_dev scull_dev={ .data=NULL, .size=0, .itemsize=1000 }; struct file_operations my_fops={ .owner=THIS_MODULE, .read=scullc_read, .write=scullc_write, .open=scullc_open, .release=scullc_release, .llseek=scullc_llseek }; int scullc_trim(struct scullc_dev *dev) { struct dataset *dptr,*next; printk(KERN_DEBUG"starting to trim\n"); if(dev==NULL) { printk(KERN_WARNING"dev is a nullptr!\n"); return -EINVAL; } dptr=dev->data; while(dptr) { next=dptr->next; kfree(dptr->item);//NULL指针不会进行释放 kfree(dptr); dptr=next; } printk(KERN_DEBUG"success to trim\n"); return 0; } struct dataset *scullc_follow(struct scullc_dev *dev,int n) { struct dataset *dptr; printk(KERN_DEBUG"starting to follow\n"); if(dev->data==NULL) { dev->data=kmalloc(sizeof(struct dataset),GFP_KERNEL); memset(dev->data,0,sizeof(struct dataset)); } dptr=dev->data; while(n--) { if(dptr->next==NULL) { dptr->next=kmalloc(sizeof(struct dataset),GFP_KERNEL); memset(dptr->next,0,sizeof(struct dataset)); } dptr=dptr->next; } printk(KERN_DEBUG"success to follow\n"); return dptr; } ssize_t scullc_read(struct file *filp,char *buf,size_t count,loff_t *f_pos) { struct scullc_dev *dev=filp->private_data; struct dataset *dptr; int d_pos,i_pos; printk(KERN_DEBUG"starting to read\n"); down(&lock1); if(dev->size<=*f_pos) { return 0; } if(dev->size<*f_pos+count) { count=dev->size-*f_pos; } i_pos=*f_pos%(dev->itemsize); d_pos=*f_pos/(dev->itemsize); dptr=scullc_follow(dev,d_pos); if(dptr==NULL) { printk(KERN_WARNING"dptr is a nullptr\n"); return -EFAULT; } if(dptr->item==NULL) { printk(KERN_WARNING"dptr->data is a nullptr\n"); return -EFAULT; } if(i_pos+count>dev->itemsize) { count=dev->itemsize-i_pos;//实际读的字节数 } raw_copy_to_user(buf,dptr->item+i_pos,count); *f_pos+=count; printk(KERN_DEBUG"success to read (size %ld,count %ld,f_pos %ld):\n",dev->size,count,*f_pos); return count; } ssize_t scullc_write(struct file *filp, const char *buf, size_t count,loff_t *f_pos) { struct scullc_dev *dev=filp->private_data; struct dataset *dptr; int d_pos,i_pos; printk(KERN_DEBUG"starting to write\n"); i_pos=*f_pos%(dev->itemsize); d_pos=*f_pos/(dev->itemsize); dptr=scullc_follow(dev,d_pos); if(i_pos+count>dev->itemsize) { count=dev->itemsize-i_pos;//实际写的字节数 } if(dptr->item==NULL) { dptr->item=kmalloc(dev->itemsize,GFP_KERNEL); memset(dptr->item,0,dev->itemsize); } raw_copy_from_user(dptr->item+i_pos,buf,count); *f_pos+=count; dev->size=dev->size<*f_pos?*f_pos:dev->size; printk(KERN_DEBUG"success to write (size %ld,count %ld,f_pos %ld)\n",dev->size,count,*f_pos); up(&lock1); return count; } loff_t scullc_llseek(struct file *filp,loff_t offset,int pos) { struct scullc_dev *dev=filp->private_data; loff_t retval=-EFAULT; switch(pos) { case SEEK_SET: if(offset<0) { printk(KERN_WARNING"llseek pos is wrong\n"); } else { retval=offset; filp->f_pos=retval; } break; case SEEK_CUR: if(filp->f_pos+offset<0) { printk(KERN_WARNING"llseek pos is wrong\n"); } else { retval=filp->f_pos+offset; filp->f_pos=retval; } break; case SEEK_END: if(dev->size+offset<0) { printk(KERN_WARNING"llseek pos is wrong\n"); } else { retval=dev->size+offset; filp->f_pos=retval; } break; default: printk(KERN_WARNING"llseek pos is wrong\n"); } return retval; } int scullc_open(struct inode *inode,struct file *filp) { struct scullc_dev *dev; printk(KERN_DEBUG"starting to open\n"); dev=container_of(inode->i_cdev,struct scullc_dev,cdev); filp->private_data=dev; // if((filp->f_flags&O_ACCMODE)==O_WRONLY) // { // scullc_trim(dev); // dev->data=NULL; // dev->size=0; // } printk(KERN_DEBUG"success to open\n"); return 0; } int scullc_release (struct inode *inode, struct file *filp) { printk(KERN_DEBUG"starting to release\n"); printk(KERN_DEBUG"success to release\n"); return 0; } static int scullc_init(void) { int result; printk(KERN_DEBUG"starting to init\n"); result=alloc_chrdev_region(&devno,0,4,"scullc"); if(result) { printk(KERN_WARNING"failed to alloc the dev_t\n"); return result; } printk(KERN_DEBUG"success to alloc the dev_t\n"); cdev_init(&scull_dev.cdev,&my_fops); scull_dev.cdev.owner=THIS_MODULE; result=cdev_add(&scull_dev.cdev,devno,4); if(result) { printk(KERN_WARNING"failed to adding scull_dev\n"); return result; } sema_init(&lock1,0); printk(KERN_DEBUG"success to init\n"); return 0; } static void scullc_cleanup(void) { printk(KERN_DEBUG"starting to cleanup\n"); scullc_trim(&scull_dev); cdev_del(&scull_dev.cdev); unregister_chrdev_region(devno,4); printk(KERN_DEBUG"success to cleanup\n"); } module_init(scullc_init); module_exit(scullc_cleanup); // #include"scullc.h" // dev_t devno; // struct scullc_dev scull_dev={ // .next=NULL, // .quantum=4000, // .qset=1000, // .size=0 // }; // struct file_operations my_fops={ // .owner=THIS_MODULE, // .read=scullc_read, // .write=scullc_write, // .open=scullc_open, // .release=scullc_release // }; // struct scullc_qset *scullc_follow(struct scullc_dev *dev, int n) // { // printk(KERN_DEBUG"starting to follow\n"); // if(dev->next==NULL) // { // dev->next=kmalloc(sizeof(struct scullc_qset),GFP_KERNEL); // memset(dev->next,0,sizeof(struct scullc_qset)); // } // struct scullc_qset *dptr=dev->next; // while(n--) // { // if(dptr->next==NULL) // { // dptr->next=kmalloc(sizeof(struct scullc_qset),GFP_KERNEL); // memset(dptr->next,0,sizeof(struct scullc_qset)); // } // dptr=dptr->next; // } // printk(KERN_DEBUG"success to follow\n"); // return dptr; // } // int scullc_trim(struct scullc_dev *dev) // { // printk(KERN_DEBUG"starting to trim\n"); // struct scullc_qset *dptr,*next; // int i,qset=dev->qset; // for(dptr=dev->next;dptr;dptr=next) // { // for(i=0;i<qset;++i) // { // kfree((dptr->data)[i]); // } // kfree(dptr->data); // next=dptr->next; // kfree(dptr); // } // dev->size=0; // dev->next=NULL; // printk(KERN_DEBUG"success to trim\n"); // return 0; // } // ssize_t scullc_read(struct file *filp,char *buf,size_t count,loff_t *f_pos) // { // printk(KERN_DEBUG"starting to read\n"); // struct scullc_dev *dev=filp->private_data; // struct scullc_qset *dptr; // int quantum=dev->quantum,qset=dev->qset; // int itemsize=quantum*qset; // int item,s_pos,q_pos,rest; // ssize_t retval=0; // if(*f_pos>=dev->size) // { // return retval; // } // if(*f_pos+count>dev->size) // { // count=dev->size-*f_pos; // } // item=*f_pos/itemsize; // rest=*f_pos%itemsize; // s_pos=rest/quantum; // q_pos=rest%quantum; // dptr=scullc_follow(dev,item); // printk(KERN_DEBUG"flag1\n"); // if(dptr->data==NULL||dptr->data[s_pos]==NULL) // { // return retval; // } // printk(KERN_DEBUG"flag2\n"); // if(count>quantum-q_pos) // { // count=quantum-q_pos; // } // printk(KERN_DEBUG"flag3\n"); // if(raw_copy_to_user(buf,dptr->data[q_pos],count)) // { // return 0; // } // printk(KERN_DEBUG"flag4\n"); // *f_pos+=count; // retval=count; // printk(KERN_DEBUG"success to read (size %d):\n",dev->size); // return retval; // } // ssize_t scullc_write(struct file *filp, const char *buf, size_t count,loff_t *f_pos) // { // printk(KERN_DEBUG"starting to write\n"); // struct scullc_dev *dev=filp->private_data; // struct scullc_qset *dptr; // int quantum=dev->quantum,qset=dev->qset; // int itemsize=quantum*qset; // int item,s_pos,q_pos,rest; // ssize_t retval=0; // item=*f_pos/itemsize; // rest=*f_pos%itemsize; // s_pos=rest/quantum; // q_pos=rest%quantum; // dptr=scullc_follow(dev,item); // if(dptr->data==NULL) // { // dptr->data=kmalloc(dev->qset*sizeof(char *),GFP_KERNEL); // } // if(dptr->data[s_pos]==NULL) // { // dptr->data[s_pos]=kmalloc(dev->quantum,GFP_KERNEL); // } // if(count>quantum-q_pos) // { // count=quantum-q_pos; // } // raw_copy_from_user(dptr->data[s_pos]+q_pos,buf,count); // *f_pos+=count; // retval=count; // dev->size=dev->size<*f_pos?dev->size:*f_pos; // printk(KERN_DEBUG"success to write (size %d,%d,%d):\n",dev->size,count,*f_pos); // return retval; // } // int scullc_open(struct inode *inode,struct file *filp) // { // printk(KERN_DEBUG"starting to open\n"); // struct scullc_dev *dev; // dev=container_of(inode->i_cdev,struct scullc_dev,cdev); // filp->private_data=dev; // if((filp->f_flags&O_ACCMODE)==O_WRONLY) // { // scullc_trim(dev); // } // printk(KERN_DEBUG"success to open\n"); // return 0; // } // int scullc_release (struct inode *inode, struct file *filp) // { // printk(KERN_DEBUG"starting to release\n"); // // scullc_trim((struct scullc_dev *)filp->private_data); // printk(KERN_DEBUG"start to release\n"); // return 0; // } // static int scullc_init(void) // { // int result; // printk(KERN_DEBUG"starting to init\n"); // result=alloc_chrdev_region(&devno,0,4,"scullc"); // if(result) // { // printk(KERN_WARNING"failed to alloc the dev_t\n"); // return result; // } // printk(KERN_DEBUG"success to alloc the dev_t\n"); // cdev_init(&scull_dev.cdev,&my_fops); // scull_dev.cdev.owner=THIS_MODULE; // result=cdev_add(&scull_dev.cdev,devno,4); // if(result) // { // printk(KERN_WARNING"failed to adding scull_dev\n"); // return result; // } // printk(KERN_DEBUG"success to init\n"); // return 0; // } // static void scullc_cleanup(void) // { // printk(KERN_DEBUG"starting to cleanup\n"); // scullc_trim(&scull_dev); // cdev_del(&scull_dev.cdev); // unregister_chrdev_region(devno,4); // printk(KERN_DEBUG"success to cleanup\n"); // } // module_init(scullc_init); // module_exit(scullc_cleanup); <file_sep>#!/bin/bash module="scullc" device="scullc" # remove nodes rm -f /dev/${device}[0-3] /dev/${device} # invoke rmmod with all arguments we got rmmod $module|| exit 1 exit 0 <file_sep>#include<linux/module.h> #include<linux/types.h> #include<linux/kdev_t.h> #include<linux/fs.h> #include<linux/slab.h> #include<linux/cdev.h> #include<linux/kernel.h> #include<asm/uaccess.h> #include<linux/errno.h> #include<linux/wait.h> #include<linux/semaphore.h> #include<linux/sched.h> #include<linux/sched/signal.h> #include<linux/poll.h> #define AVAIL ((dev->rpos-dev->wpos-1+dev->size)%dev->size) MODULE_AUTHOR("lhc"); MODULE_LICENSE("Dual BSD/GPL"); struct scullpipe_dev{ char *data; int rpos; int wpos; int size; struct cdev cdev; }; int scullpipe_open(struct inode *,struct file *); int scullpipe_release(struct inode*,struct file *); ssize_t scullpipe_read(struct file *,char *,size_t,loff_t *); ssize_t scullpipe_write(struct file *,const char *,size_t,loff_t *); unsigned int scullpipe_poll(struct file *,poll_table *); kuid_t uid; int ucount=0; // atomic_t avail=ATOMIC_INIT(1); spinlock_t ulock; struct semaphore rsem; struct semaphore wsem; wait_queue_head_t inq; wait_queue_head_t outq; dev_t devno; struct scullpipe_dev scull_dev={ .data=NULL, .rpos=0, .wpos=0, .size=100 }; struct file_operations my_fops={ .owner=THIS_MODULE, .read=scullpipe_read, .write=scullpipe_write, .poll=scullpipe_poll, .open=scullpipe_open, .release=scullpipe_release };<file_sep>#include<linux/ioport.h> #include<linux/slab.h> MODULE_AUTHOR("lhc"); MODULE_LICENSE("Dual BSD/GPL"); static int short_init(void) { struct resource *rs; rs=request_region(0,24,"short"); if(rs==NULL) return -1; } static int short_cleanup(void) { release_region(0,24); } module_init(&short_init); module_exit(&short_cleanup); <file_sep>#include<linux/module.h> #include<linux/types.h> #include<linux/kdev_t.h> #include<linux/fs.h> #include<linux/slab.h> #include<linux/cdev.h> #include<linux/kernel.h> #include<asm/uaccess.h> #include<linux/errno.h> #include<linux/semaphore.h> MODULE_AUTHOR("lhc"); MODULE_LICENSE("Dual BSD/GPL"); struct dataset{ char *item; struct dataset *next; }; struct scullc_dev{ struct dataset *data; int size; int itemsize; struct cdev cdev; }; struct semaphore lock1; // struct scullc_dev{ // struct scullc_qset *next; // int quantum; /* the current allocation size */ // int qset; /* the current array size */ // size_t size; /* 32-bit will suffice */ // struct semaphore sem; /* Mutual exclusion */ // struct cdev cdev; // }; // struct scullc_qset{ // char **data; // struct scullc_qset *next; // }; int scullc_open(struct inode *,struct file *); int scullc_release(struct inode*,struct file *); ssize_t scullc_read(struct file *,char *,size_t,loff_t *); ssize_t scullc_write(struct file *,const char *,size_t,loff_t *); int scullc_trim(struct scullc_dev *); struct dataset *scullc_follow(struct scullc_dev *dev,int n); loff_t scullc_llseek(struct file *,loff_t,int);<file_sep>obj-m:=scullpipe.o KERNELDIR:=/lib/modules/4.18.0-20-generic/build # KERNELDIR:=/lib/modules/2.6.23/build PWD:=$(shell pwd) modules: $(MAKE) -C $(KERNELDIR) M=$(PWD) modules modules_install: $(MAKE) -C $(KERNELDIR) M=$(PWD) modules_install<file_sep>#!/bin/bash module="scullpipe" device="scullpipe" # remove nodes rm -f /dev/${device}[0-3] /dev/${device} # invoke rmmod with all arguments we got rmmod $module|| exit 1 exit 0 <file_sep>#!/bin/bash while true do dmesg|tail -n 40 >check.out sleep 1 done<file_sep>#include<fcntl.h> #include<stdio.h> int main(int argc,char *argv[]) { int fd=open("/dev/scullc0",O_RDWR); int file=open(argv[1],O_RDWR); close(fd); close(file); return 0; }<file_sep>#include"scullpipe.h" ssize_t scullpipe_read(struct file *filp,char *buf,size_t count,loff_t *f_pos) { struct scullpipe_dev *dev=filp->private_data; int retval; if(down_interruptible(&rsem)) return -ERESTARTSYS; while(dev->size-AVAIL-1==0) { up(&rsem); DEFINE_WAIT(wait); prepare_to_wait(&inq,&wait,TASK_INTERRUPTIBLE); if(dev->size-AVAIL-1==0) schedule(); finish_wait(&inq,&wait); if(signal_pending(current)) return -ERESTARTSYS; if(down_interruptible(&rsem)) return -ERESTARTSYS; } printk(KERN_DEBUG"starting to read%d,%d,%d,%d\n",current->pid,dev->rpos,dev->wpos,AVAIL); if(count>dev->size-AVAIL-1) count=dev->size-AVAIL-1; retval=count; if(dev->rpos<dev->wpos) { raw_copy_to_user(buf,dev->data+dev->rpos,count); dev->rpos+=count; } else { if(dev->size-dev->rpos<=count) { count-=dev->size-dev->rpos; raw_copy_to_user(buf,dev->data+dev->rpos,dev->size-dev->rpos); if(count) { raw_copy_to_user(buf+dev->size-dev->rpos,dev->data,count); dev->rpos=count; } else dev->rpos=0; } else { raw_copy_to_user(buf,dev->data+dev->rpos,count); dev->rpos+=count; } } printk(KERN_DEBUG"%s\n",dev->data); printk(KERN_DEBUG"success to read%d,%d,%d,%d\n",current->pid,dev->rpos,dev->wpos,AVAIL); up(&rsem); wake_up_interruptible(&outq); return retval; } ssize_t scullpipe_write(struct file *filp, const char *buf, size_t count,loff_t *f_pos) { struct scullpipe_dev *dev=filp->private_data; int retval; unsigned long end_time; unsigned long start_time=jiffies; unsigned long wait_time=jiffies+5*HZ; wait_event_interruptible_timeout(outq,0,5*HZ); if(down_interruptible(&wsem)) return -ERESTARTSYS; while(AVAIL==0) { up(&wsem); DEFINE_WAIT(wait); prepare_to_wait(&outq,&wait,TASK_INTERRUPTIBLE); if(AVAIL==0) schedule(); finish_wait(&outq,&wait); if(signal_pending(current)) return -ERESTARTSYS; if(down_interruptible(&wsem)) return -ERESTARTSYS; } printk(KERN_DEBUG"starting to write%d,%d,%d,%d\n",current->pid,dev->rpos,dev->wpos,AVAIL); if(AVAIL<count) count=AVAIL; retval=count; if(dev->wpos>=dev->rpos) { if(dev->size-dev->wpos<=count) { count-=dev->size-dev->wpos; raw_copy_from_user(dev->data+dev->wpos,buf,dev->size-dev->wpos); if(count) { raw_copy_from_user(dev->data,buf+dev->size-dev->wpos,count); dev->wpos=count; } else dev->wpos=0; } else { raw_copy_from_user(dev->data+dev->wpos,buf,count); dev->wpos+=count; } } else { raw_copy_from_user(dev->data+dev->wpos,buf,count); dev->wpos+=count; } printk(KERN_DEBUG"%s\n",dev->data); printk(KERN_DEBUG"success to write%d,%d,%d,%d\n",current->pid,dev->rpos,dev->wpos,AVAIL); up(&wsem); wake_up_interruptible(&inq); end_time=jiffies; printk(KERN_DEBUG"time cost is %ds\n",(end_time-start_time)/HZ); return retval; } unsigned int scullpipe_poll(struct file *filp,poll_table *wait) { struct scullpipe_dev *dev=filp->private_data; unsigned int mask=0; down_interruptible(&rsem); down_interruptible(&wsem); poll_wait(filp,&inq,wait); poll_wait(filp,&outq,wait); if(dev->rpos!=dev->wpos) mask|=POLLIN|POLLRDNORM; if(AVAIL!=0) mask|=POLLOUT|POLLWRNORM; up(&wsem); up(&rsem); return mask; } int scullpipe_open(struct inode *inode,struct file *filp) { struct scullpipe_dev *dev; printk(KERN_DEBUG"starting to open\n"); // if(!atomic_dec_and_test(&avail)) // { // atomic_inc(&avail); // printk(KERN_DEBUG"failed to open\n"); // return -EBUSY; // } spin_lock(&ulock); if(ucount) { if(uid.val!=current->cred->euid.val&&uid.val!=current->cred->uid.val&&!capable(CAP_DAC_OVERRIDE)) { printk(KERN_DEBUG"failed to open\n"); spin_unlock(&ulock); return -EBUSY; } } else { uid=current->cred->euid; } ucount++; spin_unlock(&ulock); dev=container_of(inode->i_cdev,struct scullpipe_dev,cdev); filp->private_data=dev; printk(KERN_DEBUG"success to open\n"); return 0; } int scullpipe_release (struct inode *inode, struct file *filp) { printk(KERN_DEBUG"starting to release\n"); spin_lock(&ulock); ucount--; spin_unlock(&ulock); // atomic_inc(&avail); printk(KERN_DEBUG"success to release\n"); return 0; } static int __init scullpipe_init(void) { int result,i; printk(KERN_DEBUG"starting to init\n"); result=alloc_chrdev_region(&devno,0,4,"scullpipe"); if(result) { printk(KERN_WARNING"failed to alloc the dev_t\n"); return result; } printk(KERN_DEBUG"success to alloc the dev_t\n"); cdev_init(&scull_dev.cdev,&my_fops); scull_dev.cdev.owner=THIS_MODULE; result=cdev_add(&scull_dev.cdev,devno,4); if(result) { printk(KERN_WARNING"failed to adding scull_dev\n"); return result; } scull_dev.data=kmalloc(scull_dev.size+1,GFP_KERNEL); if(scull_dev.data==NULL) return -EFAULT; for(i=0;i<100;++i) scull_dev.data[i]='0'; scull_dev.data[100]=0; init_waitqueue_head(&inq); init_waitqueue_head(&outq); spin_lock_init(&ulock); sema_init(&rsem,1); sema_init(&wsem,1); printk(KERN_DEBUG"success to init\n"); return 0; } static void __exit scullpipe_cleanup(void) { printk(KERN_DEBUG"starting to cleanup\n"); kfree(scull_dev.data); cdev_del(&scull_dev.cdev); unregister_chrdev_region(devno,4); printk(KERN_DEBUG"success to cleanup\n"); } module_init(scullpipe_init); module_exit(scullpipe_cleanup); <file_sep>#!/bin/bash count=0 while [ $count -ne 20 ] do echo -n hello >/dev/scullpipe0 done echo -n hello >/dev/scullpipe0 >check.out while true do if isavail /dev/scullpipe0 r then get /dev/scullpipe0 10 0 0 >>check.out fi sleep 1 done
da3e37e8a69a042b0e9a1afb0913210973e3e828
[ "C", "Makefile", "Shell" ]
11
C
lhcmaple/mydriver
945cbd4582480f67cafd5e2fd1d9f9ad9b54c594
9d9b67f6ec1886fd7450b2e4d891cbb2d7726093
refs/heads/master
<repo_name>davidccs/C<file_sep>/listIteratorInt.c /* listIteratorInt.c ... list Iterator ADT implementation Written by <NAME> Date: 14/3/2017 */ #include <stdlib.h> #include <stdio.h> #include <assert.h> #include "listIteratorInt.h" #define TRUE 1 #define FALSE 0 typedef struct node *Node; // doubly link list typedef struct node { int value; // stores value inside Node next; // next pointer Node prev; // previous pointer } node; typedef struct IteratorIntRep { Node before; // previous cursor Node after; // next cursor Node reset; // keeps track of the start of the list Node lastAccessed; // keeps track of the last value accessed int callAccessed; // checks add, set, delete have been accessed } IteratorIntRep; static Node newNode(int data); // creates a new node Node newNode(int data){ Node new = malloc(sizeof(struct node)); assert(new != NULL); new->next = NULL; new->prev = NULL; new->value = data; return new; } //Creates a new list iterator IteratorInt IteratorIntNew(){ IteratorInt new = malloc(sizeof(struct IteratorIntRep)); assert (new != NULL); new->before = NULL; new->after = NULL; new->reset = NULL; new->lastAccessed = NULL; new->callAccessed = FALSE; return new; } //Resets it to the start of the list. void reset(IteratorInt it){ Node temp = it->before; // this case is only if the list is NOT empty // sets it to the beginning if (it->before != NULL){ while (temp->prev != NULL){ temp = temp->prev; } it->after = temp; it->before = NULL; } else { it->before = NULL; it->after = it->reset; } } int add(IteratorInt it, int v){ Node new; Node temp; Node hold; new = newNode(v); int fact = FALSE; // if list is empty if (it->after == NULL && it->before == NULL){ it->after = NULL; it->before = new; it->reset = new; // points to the first node created fact = TRUE; // // insert at the end } else if (it->after == NULL){ temp = it->before; temp->next = new; new->prev = temp; it->before = new; it->after = NULL; fact = TRUE; // inserting at the front } else if (it->before == NULL){ temp = it->after; new->next = temp; temp->prev = new; it->before = new; it->after = new->next; it->reset = new; fact = TRUE; // inserting inbetwen nodes } else { temp = it->before; hold = it->after; temp->next = new; new->prev = temp; hold->prev = new; new->next = hold; it->before = new; fact = TRUE; } it->callAccessed = FALSE; it->lastAccessed = new; return fact; } int hasNext(IteratorInt it){ int fact = FALSE; // checks if after pointer is NULL if (it->after != NULL){ fact = TRUE; } else { fact = FALSE; } return fact; } int hasPrevious(IteratorInt it){ int fact = 0; // checks if previous pointer is NULL if (it->before != NULL){ fact = TRUE; } else { fact = FALSE; } return fact; } int *next(IteratorInt it){ int *ptr = NULL; // check if next node is not NULL if (it->after != NULL ){ ptr = &(it->after->value); it->before = it->after; it->after = it->after->next; it->callAccessed = TRUE; // if the after node IS NULL } else { it->callAccessed = FALSE; ptr = NULL; } // save the returned value if (ptr != NULL) it->lastAccessed = it->before; return ptr; } int *previous(IteratorInt it){ int *ptr = NULL; if (it->before != NULL){ ptr = &(it->before->value); it->after = it->before; it->before = it->before->prev; it->callAccessed = TRUE; // before pointer DOES point at NULL } else { it->callAccessed = FALSE; ptr = NULL; } // save the returned value if (ptr != NULL) it->lastAccessed = it->after; return ptr; } int delete(IteratorInt it){ int fact = FALSE; // checks next,previous has been successful if (it->callAccessed == TRUE){ Node temp = it->lastAccessed; // empty list if (it->lastAccessed == NULL){ fact = FALSE; // deleting one node } else if (it->lastAccessed->next == NULL && it->lastAccessed->prev == NULL){ it->before = NULL; it->after = NULL;; it->reset = NULL; free(temp); //it->lastAccessed = NULL; // deleting node at the front of the list } else if (it->lastAccessed->next != NULL && it->lastAccessed->prev == NULL){ it->reset = it->lastAccessed->next; it->after = it->lastAccessed->next; Node point = it->after; point->prev = NULL; it->before = NULL; free(temp); //it->lastAccessed = NULL; // deleting at the end of list } else if (it->lastAccessed->next == NULL && it->lastAccessed->prev != NULL){ it->before = it->lastAccessed->prev; Node point = it->before; it->after = NULL; point->next = NULL; free(temp); //it->lastAccessed = NULL; // deleting inbetween } else { Node tempPrev = it->lastAccessed->prev; Node tempNext = it->lastAccessed->next; tempPrev->next = tempNext; tempNext->prev = tempPrev; it->after = tempNext; it->before = tempPrev; free(temp); //it->lastAccessed = NULL; } fact = TRUE; } else { fact = FALSE; } it->callAccessed = FALSE; return fact; } int set(IteratorInt it, int v){ int fact = FALSE; // checks if next/prev && set is correct // also fix up reset function if (it->callAccessed == TRUE){ it->lastAccessed->value = v; fact = TRUE; } else { fact = FALSE; } // ensures delete/set cannot be called CONSECUTIVELY it->callAccessed = FALSE; return fact; } int *findNext(IteratorInt it, int v){ int *ptr = NULL; if (it->after != NULL){ // searches for a node equal to v while (it->lastAccessed->value != v && it->lastAccessed->next != NULL){ it->lastAccessed = it->lastAccessed->next; } it->after = it->lastAccessed->next; it->before = it->lastAccessed; it->callAccessed = TRUE; // v does not match } else { it->callAccessed = FALSE; ptr = NULL; } // resets call if (ptr != NULL) it->lastAccessed = it->before; return ptr; } int *findPrevious(IteratorInt it, int v){ int *ptr = NULL; if (it->before != NULL){ // searches for a node equal to v while (it->lastAccessed->value != v && it->lastAccessed->prev != NULL){ it->lastAccessed = it->lastAccessed->prev; } it->after = it->lastAccessed; it->before = it->lastAccessed->prev; it->callAccessed = TRUE; // if v does not match } else { it->callAccessed = FALSE; ptr = NULL; } // resets the calls if (ptr != NULL) it->lastAccessed = it->after; return ptr; } <file_sep>/testListIteratorInt.c /* client to test listIteratorInt. Written by .... */ #include <stdlib.h> #include <stdio.h> #include <assert.h> #include <string.h> #include "listIteratorInt.h" int main(int argc, char *argv[]){ //IteratorInt newList = IteratorIntNew(); /* printf("No Nodes\n"); printf("====Before Result========\n"); print(newList); delete(newList); printf("====After Result=========\n"); print(newList); printf("========PASSED===========\n"); printf("\n"); printf("One Node\n"); printf("====Before Result========\n"); add(newList,30); previous(newList); print(newList); delete(newList); printf("====After Result=========\n"); print(newList); printf("========PASSED===========\n"); */ /* printf("\n"); printf("Deleting Front Node\n"); printf("====Before Result========\n"); add(newList,30); add(newList,40); add(newList,20); previous(newList); previous(newList); previous(newList); print(newList); delete(newList); printf("====After Result=========\n"); print(newList); printf("========PASSED===========\n"); */ /* printf("\n"); printf("Deleting End Node\n"); printf("====Before Result========\n"); add(newList,30); add(newList,40); add(newList,20); previous(newList); next(newList); print(newList); delete(newList); printf("====After Result=========\n"); print(newList); printf("========PASSED===========\n"); */ /*printf("\n"); printf("Deleting Inbetween Node\n"); printf("====Before Result========\n"); add(newList,30); add(newList,40); add(newList,20); previous(newList); previous(newList); print(newList); delete(newList); printf("====After Result=========\n"); print(newList); printf("========PASSED===========\n"); */ /* add(newList, 30); add(newList, 40); add(newList, 35); add(newList, 24); previous(newList); previous(newList); previous(newList); previous(newList); printPointer(newList); print(newList); findNext(newList, 25); */ //printPointer(newList); //previous(newList); //delete(newList); //assert(delete(newList) == 1); /*printPointer(newList); print(newList); reset(newList); printPointer(newList); */ //printPointer(newList); /*next(newList); next(newList); next(newList); previous(newList); delete(newList); print(newList); delete(newList); add(newList,5); previous(newList); previous(newList); set(newList, 69); print(newList); delete(newList); print(newList); */ /*delete(newList); printPointer(newList); //set(newList,20); printPointer(newList); print(newList); */ /*add(newList, 20); add(newList, 12); add(newList, 33); add(newList, 25); print(newList); previous(newList); previous(newList); printf("lemao\n"); next(newList); delete(newList); printf("hello\n"); previous(newList); printf("OK\n"); print(newList); printf("\n"); printPointer(newList); */ printf("ALL TEST PASSED YOU ARE AWESOME!\n"); return EXIT_SUCCESS; } <file_sep>/README.md # C C code Programs
7805ea8f37f69c8caa1bc9585a7d7a873d911671
[ "Markdown", "C" ]
3
C
davidccs/C
9dfa6229e9fd5c8641e83389f7ebb89b16abc8e2
bc54d36e3b6b7edda4d94ebb947bc412f583a811
refs/heads/master
<repo_name>miolfo/file-line-calculator<file_sep>/line-calculator.py import os import argparse def calculate_lines(path, extension): dirs = os.listdir(path) linecount = 0 for dir in dirs: if os.path.isfile(os.path.join(path, dir)): linecount += get_lines_in_file(path, dir) return linecount def calculate_lines_recursive(path, extension): linecount = 0 for root, _, files in os.walk(path): for file in files: if not extension: linecount += get_lines_in_file(root, file) else: _, file_extension = os.path.splitext(file) if file_extension == extension: linecount += get_lines_in_file(root, file) return linecount def get_lines_in_file(path, file_name): with open(os.path.join(path, file_name)) as file: try: lines = file.readlines() return len(lines) except UnicodeDecodeError: return 0 if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("-p", "--path", dest="path", help="Path from which to start line calculation") parser.add_argument("-r", "--recursive", dest="recursive", help="Recurse through all folders in specified folder", action="store_true") parser.add_argument("-e", "--file-ending", dest="file_ending", help="Only calculate files of this extension") args = parser.parse_args() path = os.getcwd() if(args.path): path = args.path if args.recursive: count = calculate_lines_recursive(path, args.file_ending) print("Line count (recursively) in {0} is {1}".format(path, str(count))) else: count = calculate_lines(path, args.file_ending) print("Line count in {0} is {1}".format(path, str(count)))
14ea253853597243bdaadce87897740c61c10375
[ "Python" ]
1
Python
miolfo/file-line-calculator
59358cbb7af88c060fba5320879fe21c07dee7d3
e9604ecee76349698f331812b3d2a6c90ee16d49
refs/heads/main
<file_sep>package test; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ FigurasTest.class, FigurasTestParametrizada.class }) public class FigurasTestSuit { } <file_sep>package figuras; public class Main { public static void main(String[] args) { // Area y perimetro del circulo. Area area = new Area(); Perimetro perimetro = new Perimetro(); double acirculo = area.circulo(5); double pcirculo = perimetro.circulo(5); System.out.println("Area: " + acirculo + " Perimetro: " + pcirculo); } } <file_sep>package figuras; public class Area { public static double cuadrado(int lado) { return Math.pow(lado, 2); } public static double triangulo(int base, int altura) { return (base*altura)/2; } public static int rectangulo(int base, int altura) { return base*altura; } public static double circulo(int radio) { return Math.PI * Math.pow(radio, 2); } public static double rombo(int diagonalMenor, int diagonalMayor) { return (diagonalMenor*diagonalMayor)/2; } public static double pentagono(int lado, int apotema) { return (5*lado*apotema)/2; } public static double hexagono(int lado, int apotema) { return 3*lado*apotema; } public static double elipse(int semieje1, int semieje2) { return Math.PI * semieje1 * semieje2; } public static int trapecio(int baseMayor, int baseMenor, int altura) { return ((baseMayor+baseMenor)*altura)/2; } public static int romboide(int base, int altura) { return base*altura; } } <file_sep>package test; import static org.junit.Assert.*; import java.util.Arrays; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized.Parameters; import figuras.Area; import org.junit.runners.Parameterized; @RunWith(value = Parameterized.class) public class FigurasTestParametrizada { @Parameters public static Iterable<Object[]> getData() { return Arrays.asList(new Object[][] { {5, 2, 10}, {10, 4, 40}, {15, 2, 30}, {10, 2, 20}, {8, 2, 16}, {30, 4, 120} }); } private int base, altura, exp; public FigurasTestParametrizada (int base, int altura, int exp) { this.base = base; this.altura = altura; this.exp = exp; } @Test public void testAreaRectangulo() { // Test area (base*altura). int resultado = Area.rectangulo(base, altura); assertEquals(exp, resultado); } }<file_sep>package figuras; public class Perimetro { int total; public static int cuadrado(int lado) { return 4 * lado; } public static int triangulo(int lado1, int lado2, int lado3) { return lado1 + lado2 + lado3; } public static int rectangulo(int base, int altura) { return 2 * base + 2 * altura; } public static double circulo(int radio) { return 2 * Math.PI * radio; } public static int rombo(int lado) { return 4 * lado; } public static int pentagono(int lado) { return 5 * lado; } public static int hexagono(int lado) { return 6 * lado; } public static double elipse(int semiejeMenor, int semiejeMayor) { return Math.PI * 2 * Math.sqrt((Math.pow(semiejeMenor, 2) + Math.pow(semiejeMayor, 2)) / 2); } public static int trapecio(int lado1, int lado2, int lado3, int lado4) { return lado1 + lado2 + lado3 + lado4; } public static int romboide(int base, int altura) { return 2 * base + 2 * altura; } public static int dividirPerimetros(int perimetro1, int perimetro2) { return perimetro1/perimetro2; } public static int dividirPerimetrosLento(int perimetro1, int perimetro2) { try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return perimetro1/perimetro2; } }
66d1911fbc6a04ed48925932f8bcadf55f60b674
[ "Java" ]
5
Java
antonio-sanchezz/JUnit04
7901a297f7ae714bf260a00c1ebe57d62a6f2eca
9b1bebe81916b83819a4c03fc8f4e00621c853c2
refs/heads/master
<file_sep># astar-core #### Description A-Star algorithm #### Installation ```sh npm install astar-core --save or yarn add astar-core ``` ### Usage ```js import AStarCore from "astar-core"; const { AStar, Graph } = AStarCore; // map size equals 【gridSize x gridSize】 const gridSize = 10; // decide how many walls in map const wallFrequency = 0.1; // wall flag const WALL = 0; // road flag const ROAD = 1; // 2 D arrays to store all nodes const nodes = []; // generate all nodes in map for (let x = 0; x < gridSize; x++) { const nodeRow = []; for (let y = 0; y < gridSize; y++) { const isWall = Math.floor(Math.random() * (1 / wallFrequency)); if (isWall === WALL) { nodeRow.push(WALL); } else { nodeRow.push(ROAD); } } nodes.push(nodeRow); } // start node const start = nodes[0][0]; // end node const end = nodes[gridSize - 1][gridSize - 1]; // graph options // diagonal: specifies whether diagonal moves are allowed. const graphOptions = { diagonal: false }; // create a map data const graph = new Graph(nodes, graphOptions); // a-star options // closest: specifies whether to return the path to the closest node if the target is unreachable. // heuristic: Heuristic function (see AStarCore.Heuristics). const astarOptions = { closest: false, heuristic: null }; // use a-star algorithm to search the shortest path. // it will return the path from start to end. const path = AStar.search(graph, start, end, astarOptions); ```<file_sep>import GridNode from './GridNode'; import AStar from './AStar'; /** * @name Graph * @description 地图 */ export default class Graph { /** * @name nodes * @description 节点集合 */ private nodes: Array<GridNode>; /** * @name grid * @description 网格,二维的节点集合 */ private grid: Array<Array<GridNode>>; /** * @name diagonal * @description 标识是否可以对角移动 */ private diagonal: boolean; /** * @name dirtyNodes * @description 脏节点集合 */ private dirtyNodes: Array<GridNode>; constructor(gridIn: Array<Array<number>>, options: any) { options = options || {}; this.nodes = []; this.diagonal = !!options.diagonal; this.grid = []; for (let x = 0; x < gridIn.length; x++) { this.grid[x] = []; for (let y = 0, row = gridIn[x]; y < row.length; y++) { const node = new GridNode(x, y, row[y]); this.grid[x][y] = node; this.nodes.push(node); } } this.init(); } /** * @name init * @description 初始化 * @returns {void} */ public init(): void { this.dirtyNodes = []; for (let i = 0; i < this.nodes.length; i++) { AStar.cleanNode(this.nodes[i]); } } /** * @name cleanDirty * @description 清理脏节点集合 * @returns {void} */ public cleanDirty(): void { for (let i = 0; i < this.dirtyNodes.length; i++) { AStar.cleanNode(this.dirtyNodes[i]); } this.dirtyNodes = []; } /** * @name markDirty * @description 加入脏节点集合 * @param node 节点 * @returns {void} */ public markDirty(node: GridNode): void { this.dirtyNodes.push(node); } /** * @name neighbors * @description 获取某一节点的所有相邻节点 * @param node 节点 * @returns {Array<GridNode>} 所有相邻节点 */ public neighbors(node: GridNode): Array<GridNode> { const ret = []; const x = node.x; const y = node.y; const grid = this.grid; // 左 if (grid[x - 1] && grid[x - 1][y]) { ret.push(grid[x - 1][y]); } // 右 if (grid[x + 1] && grid[x + 1][y]) { ret.push(grid[x + 1][y]); } // 下 if (grid[x] && grid[x][y - 1]) { ret.push(grid[x][y - 1]); } // 上 if (grid[x] && grid[x][y + 1]) { ret.push(grid[x][y + 1]); } // 如果允许对角移动,则将相邻四个对角的节点也加进来 if (this.diagonal) { // 左下 if (grid[x - 1] && grid[x - 1][y - 1]) { ret.push(grid[x - 1][y - 1]); } // 右下 if (grid[x + 1] && grid[x + 1][y - 1]) { ret.push(grid[x + 1][y - 1]); } // 左上 if (grid[x - 1] && grid[x - 1][y + 1]) { ret.push(grid[x - 1][y + 1]); } // 右上 if (grid[x + 1] && grid[x + 1][y + 1]) { ret.push(grid[x + 1][y + 1]); } } return ret; } /** * @name toString * @description 格式化字符串 */ public toString(): string { const graphString = []; const nodes = this.grid; for (let x = 0; x < nodes.length; x++) { const rowDebug = []; const row = nodes[x]; for (let y = 0; y < row.length; y++) { rowDebug.push(row[y].weight); } graphString.push(rowDebug.join(' ')); } return graphString.join('\n'); } } <file_sep>/** Declaration file generated by dts-gen */ export = astar_core; interface IGridNode { /** * @name x * @description X坐标 */ x: number; /** * @name y * @description Y坐标 */ y: number; /** * @name x * @description 权重 */ weight: number; /** * @name f * @description 综合优先级 */ f: number; /** * @name n * @description 节点距离起点的代价 */ g: number; /** * @name h * @description 节点距离终点的预计代价 */ h: number; /** * @name visited * @description 节点是否被访问过 */ visited: boolean; /** * @name closed * @description 节点是否在关闭列表 */ closed: boolean; /** * @name parent * @description 路径上的父节点 */ parent: IGridNode; /** * @name toString * @description 格式化字符串 * @returns {string} */ toString(): string; /** * @name getCost * @description 获取权重 * @param fromNeighbor 相邻节点 * @returns {number} */ getCost(fromNeighbor: IGridNode): number; /** * @name isWall * @description 是否是墙 * @returns {boolean} */ isWall(): boolean; } interface IGraph { /** * @name nodes * @description 节点集合 */ nodes: Array<IGridNode>; /** * @name grid * @description 网格,二维的节点集合 */ grid: Array<Array<IGridNode>>; /** * @name diagonal * @description 标识是否可以对角移动 */ diagonal: boolean; /** * @name dirtyNodes * @description 脏节点集合 */ dirtyNodes: Array<IGridNode>; /** * @name init * @description 初始化 * @returns {void} */ init(): void; /** * @name cleanDirty * @description 清理脏节点集合 * @returns {void} */ cleanDirty(): void; /** * @name markDirty * @description 加入脏节点集合 * @param node 节点 * @returns {void} */ markDirty(node: IGridNode): void; /** * @name neighbors * @description 获取某一节点的所有相邻节点 * @param node 节点 * @returns {Array<IGridNode>} 所有相邻节点 */ neighbors(node: IGridNode): Array<IGridNode>; /** * @name toString * @description 格式化字符串 */ toString(): string; } interface IAstar { cleanNode(node: IGridNode): void; search (graph: IGraph, start: IGridNode, end: IGridNode, options:any): Array<IGridNode> } declare const astar_core: { default: { AStar: IAstar; Graph: IGraph; GridNode: IGridNode; Heuristics: { diagonal: Function; manhattan: Function; }; }; }; <file_sep>"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const BinaryHeap_1 = require("./BinaryHeap"); function pathTo(node) { let curr = node; const path = []; while (curr.parent) { path.unshift(curr); curr = curr.parent; } return path; } exports.Heuristics = { manhattan: function (pos0, pos1) { var d1 = Math.abs(pos1.x - pos0.x); var d2 = Math.abs(pos1.y - pos0.y); return d1 + d2; }, diagonal: function (pos0, pos1) { var D = 1; var D2 = Math.sqrt(2); var d1 = Math.abs(pos1.x - pos0.x); var d2 = Math.abs(pos1.y - pos0.y); return (D * (d1 + d2)) + ((D2 - (2 * D)) * Math.min(d1, d2)); } }; class AStar { static cleanNode(node) { node.f = 0; node.g = 0; node.h = 0; node.visited = false; node.closed = false; node.parent = null; } static search(graph, start, end, options) { graph.cleanDirty(); options = options || {}; const heuristic = options.heuristic || exports.Heuristics.manhattan; const closest = options.closest || false; const openHeap = new BinaryHeap_1.default(function (node) { return node.f; }); let closestNode = start; start.h = heuristic(start, end); graph.markDirty(start); openHeap.push(start); let iterNum = 0; const neighborNodes = new Map(); const currentNodes = new Map(); while (openHeap.size() > 0) { let currentNode = openHeap.pop(); if (currentNode === end) { const result = { path: pathTo(currentNode), currentNodes, neighborNodes, }; return result; } currentNode.closed = true; const neighbors = graph.neighbors(currentNode); for (var i = 0, il = neighbors.length; i < il; ++i) { const neighbor = neighbors[i]; if (neighbor.closed || neighbor.isWall()) { continue; } const gScore = currentNode.g + neighbor.getCost(currentNode); const beenVisited = neighbor.visited; if (!beenVisited || gScore < neighbor.g) { neighbor.visited = true; neighbor.parent = currentNode; neighbor.h = neighbor.h || heuristic(neighbor, end); neighbor.g = gScore; neighbor.f = neighbor.g + neighbor.h; graph.markDirty(neighbor); if (closest) { if (neighbor.h < closestNode.h || (neighbor.h === closestNode.h && neighbor.g < closestNode.g)) { closestNode = neighbor; } } if (!beenVisited) { openHeap.push(neighbor); } else { openHeap.rescoreElement(neighbor); } } } neighborNodes[iterNum] = neighbors; currentNodes[iterNum] = currentNode; iterNum++; } if (closest) { const result = { path: pathTo(closestNode), currentNodes, neighborNodes, }; return result; } const result = { path: [], currentNodes, neighborNodes, }; return result; } } exports.default = AStar; <file_sep>import AStar, { Heuristics } from './AStar'; import Graph from './Graph'; import GridNode from './GridNode'; export default { AStar, Graph, GridNode, Heuristics, }<file_sep>import GridNode from './GridNode'; export default class BinaryHeap { /** * @name items * @description 数组 */ public items: Array<GridNode>; /** * @name scoreFunction * @description 得分函数 */ private scoreFunction: Function; /** * @description 构造函数 * @param scoreFunction 得分函数 */ constructor(scoreFunction: Function) { this.items = []; this.scoreFunction = scoreFunction; } public push(node: GridNode): void { // 将新元素添加到数组尾部 this.items.push(node); // 允许它下沉. this.sinkDown(this.items.length - 1); } public pop(): GridNode { // 第一个元素 const first = this.items[0]; // 获取数组尾部的元素 const end = this.items.pop(); // 如果数组中还有元素,将尾部元素放到起始位置,让其冒泡 if (this.items.length > 0) { this.items[0] = end; this.bubbleUp(0); } return first; } public remove(node: GridNode): void { const i = this.items.indexOf(node); // 找到后重复填充 const end = this.items.pop(); if (i !== this.items.length - 1) { this.items[i] = end; if (this.scoreFunction(end) < this.scoreFunction(node)) { this.sinkDown(i); } else { this.bubbleUp(i); } } } public size(): number { return this.items.length; } public rescoreElement(node: GridNode): void { this.sinkDown(this.items.indexOf(node)); } public sinkDown(n: number): void { // 获取被下沉的元素 const element = this.items[n]; // 如果n为0,元素不能再被下沉 while (n > 0) { // 计算父节点的位置并获取 const parentN = ((n + 1) >> 1) - 1; const parent = this.items[parentN]; // 如果父节点得分更高,则交换元素位置 if (this.scoreFunction(element) < this.scoreFunction(parent)) { this.items[parentN] = element; this.items[n] = parent; // 更新n,继续下一次新的位置 n = parentN; } else { // 父节点无需再下沉 break; } } } public bubbleUp(n: number): void { // 查找目标元素及其得分 const length = this.items.length; const element = this.items[n]; const elemScore = this.scoreFunction(element); while (true) { // 计算子节点位置 const child2N = (n + 1) << 1; const child1N = child2N - 1; // 这用于存储元素的新位置 let swap = null; let child1Score: number = 0; // 如果第一个子元素存在 if (child1N < length) { // 获取并计算其得分 const child1 = this.items[child1N]; child1Score = this.scoreFunction(child1); // 如果得分小于当前元素,则需要交换第一个子节点 if (child1Score < elemScore) { swap = child1N; } } // 对第二个子节点使用同样的方式 if (child2N < length) { const child2 = this.items[child2N]; const child2Score = this.scoreFunction(child2); // 如果得分小于此时得分小的元素(前一次判断出来了),则需要交换为第二个子节点 if (child2Score < (swap === null ? elemScore : child1Score)) { swap = child2N; } } // 交换节点 if (swap !== null) { this.items[n] = this.items[swap]; this.items[swap] = element; n = swap; } else { break; } } } }<file_sep>import GridNode from './GridNode'; import Graph from './Graph'; import BinaryHeap from './BinaryHeap'; /** * @name pathTo * @description 到对应节点位置的路径 * @param node 节点 * @returns 路径数组 */ function pathTo(node: GridNode): Array<GridNode> { let curr = node; const path = []; while (curr.parent) { path.unshift(curr); curr = curr.parent; } return path; } export interface AStarResult { path: Array<GridNode>; currentNodes: Map<number, GridNode>; neighborNodes: Map<number, Array<GridNode>>; } /** * @name Heuristics * @description 启发式算法 manhattan-曼哈顿距离,diagonal-对角距离 */ export const Heuristics = { manhattan: function(pos0: GridNode, pos1: GridNode): number { var d1 = Math.abs(pos1.x - pos0.x); var d2 = Math.abs(pos1.y - pos0.y); return d1 + d2; }, diagonal: function(pos0: GridNode, pos1: GridNode): number { var D = 1; var D2 = Math.sqrt(2); var d1 = Math.abs(pos1.x - pos0.x); var d2 = Math.abs(pos1.y - pos0.y); return (D * (d1 + d2)) + ((D2 - (2 * D)) * Math.min(d1, d2)); } } /** * AStar算法 */ export default class AStar { /** * @name cleanNode * @description 清理节点数据 * @param node 节点 * @returns {void} */ public static cleanNode(node: GridNode): void { node.f = 0; node.g = 0; node.h = 0; node.visited = false; node.closed = false; node.parent = null; } /** * @name search * @description 开始搜索最短路径 * @param graph 图 * @param start 起始节点 * @param end 终点节点 * @param options 配置 */ public static search (graph: Graph, start: GridNode, end: GridNode, options:any): AStarResult { graph.cleanDirty(); options = options || {}; // 启发算法,默认用曼哈顿距离作为启发算法 const heuristic = options.heuristic || Heuristics.manhattan; // 如果目标节点不可达,是否返回最接近目标的节点 const closest = options.closest || false; const openHeap = new BinaryHeap(function(node: GridNode) { return node.f; }); // 将起始节点作为当前最近节点 let closestNode = start; start.h = heuristic(start, end); graph.markDirty(start); openHeap.push(start); let iterNum = 0; const neighborNodes: Map<number, Array<GridNode>> = new Map(); const currentNodes: Map<number, GridNode> = new Map(); while (openHeap.size() > 0) { // 取对顶元素,也就是F最小的。堆帮我们排好序了 let currentNode = openHeap.pop(); // 如果当前节点是终点,则返回路径 if (currentNode === end) { const result: AStarResult = { path: pathTo(currentNode), currentNodes, neighborNodes, }; return result; } // 将当前节点放入关闭列表,这里用的是closed标志,然后处理其他相邻节点 currentNode.closed = true; // 找到当前节点的所有相邻节点 const neighbors = graph.neighbors(currentNode); for (var i = 0, il = neighbors.length; i < il; ++i) { const neighbor = neighbors[i]; if (neighbor.closed || neighbor.isWall()) { // 如果这个相邻节点在关闭列表或者是墙,则跳过处理下一个 continue; } // g为节点到起点的最短距离,相邻节点的g等于当前节点的g加上与相邻节点的距离 // 我们需要校验到达相邻节点的路径是否是当前最短的路径 const gScore = currentNode.g + neighbor.getCost(currentNode); const beenVisited = neighbor.visited; // 如果相邻节点未被访问到或者其新的g值小于旧的g值则重新计算 if (!beenVisited || gScore < neighbor.g) { neighbor.visited = true; neighbor.parent = currentNode; neighbor.h = neighbor.h || heuristic(neighbor, end); neighbor.g = gScore; neighbor.f = neighbor.g + neighbor.h; graph.markDirty(neighbor); if (closest) { // 如果相邻节点比当前最近节点还靠近终点,则将其置为当前最近节点 if (neighbor.h < closestNode.h || (neighbor.h === closestNode.h && neighbor.g < closestNode.g)) { closestNode = neighbor; } } if (!beenVisited) { // 将相邻节点入栈,栈会根据其f值将其放到正确的位置 openHeap.push(neighbor); } else { // 因为之前访问过此相邻节点,则需要重新排序堆的位置 openHeap.rescoreElement(neighbor); } } } neighborNodes[iterNum] = neighbors; currentNodes[iterNum] = currentNode; iterNum++; } if (closest) { const result: AStarResult = { path: pathTo(closestNode), currentNodes, neighborNodes, }; return result; } // 找不到路径,返回空 const result: AStarResult = { path: [], currentNodes, neighborNodes, }; return result; } }<file_sep>/** * @name GridNode * @description 网格节点 */ export default class GridNode { /** * @name x * @description X坐标 */ public x: number; /** * @name y * @description Y坐标 */ public y: number; /** * @name x * @description 权重 */ public weight: number; /** * @name f * @description 综合优先级 */ public f: number = 0; /** * @name n * @description 节点距离起点的代价 */ public g: number = 0; /** * @name h * @description 节点距离终点的预计代价 */ public h: number = 0; /** * @name visited * @description 节点是否被访问过 */ public visited: boolean = false; /** * @name closed * @description 节点是否在关闭列表 */ public closed: boolean = false; /** * @name parent * @description 路径上的父节点 */ public parent: GridNode = null; constructor(x: number, y: number, weight: number) { this.x = x; this.y = y; this.weight = weight; } /** * @name toString * @description 格式化字符串 * @returns {string} */ public toString(): string { return '[' + this.x + ' ' + this.y + ']'; } /** * @name getCost * @description 获取权重 * @param fromNeighbor 相邻节点 * @returns {number} */ public getCost(fromNeighbor: GridNode): number { // 计算对角权重 if (fromNeighbor && fromNeighbor.x != this.x && fromNeighbor.y != this.y) { return this.weight * 1.41421; } return this.weight; } /** * @name isWall * @description 是否是墙 * @returns {boolean} */ public isWall(): boolean { return this.weight === 0; } }
6eedc64e73e7d62fa1a995a207eab820fbfa2820
[ "Markdown", "TypeScript", "JavaScript" ]
8
Markdown
FEYeh/astar-core
598755abdc2ec398e90069c4506c21cf5fb07f05
7e3483cd27ee6a6dc1a3697c3af06a5b43af15f4
refs/heads/master
<file_sep> var thisHost; function beginCheck(localhost) { thisHost = localhost; var domain = encodeURIComponent($('#website').val()); var url = thisHost + "/MozMetrics/fetchLinksMetrics?domain="+domain; $('#entryForm').hide(); $('#spinner').show(); $.get(url, processLinksMetrics); } function processLinksMetrics(data) { //alert(data); $('#spinner').hide(); if (data == "error") { $("#anotherRunButtonDiv").show(); $("#errorSection").show(); } else { $("#results").show(); $("#buttonDiv").show(); var json = JSON.parse(data); var linksBlock = ""; if (json && json.length > 0) { var title = json[0].luut; var url = json[0].luuu; $("#url").html(url); $("#title").html(url); } for (var i=0;i<json.length;i++) { var obj = json[i]; var url = obj.uu; linksBlock+="<p>"; linksBlock+=url; linksBlock+"</p>" } $("#allLinks").html(linksBlock); $("#anotherRunButtonDiv").show(); } } function anotherRun() { $("#results").hide(); $('#entryForm').show(); $('#website').val(""); $('#buttonDiv').show(); $("#errorSection").hide(); $("#anotherRunButtonDiv").hide(); }<file_sep>package com.careydevelopment.instagramautomation.controller; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller public class HelloWorldController { private static final Logger LOGGER = Logger.getLogger(HelloWorldController.class); @RequestMapping("/hello") public String hello(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) { LOGGER.info("\n\nIn hello!!!!\n\n"); model.addAttribute("name", name); return "greeting"; } } <file_sep>package com.careydevelopment.instagramautomation.controller; import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.jinstagram.Instagram; import org.jinstagram.entity.tags.TagMediaFeed; import org.jinstagram.entity.users.basicinfo.UserInfo; import org.jinstagram.entity.users.feed.MediaFeedData; import org.jinstagram.entity.users.feed.UserFeed; import org.jinstagram.entity.users.feed.UserFeedData; import org.jinstagram.exceptions.InstagramException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.careydevelopment.instagramautomation.model.UserLightweight; @RestController public class GetUsersController { private static final Logger LOGGER = LoggerFactory.getLogger(GetUsersController.class); private static final int COUNT_SIZE = 100; private Instagram instagram = null; private List<String> followers = new ArrayList<String>(); //@Autowired //FollowRunRepository followRunRepository; //@Autowired //UserRepository userRepository; @RequestMapping(value="/getUsers",method = RequestMethod.GET,produces="application/json") public List<UserLightweight> getUsers(@RequestParam(value="keyword", required=true) String keywords, HttpServletRequest request, Model model) { //FollowRun followRun = logRun(); //request.getSession().setAttribute(CURRENT_FOLLOW_RUN, followRun); LOGGER.info("in getUsers"); instagram = (Instagram)request.getSession().getAttribute("instagram"); String[] keys = keywords.split(","); List<UserLightweight> ships = new ArrayList<UserLightweight>(); try { UserFeed feed = instagram.getUserFollowList(instagram.getCurrentUserInfo().getData().getId()); setFollowers(feed); for (int i=0;i<keys.length;i++) { String key = keys[i]; if (key != null && key.trim().length() > 2) { LOGGER.info("Now searching for " + key); if (key.startsWith("#")) key = key.substring(1,key.length()); TagMediaFeed mediaFeed = instagram.getRecentMediaTags(key); List<MediaFeedData> mediaFeeds = mediaFeed.getData(); String[] returnedDudes = getReturnedDudes(mediaFeeds); /*for (String s : returnedDudes) { LOGGER.info(s); }*/ //RelationshipFeed feed = instagram.getUserRelationship(m.getUser().getId()); //ResponseList<Friendship> friendships = twitter.lookupFriendships(returnedDudes); ships.addAll(getLightweights(returnedDudes)); } } } catch (Exception e) { e.printStackTrace(); } return ships; } private void setFollowers(UserFeed feed) { LOGGER.info("Getting followers"); List<UserFeedData> users = feed.getUserList(); for(UserFeedData data : users) { followers.add(data.getId()); } } //saves the log of the run to the db /*private FollowRun logRun() { FollowRun followRun = new FollowRun(); String username = SecurityHelper.getUsername(); User user = userRepository.findById(username); followRun.setUser(user); FollowRun persisted = followRunRepository.save(followRun); return persisted; }*/ /** * Translates heavyweight Friendship objets from Twitter4j into lightweight objects * Easier for JSON */ private List<UserLightweight> getLightweights(String[] ids) throws InstagramException { LOGGER.info("getting lightweights"); List<UserLightweight> ships = new ArrayList<UserLightweight>(); int count = 0; for (String id : ids) { UserInfo userInfo = instagram.getUserInfo(id); UserLightweight light = new UserLightweight(); light.setId(userInfo.getData().getId()); light.setScreenName(userInfo.getData().getUsername()); //be sure to skip the people who are DNF //if (!dnfIds.contains(friendship.getId())) { if (!followers.contains(id)) { light.setFollowing(false); } else { light.setFollowing(true); } /*} else { LOGGER.info("Skipping " + friendship.getScreenName() + " because that user is DNF"); }*/ ships.add(light); //if (count>10) break; } LOGGER.info("done getting lightweights"); return ships; } /** * Returns candidates for following */ private String[] getReturnedDudes(List<MediaFeedData> mediaFeeds) throws InstagramException { LOGGER.info("Getting returned dudes"); String[] returnedDudes = new String[mediaFeeds.size()]; //long[] blocks = twitter.getBlocksIDs().getIDs(); int i = 0; for (MediaFeedData media : mediaFeeds) { returnedDudes[i] = media.getUser().getId(); i++; } return returnedDudes; } /** * Reads a list of do-not-follows from the file. * That file will be appended with the IDs of people we try to follow here * So we don't keep following the same person over and over */ /*private List<Long> fetchDnfs() { BufferedReader br = null; List<Long> dnfIds = new ArrayList<Long>(); try { br = new BufferedReader(new FileReader(DNF_FILE)); String line = br.readLine(); while (line != null) { if (!line.trim().equals("")) { Long id = new Long(line); dnfIds.add(id); } line = br.readLine(); } } catch (Exception e) { e.printStackTrace(); } finally { try { br.close(); } catch (Exception e) { e.printStackTrace(); } } return dnfIds; }*/ } <file_sep> var thisHost; function beginCheck(localhost) { thisHost = localhost; var domain = encodeURIComponent($('#website').val()); var url = thisHost + "/MozMetrics/fetchBasicMetrics?domain="+domain; $('#entryForm').hide(); $('#spinner').show(); $.get(url, processBasicMetrics); } function processBasicMetrics(data) { //alert(data); $('#spinner').hide(); if (data == "error") { $("#anotherRunButtonDiv").show(); $("#errorSection").show(); } else { var json = JSON.parse(data); $("#results").show(); $("#buttonDiv").show(); var siteTitle = json.ut; var siteUrl = json.uu; var equityLinks = json.ueid; var allLinks = json.uid; var mozRank10 = json.umrp; var mozRankRaw = json.umrr; var pageAuthority = json.upa; var domainAuthority = json.pda; $("#siteTitle").html(siteTitle); $("#siteUrl").html(siteUrl); $("#equityLinks").html(equityLinks); $("#allLinks").html(allLinks); $("#mozRank10").html(mozRank10); //$("#mozRankRaw").html(mozRankRaw); $("#pageAuthority").html(pageAuthority); $("#domainAuthority").html(domainAuthority); $("#anotherRunButtonDiv").show(); } } function anotherRun() { $("#results").hide(); $('#entryForm').show(); $('#website').val(""); $('#buttonDiv').show(); $("#errorSection").hide(); $("#anotherRunButtonDiv").hide(); }
868ea9bf8781e9ce63222a657b5d8d1e6e6d8208
[ "JavaScript", "Java" ]
4
JavaScript
brianmarey/InstagramAutomationWebApp
324ca075ccd0c984da12aaa3dad49a390f15b774
9998ab3c6c6443d15d3dd633e3a3ab2296989116
refs/heads/master
<repo_name>Arthurlpgc/Compiladores<file_sep>/src/alpgc_jvsnVisitor.java // Generated from alpgc_jvsn.g4 by ANTLR 4.4 import org.antlr.v4.runtime.misc.NotNull; import org.antlr.v4.runtime.tree.ParseTreeVisitor; /** * This interface defines a complete generic visitor for a parse tree produced * by {@link alpgc_jvsnParser}. * * @param <T> The return type of the visit operation. Use {@link Void} for * operations with no return type. */ public interface alpgc_jvsnVisitor<T> extends ParseTreeVisitor<T> { /** * Visit a parse tree produced by {@link alpgc_jvsnParser#formal}. * @param ctx the parse tree * @return the visitor result */ T visitFormal(@NotNull alpgc_jvsnParser.FormalContext ctx); /** * Visit a parse tree produced by {@link alpgc_jvsnParser#identifier}. * @param ctx the parse tree * @return the visitor result */ T visitIdentifier(@NotNull alpgc_jvsnParser.IdentifierContext ctx); /** * Visit a parse tree produced by {@link alpgc_jvsnParser#goal}. * @param ctx the parse tree * @return the visitor result */ T visitGoal(@NotNull alpgc_jvsnParser.GoalContext ctx); /** * Visit a parse tree produced by {@link alpgc_jvsnParser#expression}. * @param ctx the parse tree * @return the visitor result */ T visitExpression(@NotNull alpgc_jvsnParser.ExpressionContext ctx); /** * Visit a parse tree produced by {@link alpgc_jvsnParser#method_declaration}. * @param ctx the parse tree * @return the visitor result */ T visitMethod_declaration(@NotNull alpgc_jvsnParser.Method_declarationContext ctx); /** * Visit a parse tree produced by {@link alpgc_jvsnParser#statement}. * @param ctx the parse tree * @return the visitor result */ T visitStatement(@NotNull alpgc_jvsnParser.StatementContext ctx); /** * Visit a parse tree produced by {@link alpgc_jvsnParser#var_declaration}. * @param ctx the parse tree * @return the visitor result */ T visitVar_declaration(@NotNull alpgc_jvsnParser.Var_declarationContext ctx); /** * Visit a parse tree produced by {@link alpgc_jvsnParser#main_class}. * @param ctx the parse tree * @return the visitor result */ T visitMain_class(@NotNull alpgc_jvsnParser.Main_classContext ctx); /** * Visit a parse tree produced by {@link alpgc_jvsnParser#class_declaration}. * @param ctx the parse tree * @return the visitor result */ T visitClass_declaration(@NotNull alpgc_jvsnParser.Class_declarationContext ctx); /** * Visit a parse tree produced by {@link alpgc_jvsnParser#type}. * @param ctx the parse tree * @return the visitor result */ T visitType(@NotNull alpgc_jvsnParser.TypeContext ctx); }<file_sep>/src/alpgc_jvsnListener.java // Generated from alpgc_jvsn.g4 by ANTLR 4.4 import org.antlr.v4.runtime.misc.NotNull; import org.antlr.v4.runtime.tree.ParseTreeListener; /** * This interface defines a complete listener for a parse tree produced by * {@link alpgc_jvsnParser}. */ public interface alpgc_jvsnListener extends ParseTreeListener { /** * Enter a parse tree produced by {@link alpgc_jvsnParser#formal}. * @param ctx the parse tree */ void enterFormal(@NotNull alpgc_jvsnParser.FormalContext ctx); /** * Exit a parse tree produced by {@link alpgc_jvsnParser#formal}. * @param ctx the parse tree */ void exitFormal(@NotNull alpgc_jvsnParser.FormalContext ctx); /** * Enter a parse tree produced by {@link alpgc_jvsnParser#identifier}. * @param ctx the parse tree */ void enterIdentifier(@NotNull alpgc_jvsnParser.IdentifierContext ctx); /** * Exit a parse tree produced by {@link alpgc_jvsnParser#identifier}. * @param ctx the parse tree */ void exitIdentifier(@NotNull alpgc_jvsnParser.IdentifierContext ctx); /** * Enter a parse tree produced by {@link alpgc_jvsnParser#goal}. * @param ctx the parse tree */ void enterGoal(@NotNull alpgc_jvsnParser.GoalContext ctx); /** * Exit a parse tree produced by {@link alpgc_jvsnParser#goal}. * @param ctx the parse tree */ void exitGoal(@NotNull alpgc_jvsnParser.GoalContext ctx); /** * Enter a parse tree produced by {@link alpgc_jvsnParser#expression}. * @param ctx the parse tree */ void enterExpression(@NotNull alpgc_jvsnParser.ExpressionContext ctx); /** * Exit a parse tree produced by {@link alpgc_jvsnParser#expression}. * @param ctx the parse tree */ void exitExpression(@NotNull alpgc_jvsnParser.ExpressionContext ctx); /** * Enter a parse tree produced by {@link alpgc_jvsnParser#method_declaration}. * @param ctx the parse tree */ void enterMethod_declaration(@NotNull alpgc_jvsnParser.Method_declarationContext ctx); /** * Exit a parse tree produced by {@link alpgc_jvsnParser#method_declaration}. * @param ctx the parse tree */ void exitMethod_declaration(@NotNull alpgc_jvsnParser.Method_declarationContext ctx); /** * Enter a parse tree produced by {@link alpgc_jvsnParser#statement}. * @param ctx the parse tree */ void enterStatement(@NotNull alpgc_jvsnParser.StatementContext ctx); /** * Exit a parse tree produced by {@link alpgc_jvsnParser#statement}. * @param ctx the parse tree */ void exitStatement(@NotNull alpgc_jvsnParser.StatementContext ctx); /** * Enter a parse tree produced by {@link alpgc_jvsnParser#var_declaration}. * @param ctx the parse tree */ void enterVar_declaration(@NotNull alpgc_jvsnParser.Var_declarationContext ctx); /** * Exit a parse tree produced by {@link alpgc_jvsnParser#var_declaration}. * @param ctx the parse tree */ void exitVar_declaration(@NotNull alpgc_jvsnParser.Var_declarationContext ctx); /** * Enter a parse tree produced by {@link alpgc_jvsnParser#main_class}. * @param ctx the parse tree */ void enterMain_class(@NotNull alpgc_jvsnParser.Main_classContext ctx); /** * Exit a parse tree produced by {@link alpgc_jvsnParser#main_class}. * @param ctx the parse tree */ void exitMain_class(@NotNull alpgc_jvsnParser.Main_classContext ctx); /** * Enter a parse tree produced by {@link alpgc_jvsnParser#class_declaration}. * @param ctx the parse tree */ void enterClass_declaration(@NotNull alpgc_jvsnParser.Class_declarationContext ctx); /** * Exit a parse tree produced by {@link alpgc_jvsnParser#class_declaration}. * @param ctx the parse tree */ void exitClass_declaration(@NotNull alpgc_jvsnParser.Class_declarationContext ctx); /** * Enter a parse tree produced by {@link alpgc_jvsnParser#type}. * @param ctx the parse tree */ void enterType(@NotNull alpgc_jvsnParser.TypeContext ctx); /** * Exit a parse tree produced by {@link alpgc_jvsnParser#type}. * @param ctx the parse tree */ void exitType(@NotNull alpgc_jvsnParser.TypeContext ctx); }<file_sep>/src/teste.java import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.tree.ParseTree; import ast.Program; import visitor.BuildSymbolTableVisitor; import visitor.PrettyPrintVisitor; import visitor.TypeCheckVisitor; public class teste { int [] a; public static void main(String[] args) throws IOException { InputStream stream = new FileInputStream("src/Teste.txt"); ANTLRInputStream input = new ANTLRInputStream(stream); alpgc_jvsnLexer lexer = new alpgc_jvsnLexer(input); CommonTokenStream token = new CommonTokenStream(lexer); alpgc_jvsnParser parser = new alpgc_jvsnParser(token); ParseTree tree = parser.goal(); System.out.println(tree.toStringTree(parser)); alpgc_jvsn_visitor visitor = new alpgc_jvsn_visitor(); Program program = (Program) visitor.visit(tree); program.accept(new PrettyPrintVisitor()); BuildSymbolTableVisitor buildTable = new BuildSymbolTableVisitor(); buildTable.visit(program); TypeCheckVisitor typeCheck = new TypeCheckVisitor(buildTable.getSymbolTable()); typeCheck.visit(program); } } <file_sep>/src/alpgc_jvsn_visitor.java import java.util.List; import ast.*; public class alpgc_jvsn_visitor extends alpgc_jvsnBaseVisitor<Object> { public Object visitGoal(alpgc_jvsnParser.GoalContext ctx){ MainClass main = (MainClass) this.visit(ctx.getChild(0)); ClassDeclList lista=new ClassDeclList(); for(alpgc_jvsnParser.Class_declarationContext k:ctx.class_declaration()){ lista.addElement((ClassDecl)this.visit(k)); } Program program = new Program(main, lista); return program; } public Object visitIdentifier(alpgc_jvsnParser.IdentifierContext ctx){ return new Identifier(ctx.getText()); } public Object visitMain_class(alpgc_jvsnParser.Main_classContext ctx){ Identifier i1 = new Identifier(ctx.identifier(0).getText()); Identifier i2 = new Identifier(ctx.identifier(1).getText()); Statement st = (Statement) this.visit(ctx.statement()); return new MainClass(i1, i2, st); } public Object visitClass_declaration(alpgc_jvsnParser.Class_declarationContext ctx){ VarDeclList varlist=new VarDeclList(); for(alpgc_jvsnParser.Var_declarationContext vctx:ctx.var_declaration()){ varlist.addElement((VarDecl)this.visit(vctx)); } MethodDeclList mdl=new MethodDeclList(); for(alpgc_jvsnParser.Method_declarationContext mctx:ctx.method_declaration()){ mdl.addElement((MethodDecl)this.visit(mctx)); } if(ctx.identifier(1)==null)return new ClassDeclSimple((Identifier)this.visit(ctx.identifier(0)), varlist, mdl); else return new ClassDeclExtends((Identifier)this.visit(ctx.identifier(0)),(Identifier)this.visit(ctx.identifier(1)), varlist, mdl); } public Object visitType(alpgc_jvsnParser.TypeContext ctx){ if(ctx.getChild(0).getText().equals("boolean"))return new BooleanType(); else if(ctx.getChild(0).getText().equals("int")){ if(ctx.getChildCount()==1)return new IntegerType(); else return new IntArrayType(); }else return new IdentifierType(ctx.getText()); } public Object visitFormal(alpgc_jvsnParser.FormalContext ctx){ return new Formal((Type) this.visit(ctx.type()), (Identifier) this.visit(ctx.identifier())); } public Object visitVar_declaration(alpgc_jvsnParser.Var_declarationContext ctx){ Formal f=(Formal)this.visit(ctx.formal()); return new VarDecl(f.t,f.i); } public Object visitMethod_declaration(alpgc_jvsnParser.Method_declarationContext ctx){ Formal idType = (Formal)this.visit(ctx.formal(0)); FormalList formalList = new FormalList(); VarDeclList varList = new VarDeclList(); StatementList stList = new StatementList(); Exp exp = (Exp) this.visit(ctx.expression()); for(alpgc_jvsnParser.FormalContext formal : ctx.formal()) { formalList.addElement((Formal) this.visit(formal)); } for(alpgc_jvsnParser.Var_declarationContext var: ctx.var_declaration()) { varList.addElement((VarDecl) this.visit(var)); } for(alpgc_jvsnParser.StatementContext stmt: ctx.statement()) { stList.addElement((Statement) this.visit(stmt)); } return new MethodDecl(idType.t, idType.i, formalList, varList, stList, exp); } public Object visitStatement(alpgc_jvsnParser.StatementContext ctx){ if(ctx.getChild(0).getText().equals("{")){ StatementList sl= new StatementList(); for(alpgc_jvsnParser.StatementContext s:ctx.statement()){ sl.addElement((Statement)this.visit(s)); } return new Block(sl); }else if(ctx.getChild(0).getText().equals("if")){ Exp exp = (Exp) this.visit(ctx.expression(0)); Statement s1 = (Statement) this.visit(ctx.statement(0)); Statement s2 = (Statement) this.visit(ctx.statement(1)); return new If(exp, s1, s2); } else if(ctx.getChild(0).getText().equals("while")){ Exp exp = (Exp) this.visit(ctx.expression(0)); Statement s = (Statement) this.visit(ctx.statement(0)); return new While(exp, s); } else if(ctx.getChild(0).getText().equals("System.out.println")){ Exp exp = (Exp) this.visit(ctx.expression(0)); return new Print(exp); } else if(ctx.getChild(1).getText().equals("=")){ Identifier id = (Identifier) this.visit(ctx.identifier()); Exp exp = (Exp) this.visit(ctx.expression(0)); return new Assign(id, exp); } else { Identifier id = (Identifier) this.visit(ctx.identifier()); Exp exp1 = (Exp) this.visit(ctx.expression(0)), exp2 = (Exp) this.visit(ctx.expression(1)); return new ArrayAssign(id, exp1, exp2); } } public Object visitExpression(alpgc_jvsnParser.ExpressionContext ctx){ if(ctx.getChildCount()==1&&ctx.getChild(0).getText().equals("true"))return new True(); else if(ctx.getChildCount()==1&&ctx.getChild(0).getText().equals("false"))return new False(); else if(ctx.getChildCount()==1&&ctx.getChild(0).getText().equals("this"))return new This(); else if(ctx.getChild(0).getText().equals("!"))return new Not((Exp) this.visit(ctx.expression(0))); else if(ctx.getChild(0).getText().equals("("))return ((Exp) this.visit(ctx.expression(0))); else if(ctx.INTEGERLITERAL()!=null)return new IntegerLiteral(Integer.parseInt((ctx.INTEGERLITERAL().getText()))); else if(ctx.getChildCount()==1)return new IdentifierExp(ctx.getText()); else if(ctx.getChild(1).getText().equals("[")) { Exp arrayExpr = (Exp) this.visit(ctx.expression(0)); Exp indexExpr = (Exp) this.visit(ctx.expression(1)); return new ArrayLookup(arrayExpr,indexExpr); } else if(ctx.getChild(0).getText().equals("new")){ if(ctx.getChild(1).getText().equals("int")){ return new NewArray((Exp) this.visit(ctx.expression(0))); }else{ return new NewObject((Identifier) this.visit(ctx.identifier())); } }else if(ctx.getChild(1).getText().equals("&&")){ return new And((Exp)this.visit(ctx.expression(0)),(Exp)this.visit(ctx.expression(1))); }else if(ctx.getChild(1).getText().equals("+")){ return new Plus((Exp)this.visit(ctx.expression(0)),(Exp)this.visit(ctx.expression(1))); }else if(ctx.getChild(1).getText().equals("<")){ return new LessThan((Exp)this.visit(ctx.expression(0)),(Exp)this.visit(ctx.expression(1))); }else if(ctx.getChild(1).getText().equals("-")){ return new Minus((Exp)this.visit(ctx.expression(0)),(Exp)this.visit(ctx.expression(1))); }else if(ctx.getChild(1).getText().equals("*")){ return new Times((Exp)this.visit(ctx.expression(0)),(Exp)this.visit(ctx.expression(1))); }else if(ctx.getChild(2).getText().equals("length"))return new ArrayLength((Exp) this.visit(ctx.expression(0))); else if(ctx.getChild(1).getText().equals(".")){ Identifier id = (Identifier) this.visit(ctx.identifier()); List<alpgc_jvsnParser.ExpressionContext> listaexp = ctx.expression(); Exp base = (Exp) this.visit(listaexp.get(0)); listaexp.remove(0); ExpList listaExpRet = new ExpList(); for(alpgc_jvsnParser.ExpressionContext item:listaexp){ listaExpRet.addElement((Exp)this.visit(item)); } return new Call(base, id, listaExpRet); } else return null; } }
ada84dd97d424b7d222ad3cb6b2b372922353c9a
[ "Java" ]
4
Java
Arthurlpgc/Compiladores
c82728c7cf3cec007ac5fe276fb6df6b6b46ef21
ba9a3e79c48ab19e8690c9661c1b7d30384cad4e
refs/heads/master
<file_sep>Canova ========================= [![Join the chat at https://gitter.im/deeplearning4j/deeplearning4j](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/deeplearning4j/deeplearning4j?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) Canova is an Apache2 Licensed open-sourced tool for vectorizing raw data into usable vector formats across machine learning tools. Canova understands how to take general text and convert it into vectors with stock techniques such as kernel hashing and TF-IDF [TODO]. Runs as both a local serial process and a MapReduce (MR engine on the roadmap) scale-out process with no code changes. --- ## Targetted Vector Formats & Vectorization Engines #### Formats * svmLight * libsvm * Metronome * ARFF #### Targeted Vectorization Engines * Any CSV to vectors with a scriptable transform language * MNIST to vectors * Text to vectors: * TF-IDF * Bag of Words * word2vec #### Example Functionality * Convert the CSV-based UCI Iris dataset into svmLight open vector text format * Convert the MNIST dataset from raw binary files to the svmLight text format. * Convert raw text into the Metronome vector format * Convert raw text into TF-IDF based vectors in a text vector format {svmLight, metronome, arff} * Convert raw text into the word2vec in a text vector format {svmLight, metronome, arff} --- ## Installation To install Canova there are a couple approaches and more information can be found on the site at this [link](http://nd4j.org/getstarted.html). #### Use Maven Central Repository Search for [canova](https://search.maven.org/#search%7Cga%7C1%7CCanova) to get a list of jars you can use Add the dependency information into your pom.xml #### Clone from the GitHub Repo Canova is actively developed and you can clone the repository, compile it and reference it in your project. First clone the [ND4J repo](https://github.com/deeplearning4j/nd4j) and build compile prior to building Canova. Clone the repository: $ git clone https://github.com/deeplearning4j/Canova.git Compile the project: $ cd canova && mvn clean install -DskipTests -Dmaven.javadoc.skip=true Add the local compiled file dependencies to your pom.xml file like the following example: <dependency> <groupId>org.nd4j</groupId> <artifactId>canova-api-SNAPSHOT</artifactId> <version>0.0.0.3</version> </dependency> #### Yum Install / Load RPM (Fedora or CentOS) Create a yum repo and run yum install to load the Red Hat Package Management (RPM) files. First create the repo file to setup the configuration locally. $ sudo vi /etc/yum.repos.d/dl4j.repo Add the following to the dl4j.repo file: ''' [dl4j.repo] name=dl4j-repo baseurl=http://ec2-52-5-255-24.compute-1.amazonaws.com/repo/RPMS enabled=1 gpgcheck=0 ''' Then run the following command on the dl4j repo packages to install them on your machine: $ sudo yum install [package name] -y $ sudo yum install Canova-Distro -y # for example --- ## CSV Transformation Engine Example Below is an example of the CSV transform language in action from the command line. #### Setup Canova CLI Follow the Get the Code Installation approach and then build the stand-alone Canova jar to run the CLI from the command line: cd canova-cli/ && mvn -DskipTests=true -Dmaven.javadoc.skip=true package #### UCI Iris Schema Transform ``` @RELATION UCIIrisDataset @DELIMITER , @ATTRIBUTE sepallength NUMERIC !NORMALIZE @ATTRIBUTE sepalwidth NUMERIC !NORMALIZE @ATTRIBUTE petallength NUMERIC !NORMALIZE @ATTRIBUTE petalwidth NUMERIC !NORMALIZE @ATTRIBUTE class STRING !LABEL ``` #### Create the Configuration File We need a file to tell the vectorization engine what to do. Create a text file containing the following lines in the *canova-cli* directory (you might name the file vec_conf.txt): ``` input.header.skip=false input.statistics.debug.print=false input.format=org.canova.api.formats.input.impl.LineInputFormat input.directory=src/test/resources/csv/data/uci_iris_sample.txt input.vector.schema=src/test/resources/csv/schemas/uci/iris.txt output.directory=/tmp/iris_unit_test_sample.txt output.format=org.canova.api.formats.output.impl.SVMLightOutputFormat ``` #### Run Canova From the Command Line Now we're going to take this [sample](https://github.com/deeplearning4j/Canova/blob/master/canova-cli/src/test/resources/csv/data/uci_iris_sample.txt) of [UCI's Iris dataset](https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data). ``` 5.1,3.5,1.4,0.2,Iris-setosa 4.9,3.0,1.4,0.2,Iris-setosa 4.7,3.2,1.3,0.2,Iris-setosa 7.0,3.2,4.7,1.4,Iris-versicolor 6.4,3.2,4.5,1.5,Iris-versicolor 6.9,3.1,4.9,1.5,Iris-versicolor 5.5,2.3,4.0,1.3,Iris-versicolor 6.5,2.8,4.6,1.5,Iris-versicolor 6.3,3.3,6.0,2.5,Iris-virginica 5.8,2.7,5.1,1.9,Iris-virginica 7.1,3.0,5.9,2.1,Iris-virginica 6.3,2.9,5.6,1.8,Iris-virginica ``` We transform it into the svmLight format from the command line like this ``` ./bin/canova vectorize -conf [my_conf_file] ``` #### CLI Output The output in your command prompt should look like ``` ./bin/canova vectorize -conf /tmp/iris_conf.txt File path already exists, deleting the old file before proceeding... Output vectors written to: /tmp/iris_svmlight.txt ``` If you cd into /tmp and open *iris_svmlight.txt*, you'll see something like this: ``` 0.0 1:0.1666666666666665 2:1.0 3:0.021276595744680823 4:0.0 0.0 1:0.08333333333333343 2:0.5833333333333334 3:0.021276595744680823 4:0.0 0.0 1:0.0 2:0.7500000000000002 3:0.0 4:0.0 1.0 1:0.9583333333333335 2:0.7500000000000002 3:0.723404255319149 4:0.5217391304347826 1.0 1:0.7083333333333336 2:0.7500000000000002 3:0.6808510638297872 4:0.5652173913043479 1.0 1:0.916666666666667 2:0.6666666666666667 3:0.7659574468085107 4:0.5652173913043479 1.0 1:0.3333333333333333 2:0.0 3:0.574468085106383 4:0.47826086956521746 1.0 1:0.7500000000000001 2:0.41666666666666663 3:0.702127659574468 4:0.5652173913043479 2.0 1:0.6666666666666666 2:0.8333333333333333 3:1.0 4:1.0 2.0 1:0.45833333333333326 2:0.3333333333333336 3:0.8085106382978723 4:0.7391304347826088 2.0 1:1.0 2:0.5833333333333334 3:0.9787234042553192 4:0.8260869565217392 2.0 1:0.6666666666666666 2:0.5 3:0.9148936170212765 4:0.6956521739130436 ``` --- ## Contribute 1. Check for open issues or open a fresh issue to start a discussion around a feature idea or a bug. 2. If you feel uncomfortable or uncertain about an issue or your changes, feel free to contact us on Gitter using the link above. 3. Fork [the repository](https://github.com/deeplearning4j/Canova.git) on GitHub to start making your changes to the **master** branch (or branch off of it). 4. Write a test which shows that the bug was fixed or that the feature works as expected. 5. Send a pull request and bug us on Gitter until it gets merged and published. <file_sep>/* * * * * * * Copyright 2015 Skymind,Inc. * * * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * * you may not use this file except in compliance with the License. * * * You may obtain a copy of the License at * * * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * * * Unless required by applicable law or agreed to in writing, software * * * distributed under the License is distributed on an "AS IS" BASIS, * * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * * See the License for the specific language governing permissions and * * * limitations under the License. * * * */ package org.canova.cli.subcommands; import static org.junit.Assert.*; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import org.apache.commons.io.FileUtils; import org.canova.api.exceptions.CanovaException; import org.canova.api.formats.input.InputFormat; import org.canova.api.formats.output.OutputFormat; import org.canova.api.records.reader.RecordReader; import org.canova.api.records.reader.impl.LineRecordReader; import org.canova.api.records.writer.RecordWriter; import org.canova.api.records.writer.impl.SVMLightRecordWriter; import org.canova.api.split.FileSplit; import org.canova.api.split.InputSplit; import org.canova.api.writable.Writable; import org.junit.Test; public class TestVectorize { @Test public void testLoadConfFile() throws IOException { String[] args = { "-conf", "src/test/resources/csv/confs/unit_test_conf.txt" }; Vectorize vecCommand = new Vectorize( args ); vecCommand.loadConfigFile(); assertEquals( "/tmp/iris_unit_test_sample.txt", vecCommand.configProps.get("output.directory") ); } @Test public void testExecuteCSVConversionWorkflow() throws Exception { String[] args = { "-conf", "src/test/resources/csv/confs/unit_test_conf.txt" }; Vectorize vecCommand = new Vectorize( args ); vecCommand.execute(); // now check the output } } <file_sep>/* * * * * * * Copyright 2015 Skymind,Inc. * * * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * * you may not use this file except in compliance with the License. * * * You may obtain a copy of the License at * * * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * * * Unless required by applicable law or agreed to in writing, software * * * distributed under the License is distributed on an "AS IS" BASIS, * * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * * See the License for the specific language governing permissions and * * * limitations under the License. * * * */ package org.canova.cli.subcommands; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import java.util.Enumeration; import java.util.Properties; import com.google.common.base.Strings; import org.canova.api.conf.Configuration; import org.canova.api.exceptions.CanovaException; import org.canova.api.formats.input.InputFormat; import org.canova.api.formats.output.OutputFormat; import org.canova.api.records.reader.RecordReader; import org.canova.api.records.writer.RecordWriter; import org.canova.api.split.FileSplit; import org.canova.api.split.InputSplit; import org.canova.api.writable.Writable; import org.canova.cli.csv.schema.CSVInputSchema; import org.canova.cli.csv.vectorization.CSVVectorizationEngine; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineParser; import org.kohsuke.args4j.Option; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Vectorize Command. * Based on an input and output format * transforms data * * @author jp * @author <NAME> */ public class Vectorize implements SubCommand { private static final Logger log = LoggerFactory.getLogger(Vectorize.class); public static final String OUTPUT_FILENAME_KEY = "output.directory"; public static final String INPUT_FORMAT = "input.format"; public static final String DEFAULT_INPUT_FORMAT_CLASSNAME = "org.canova.api.formats.input.impl.LineInputFormat"; public static final String OUTPUT_FORMAT = "output.format"; public static final String DEFAULT_OUTPUT_FORMAT_CLASSNAME = "org.canova.api.formats.output.impl.SVMLightOutputFormat"; protected String[] args; public boolean validCommandLineParameters = true; @Option(name = "-conf", usage = "Sets a configuration file to drive the vectorization process") public String configurationFile = ""; public Properties configProps = null; public String outputVectorFilename = ""; private CSVInputSchema inputSchema = null; private CSVVectorizationEngine vectorizer = null; public Vectorize() { } // this picks up the input schema file from the properties file and loads it private void loadInputSchemaFile() throws Exception { String schemaFilePath = (String) this.configProps.get("input.vector.schema"); this.inputSchema = new CSVInputSchema(); this.inputSchema.parseSchemaFile(schemaFilePath); this.vectorizer = new CSVVectorizationEngine(); } // picked up in the command line parser flags (-conf=<foo.txt>) public void loadConfigFile() throws IOException { this.configProps = new Properties(); //Properties prop = new Properties(); try (InputStream in = new FileInputStream(this.configurationFile)) { this.configProps.load(in); } if (null == this.configProps.get(OUTPUT_FILENAME_KEY)) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss"); this.outputVectorFilename = "/tmp/canova_vectors_" + dateFormat.format(new Date()) + ".txt"; } else { // what if its only a directory? this.outputVectorFilename = (String) this.configProps.get(OUTPUT_FILENAME_KEY); if (!(new File(this.outputVectorFilename).exists())) { // file path does not exist File yourFile = new File(this.outputVectorFilename); if (!yourFile.exists()) { yourFile.createNewFile(); } } else { if (new File(this.outputVectorFilename).isDirectory()) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss"); //File file = new File(dateFormat.format(date) + ".tsv") ; this.outputVectorFilename += "/canova_vectors_" + dateFormat.format(new Date()) + ".txt"; } else { // if a file already exists (new File(this.outputVectorFilename)).delete(); log.info("File path already exists, deleting the old file before proceeding..."); } } } } public void debugLoadedConfProperties() { Properties props = this.configProps; //System.getProperties(); Enumeration e = props.propertyNames(); log.info("\n--- Start Canova Configuration ---"); while (e.hasMoreElements()) { String key = (String) e.nextElement(); System.out.println(key + " -- " + props.getProperty(key)); } log.info("---End Canova Configuration ---\n"); } // 1. load conf file // 2, load schema file // 3. transform csv -> output format public void execute() throws Exception { if (!this.validCommandLineParameters) { log.error("Vectorize function is not configured properly, stopping."); return; } boolean schemaLoaded; // load stuff (conf, schema) --> CSVInputSchema this.loadConfigFile(); if (null != this.configProps.get("conf.print")) { String print = (String) this.configProps.get("conf.print"); if ("true".equals(print.trim().toLowerCase())) { this.debugLoadedConfProperties(); } } try { this.loadInputSchemaFile(); schemaLoaded = true; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); schemaLoaded = false; } if (!schemaLoaded) { // if we did not load the schema then we cannot proceed with conversion } // setup input / output formats // collect dataset statistics --> CSVInputSchema // [ first dataset pass ] // for each row in CSV Dataset String datasetInputPath = (String) this.configProps.get("input.directory"); File inputFile = new File(datasetInputPath); InputSplit split = new FileSplit(inputFile); InputFormat inputFormat = this.createInputFormat(); RecordReader reader = inputFormat.createReader(split); // TODO: replace this with an { input-format, record-reader } // try (BufferedReader br = new BufferedReader( new FileReader( datasetInputPath ) )) { while (reader.hasNext()) { Collection<Writable> w = reader.next(); //for (String line; (line = br.readLine()) != null; ) { // TODO: this will end up processing key-value pairs try { this.inputSchema.evaluateInputRecord(w.toArray()[0].toString()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } reader.close(); // generate dataset report --> DatasetSummaryStatistics this.inputSchema.computeDatasetStatistics(); String schema_print_key = "input.statistics.debug.print"; if (null != this.configProps.get(schema_print_key)) { String printSchema = (String) this.configProps.get(schema_print_key); if ("true".equals(printSchema.trim().toLowerCase())) { //this.debugLoadedConfProperties(); this.inputSchema.debugPringDatasetStatistics(); } } // produce converted/vectorized output based on statistics --> Transforms + CSVInputSchema + Rows // [ second dataset pass ] reader = inputFormat.createReader(split); OutputFormat outputFormat = this.createOutputFormat(); Configuration conf = new Configuration(); conf.set(OutputFormat.OUTPUT_PATH, this.outputVectorFilename); RecordWriter writer = outputFormat.createWriter(conf); //new SVMLightRecordWriter(tmpOutSVMLightFile,true); while (reader.hasNext()) { Collection<Writable> w = reader.next(); String line = w.toArray()[0].toString(); // TODO: this will end up processing key-value pairs // this outputVector needs to be ND4J // TODO: we need to be re-using objects here for heap churn purposes //INDArray outputVector = this.vectorizer.vectorize( "", line, this.inputSchema ); if (!Strings.isNullOrEmpty(line)) { writer.write(vectorizer.vectorizeToWritable("", line, this.inputSchema)); } } reader.close(); writer.close(); log.info("Output vectors written to: " + this.outputVectorFilename); } /** * @param args arguments for command */ public Vectorize(String[] args) { this.args = args; CmdLineParser parser = new CmdLineParser(this); try { parser.parseArgument(args); } catch (CmdLineException e) { this.validCommandLineParameters = false; parser.printUsage(System.err); log.error("Unable to parse args", e); } } /** * Creates an input format * * @return */ public InputFormat createInputFormat() { //System.out.println( "> Loading Input Format: " + (String) this.configProps.get( INPUT_FORMAT ) ); String clazz = (String) this.configProps.get(INPUT_FORMAT); if (null == clazz) { clazz = DEFAULT_INPUT_FORMAT_CLASSNAME; } try { Class<? extends InputFormat> inputFormatClazz = (Class<? extends InputFormat>) Class.forName(clazz); return inputFormatClazz.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } public OutputFormat createOutputFormat() { //String clazz = conf.get( OUTPUT_FORMAT, DEFAULT_OUTPUT_FORMAT_CLASSNAME ); //System.out.println( "> Loading Output Format: " + (String) this.configProps.get( OUTPUT_FORMAT ) ); String clazz = (String) this.configProps.get(OUTPUT_FORMAT); if (null == clazz) { clazz = DEFAULT_OUTPUT_FORMAT_CLASSNAME; } try { Class<? extends OutputFormat> outputFormatClazz = (Class<? extends OutputFormat>) Class.forName(clazz); return outputFormatClazz.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } }<file_sep>/* * * * * * * Copyright 2015 Skymind,Inc. * * * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * * you may not use this file except in compliance with the License. * * * You may obtain a copy of the License at * * * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * * * Unless required by applicable law or agreed to in writing, software * * * distributed under the License is distributed on an "AS IS" BASIS, * * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * * See the License for the specific language governing permissions and * * * limitations under the License. * * * */ package org.canova.cli.csv.vectorization; import org.canova.api.io.data.DoubleWritable; import org.canova.api.io.data.Text; import org.canova.api.writable.Writable; import org.canova.cli.csv.schema.CSVInputSchema; import org.canova.cli.csv.schema.CSVSchemaColumn; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collection; import java.util.Map; /** * Vectorization Engine * - takes CSV input and converts it to a transformed vector output in a standard format * - uses the input CSV schema and the collected statistics from a pre-pass * * @author josh */ public class CSVVectorizationEngine { private static final Logger log = LoggerFactory.getLogger(CSVVectorizationEngine.class); /** * Use statistics collected from a previous pass to vectorize (or drop) each column * * @return */ public Collection<Writable> vectorize(String key, String value, CSVInputSchema schema) { //INDArray Collection<Writable> ret = new ArrayList<>(); // TODO: this needs to be different (needs to be real vector representation //String outputVector = ""; String[] columns = value.split(schema.delimiter); if (columns[0].trim().equals("")) { // log.info("Skipping blank line"); return null; } int srcColIndex = 0; int dstColIndex = 0; //log.info( "> Engine.vectorize() ----- "); double label = 0; // scan through the columns in the schema / input csv data for (Map.Entry<String, CSVSchemaColumn> entry : schema.getColumnSchemas().entrySet()) { String colKey = entry.getKey(); CSVSchemaColumn colSchemaEntry = entry.getValue(); // produce the per column transform based on stats switch (colSchemaEntry.transform) { case SKIP: // dont append this to the output vector, skipping break; case LABEL: // log.info( " label value: " + columns[ srcColIndex ] ); label = colSchemaEntry.transformColumnValue(columns[srcColIndex].trim()); break; default: // log.info( " column value: " + columns[ srcColIndex ] ); double convertedColumn = colSchemaEntry.transformColumnValue(columns[srcColIndex].trim()); // add this value to the output vector ret.add(new DoubleWritable(convertedColumn)); dstColIndex++; break; } srcColIndex++; } ret.add(new DoubleWritable(label)); //dstColIndex++; return ret; } /** * Use statistics collected from a previous pass to vectorize (or drop) each column * * @return */ public Collection<Writable> vectorizeToWritable(String key, String value, CSVInputSchema schema) { //INDArray //INDArray ret = this.createArray( schema.getTransformedVectorSize() ); Collection<Writable> ret = new ArrayList<>(); // TODO: this needs to be different (needs to be real vector representation //String outputVector = ""; String[] columns = value.split(schema.delimiter); if (columns[0].trim().equals("")) { // log.info("Skipping blank line"); return null; } int srcColIndex = 0; int dstColIndex = 0; //log.info( "> Engine.vectorize() ----- "); // scan through the columns in the schema / input csv data for (Map.Entry<String, CSVSchemaColumn> entry : schema.getColumnSchemas().entrySet()) { String colKey = entry.getKey(); CSVSchemaColumn colSchemaEntry = entry.getValue(); // produce the per column transform based on stats switch (colSchemaEntry.transform) { case SKIP: // dont append this to the output vector, skipping break; default: // log.info( " column value: " + columns[ srcColIndex ] ); double convertedColumn = colSchemaEntry.transformColumnValue(columns[srcColIndex].trim()); // add this value to the output vector //ret.putScalar(dstColIndex, convertedColumn); ret.add(new Text(convertedColumn + "")); dstColIndex++; break; } srcColIndex++; } return ret; } }
abe3011c3a657aa635ab52b8baea1f475da82150
[ "Markdown", "Java" ]
4
Markdown
srgnuclear/Canova
2f942e6fb9ad7776f183802d032c9161348f8a0e
735f3c2d72e5804440bc715bed69ceb29e5f7e9b
refs/heads/master
<repo_name>erliyusnaidi/maimasjid<file_sep>/Events/src/com/events/Register.java package com.events; import android.app.ProgressDialog; import android.os.Bundle; import android.view.View; import android.widget.EditText; import com.events.custom.CustomActivity; import com.events.model.Status; import com.events.utils.Commons; import com.events.utils.Const; import com.events.utils.StaticData; import com.events.utils.Utils; import com.events.web.WebHelper; /** * The Class Register is the Activity class that is launched when the user * clicks on Register button in Login screen and it allow user to register him * self as a new user of this app. */ public class Register extends CustomActivity { /* (non-Javadoc) * @see com.events.custom.CustomActivity#onCreate(android.os.Bundle) */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.register); setTouchNClick(R.id.btnCancel); setTouchNClick(R.id.btnReg); getActionBar().setTitle(R.string.register); } /* (non-Javadoc) * @see com.events.custom.CustomActivity#onClick(android.view.View) */ @Override public void onClick(View v) { super.onClick(v); if (v.getId() == R.id.btnReg) { doRegister(); } else { finish(); } } /** * Call the Register API and check user's Login details and based on the API * response, take required action or show error message if any. */ private void doRegister() { final String name = ((EditText) findViewById(R.id.txtName)).getText() .toString().trim(); final String email = ((EditText) findViewById(R.id.txtEmail)).getText() .toString().trim(); final String pwd = ((EditText) findViewById(R.id.txtPwd)).getText() .toString().trim(); if (Commons.isEmpty(name) || Commons.isEmpty(email) || Commons.isEmpty(pwd)) { Utils.showDialog(THIS, R.string.err_field_empty); return; } if (!Utils.isValidEmail(email)) { Utils.showDialog(THIS, R.string.err_email); return; } final ProgressDialog dia = showProgressDia(R.string.alert_wait); new Thread(new Runnable() { @Override public void run() { final Status st = WebHelper.doRegister(name, email, pwd); runOnUiThread(new Runnable() { @Override public void run() { dia.dismiss(); if (!st.isSuccess()) Utils.showDialog(THIS, st.getMessage()); else { StaticData.pref.edit() .putString(Const.USER_ID, st.getData()) .commit(); setResult(RESULT_OK); finish(); } } }); } }).start(); } } <file_sep>/Events/src/com/events/calendar/CalendarView.java package com.events.calendar; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Locale; import android.app.ProgressDialog; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.os.Handler; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.events.EventDetailActivity; import com.events.R; import com.events.custom.CustomActivity; import com.events.custom.CustomFragment; import com.events.model.Event; import com.events.utils.Commons; import com.events.utils.Const; import com.events.utils.ImageLoader; import com.events.utils.ImageLoader.ImageLoadedListener; import com.events.utils.ImageUtils; import com.events.utils.Log; import com.events.utils.StaticData; import com.events.utils.Utils; import com.events.web.WebHelper; /** * The Class CalendarView is Fragment class to hold the Calendar view. */ public class CalendarView extends CustomFragment implements DateChangeListener { /** The item month. */ public GregorianCalendar month, itemmonth;// calendar instances. /** The adapter. */ public CalendarAdapter adapter;// adapter instance /** The handler. */ public Handler handler;// for grabbing some event values for showing the dot // marker. /** The items. */ public ArrayList<String> items; // container to store calendar items which // needs showing the event marker /** The events. */ private final ArrayList<Event> events = new ArrayList<Event>(); /** The list. */ private ListView list; /** The events for selected date. */ private ArrayList<Event> eventSel; /* (non-Javadoc) * @see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle) */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View v = inflater.inflate(R.layout.calendar, null); setHasOptionsMenu(true); setupEventList(v); initCalendarView(v); return v; } /** * Initialize the calendar view. * * @param v * the v */ private void initCalendarView(View v) { month = (GregorianCalendar) Calendar.getInstance(); itemmonth = (GregorianCalendar) month.clone(); items = new ArrayList<String>(); adapter = new CalendarAdapter(getActivity(), month); adapter.setDateChangeListener(this); GridView gridview = (GridView) v.findViewById(R.id.gridview); gridview.setAdapter(adapter); handler = new Handler(); TextView title = (TextView) v.findViewById(R.id.title); title.setText(android.text.format.DateFormat.format("MMMM yyyy", month)); RelativeLayout previous = (RelativeLayout) v .findViewById(R.id.previous); previous.setOnTouchListener(CustomActivity.TOUCH); previous.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { setPreviousMonth(); refreshCalendar(getView()); } }); RelativeLayout next = (RelativeLayout) v.findViewById(R.id.next); next.setOnTouchListener(CustomActivity.TOUCH); next.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { setNextMonth(); refreshCalendar(getView()); } }); gridview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View v, int position, long id) { ((CalendarAdapter) parent.getAdapter()) .setSelected(position, v); } }); refreshCalendar(v); } /** * Set the up event list. * * @param v * the root view */ private void setupEventList(View v) { int w = StaticData.getDIP(60); int h = StaticData.getDIP(60); bmNoImg = ImageUtils.getPlaceHolderImage(R.drawable.no_image, w, h); loader = new ImageLoader(w, h, ImageUtils.SCALE_FIT_CENTER); eventSel = new ArrayList<Event>(); list = (ListView) v.findViewById(R.id.list); list.setAdapter(new EventAdapter()); list.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { startActivity(new Intent(getActivity(), EventDetailActivity.class).putExtra(Const.EXTRA_DATA, eventSel.get(position))); } }); } /** * Sets the next month. */ protected void setNextMonth() { if (month.get(Calendar.MONTH) == month.getActualMaximum(Calendar.MONTH)) { month.set(month.get(Calendar.YEAR) + 1, month.getActualMinimum(Calendar.MONTH), 1); } else { month.set(Calendar.MONTH, month.get(Calendar.MONTH) + 1); } } /** * Sets the previous month. */ protected void setPreviousMonth() { if (month.get(Calendar.MONTH) == month.getActualMinimum(Calendar.MONTH)) { month.set(month.get(Calendar.YEAR) - 1, month.getActualMaximum(Calendar.MONTH), 1); } else { month.set(Calendar.MONTH, month.get(Calendar.MONTH) - 1); } } /** * Show toast. * * @param string * the string message */ protected void showToast(String string) { Toast.makeText(getActivity(), string, Toast.LENGTH_SHORT).show(); } /** * Refresh calendar. * * @param v the v */ public void refreshCalendar(View v) { TextView title = (TextView) v.findViewById(R.id.title); onDateChange(0, 0); adapter.refreshDays(); adapter.notifyDataSetChanged(); final ProgressDialog dia = parent .showProgressDia(R.string.alert_loading); new Thread(new Runnable() { @Override public void run() { final ArrayList<Event> al = WebHelper.getEventsByMonth( month.get(Calendar.MONTH) + 1 + "", month.get(Calendar.YEAR) + ""); parent.runOnUiThread(new Runnable() { @Override public void run() { dia.dismiss(); events.clear(); if (al == null) Utils.showDialog(parent, StaticData.getErrorMessage()); else events.addAll(al); handler.post(calendarUpdater); } }); } }).start(); title.setText(android.text.format.DateFormat.format("MMMM yyyy", month)); } /** The calendar updater to update the Calendar grids and data. */ public Runnable calendarUpdater = new Runnable() { @Override public void run() { items.clear(); DateFormat df = new SimpleDateFormat("dd-MMM-yyyy", Locale.US); for (int i = 0; i < events.size(); i++) { df.format(itemmonth.getTime()); itemmonth.add(Calendar.DATE, 1); // items.add(events.get(i).getStartDate().toString()); } adapter.setItems(events); adapter.notifyDataSetChanged(); } }; /* (non-Javadoc) * @see android.support.v4.app.Fragment#onCreateOptionsMenu(android.view.Menu, android.view.MenuInflater) */ @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); } /** * The Class EventAdapter is the adapter class that is used show list of * Events for a selected date in the ListView. */ private class EventAdapter extends BaseAdapter { /* (non-Javadoc) * @see android.widget.Adapter#getCount() */ @Override public int getCount() { return eventSel.size(); } /* (non-Javadoc) * @see android.widget.Adapter#getItem(int) */ @Override public Event getItem(int position) { return eventSel.get(position); } /* (non-Javadoc) * @see android.widget.Adapter#getItemId(int) */ @Override public long getItemId(int position) { return position; } /* (non-Javadoc) * @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup) */ @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) convertView = getLayoutInflater(null).inflate( R.layout.event_item, null); Event d = getItem(position); TextView lbl = (TextView) convertView.findViewById(R.id.lbl1); lbl.setText(Commons.millsToDate(d.getStartDateTime())); lbl = (TextView) convertView.findViewById(R.id.lbl2); lbl.setText(Commons.millsToTime(d.getStartDateTime())); lbl = (TextView) convertView.findViewById(R.id.lbl3); lbl.setText(d.getTitle()); lbl = (TextView) convertView.findViewById(R.id.lbl4); lbl.setText(d.getLocation()); ImageView img = (ImageView) convertView.findViewById(R.id.img); Bitmap bm = loader.loadImage(d.getImage(), new ImageLoadedListener() { @Override public void imageLoaded(Bitmap bm) { if (bm != null) notifyDataSetChanged(); } }); if (bm == null) img.setImageBitmap(bmNoImg); else img.setImageBitmap(bm); return convertView; } } /* (non-Javadoc) * @see com.events.calendar.DateChangeListener#onDateChange(int, long) */ @Override public void onDateChange(int position, long d) { eventSel.clear(); if (d > 0) { String selectedGridDate = CalendarAdapter.dayString.get(position); String[] separatedTime = selectedGridDate.split("-"); String gridvalueString = separatedTime[2].replaceFirst("^0*", "");// taking // last // part // of // date. // ie; // 2 // from // 2012-12-02. int gridvalue = Integer.parseInt(gridvalueString); // navigate to next or previous month on clicking offdays. if (gridvalue > 10 && position < 8) { setPreviousMonth(); refreshCalendar(getView()); } else if (gridvalue < 7 && position > 28) { setNextMonth(); refreshCalendar(getView()); } for (Event e : events) { Calendar c1 = Calendar.getInstance(); c1.setTimeInMillis(d); Calendar c2 = Calendar.getInstance(); c2.setTimeInMillis(e.getStartDateTime()); // if (e.getStartDateTime() <= d && e.getEndDateTime() >= d) if (c1.get(Calendar.DAY_OF_MONTH) == c2 .get(Calendar.DAY_OF_MONTH) && c1.get(Calendar.MONTH) == c2.get(Calendar.MONTH) && c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR)) { eventSel.add(e); } } } Log.e("Ev Count=" + eventSel.size()); ((BaseAdapter) list.getAdapter()).notifyDataSetChanged(); } } <file_sep>/Events/src/com/events/ui/More.java package com.events.ui; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.events.MoreDetail; import com.events.R; import com.events.custom.CustomFragment; import com.events.utils.Const; /** * The Class More is the Fragment class that is launched when the user clicks on * More option in Left navigation drawer and it simply shows a few options for * like Help, Privacy, Account, About etc. You can customize this to display * actual contents. */ public class More extends CustomFragment { /* (non-Javadoc) * @see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle) */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View v = inflater.inflate(R.layout.more, null); setTouchNClick(v.findViewById(R.id.help)); setTouchNClick(v.findViewById(R.id.privacy)); setTouchNClick(v.findViewById(R.id.terms)); return v; } /* (non-Javadoc) * @see com.events.custom.CustomFragment#onClick(android.view.View) */ @Override public void onClick(View v) { super.onClick(v); int title; int text; if (v.getId() == R.id.help) { title = R.string.help_center; text = R.string.help_centre_text; } else if (v.getId() == R.id.privacy) { title = R.string.privacy; text = R.string.privacy_text; } else { title = R.string.terms_condi; text = R.string.terms_text; } startActivity(new Intent(parent, MoreDetail.class).putExtra( Const.EXTRA_DATA, text).putExtra(Const.EXTRA_DATA1, title)); } } <file_sep>/Events/doc/com/events/utils/ImageLoader.html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_45) on Thu Nov 06 00:57:41 IST 2014 --> <title>ImageLoader</title> <meta name="date" content="2014-11-06"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="ImageLoader"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/ImageLoader.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-files/index-1.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../com/events/utils/ExceptionHandler.html" title="class in com.events.utils"><span class="strong">Prev Class</span></a></li> <li><a href="../../../com/events/utils/ImageLoader.ImageLoadedListener.html" title="interface in com.events.utils"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?com/events/utils/ImageLoader.html" target="_top">Frames</a></li> <li><a href="ImageLoader.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li><a href="#nested_class_summary">Nested</a>&nbsp;|&nbsp;</li> <li><a href="#field_summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field_detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">com.events.utils</div> <h2 title="Class ImageLoader" class="title">Class ImageLoader</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li><a href="../../../com/events/utils/ImageUtils.html" title="class in com.events.utils">com.events.utils.ImageUtils</a></li> <li> <ul class="inheritance"> <li>com.events.utils.ImageLoader</li> </ul> </li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public class <span class="strong">ImageLoader</span> extends <a href="../../../com/events/utils/ImageUtils.html" title="class in com.events.utils">ImageUtils</a></pre> <div class="block">The Class ImageLoader.</div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== NESTED CLASS SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="nested_class_summary"> <!-- --> </a> <h3>Nested Class Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Nested Class Summary table, listing nested classes, and an explanation"> <caption><span>Nested Classes</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>static interface&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../com/events/utils/ImageLoader.ImageLoadedListener.html" title="interface in com.events.utils">ImageLoader.ImageLoadedListener</a></strong></code> <div class="block">The listener interface for receiving imageLoaded events.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../com/events/utils/ImageLoader.QueueItem.html" title="class in com.events.utils">ImageLoader.QueueItem</a></strong></code> <div class="block">The Class QueueItem.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../com/events/utils/ImageLoader.QueueRunner.html" title="class in com.events.utils">ImageLoader.QueueRunner</a></strong></code> <div class="block">The Class QueueRunner.</div> </td> </tr> </table> </li> </ul> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field_summary"> <!-- --> </a> <h3>Field Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation"> <caption><span>Fields</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>private java.util.HashMap&lt;java.lang.String,java.lang.ref.SoftReference&lt;android.graphics.Bitmap&gt;&gt;</code></td> <td class="colLast"><code><strong><a href="../../../com/events/utils/ImageLoader.html#Cache">Cache</a></strong></code> <div class="block">The Cache.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>private int</code></td> <td class="colLast"><code><strong><a href="../../../com/events/utils/ImageLoader.html#h">h</a></strong></code> <div class="block">The h.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>private android.os.Handler</code></td> <td class="colLast"><code><strong><a href="../../../com/events/utils/ImageLoader.html#handler">handler</a></strong></code> <div class="block">The handler.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>private boolean</code></td> <td class="colLast"><code><strong><a href="../../../com/events/utils/ImageLoader.html#local">local</a></strong></code> <div class="block">The local.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>private static long</code></td> <td class="colLast"><code><strong><a href="../../../com/events/utils/ImageLoader.html#MAX_BM_SIZE">MAX_BM_SIZE</a></strong></code> <div class="block">The Constant MAX_BM_SIZE.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>private java.util.ArrayList&lt;<a href="../../../com/events/utils/ImageLoader.QueueItem.html" title="class in com.events.utils">ImageLoader.QueueItem</a>&gt;</code></td> <td class="colLast"><code><strong><a href="../../../com/events/utils/ImageLoader.html#Queue">Queue</a></strong></code> <div class="block">The Queue.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>private <a href="../../../com/events/utils/ImageLoader.QueueRunner.html" title="class in com.events.utils">ImageLoader.QueueRunner</a></code></td> <td class="colLast"><code><strong><a href="../../../com/events/utils/ImageLoader.html#runner">runner</a></strong></code> <div class="block">The runner.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../com/events/utils/ImageLoader.html#saveInMainThread">saveInMainThread</a></strong></code> <div class="block">The save in main thread.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>private int</code></td> <td class="colLast"><code><strong><a href="../../../com/events/utils/ImageLoader.html#scale">scale</a></strong></code> <div class="block">The scale.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>private java.lang.Thread</code></td> <td class="colLast"><code><strong><a href="../../../com/events/utils/ImageLoader.html#thread">thread</a></strong></code> <div class="block">The thread.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>private int</code></td> <td class="colLast"><code><strong><a href="../../../com/events/utils/ImageLoader.html#w">w</a></strong></code> <div class="block">The w.</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="fields_inherited_from_class_com.events.utils.ImageUtils"> <!-- --> </a> <h3>Fields inherited from class&nbsp;com.events.utils.<a href="../../../com/events/utils/ImageUtils.html" title="class in com.events.utils">ImageUtils</a></h3> <code><a href="../../../com/events/utils/ImageUtils.html#SCALE_ASPECT">SCALE_ASPECT</a>, <a href="../../../com/events/utils/ImageUtils.html#SCALE_ASPECT_HEIGHT">SCALE_ASPECT_HEIGHT</a>, <a href="../../../com/events/utils/ImageUtils.html#SCALE_ASPECT_WIDTH">SCALE_ASPECT_WIDTH</a>, <a href="../../../com/events/utils/ImageUtils.html#SCALE_CROP">SCALE_CROP</a>, <a href="../../../com/events/utils/ImageUtils.html#SCALE_FIT_CENTER">SCALE_FIT_CENTER</a>, <a href="../../../com/events/utils/ImageUtils.html#SCALE_FIT_CENTER_NO_COL">SCALE_FIT_CENTER_NO_COL</a>, <a href="../../../com/events/utils/ImageUtils.html#SCALE_FIT_MIN_WH">SCALE_FIT_MIN_WH</a>, <a href="../../../com/events/utils/ImageUtils.html#SCALE_FIT_WIDTH">SCALE_FIT_WIDTH</a>, <a href="../../../com/events/utils/ImageUtils.html#SCALE_FITXY">SCALE_FITXY</a>, <a href="../../../com/events/utils/ImageUtils.html#SCALE_NONE">SCALE_NONE</a></code></li> </ul> </li> </ul> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../com/events/utils/ImageLoader.html#ImageLoader(int, int)">ImageLoader</a></strong>(int&nbsp;w, int&nbsp;h)</code> <div class="block">Instantiates a new image loader.</div> </td> </tr> <tr class="rowColor"> <td class="colOne"><code><strong><a href="../../../com/events/utils/ImageLoader.html#ImageLoader(int, int, int)">ImageLoader</a></strong>(int&nbsp;w, int&nbsp;h, int&nbsp;scale)</code> <div class="block">Instantiates a new image loader.</div> </td> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../com/events/utils/ImageLoader.html#ImageLoader(int, int, int, boolean)">ImageLoader</a></strong>(int&nbsp;w, int&nbsp;h, int&nbsp;scale, boolean&nbsp;local)</code> <div class="block">Instantiates a new image loader.</div> </td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../com/events/utils/ImageLoader.html#clear()">clear</a></strong>()</code> <div class="block">Clear.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.io.File</code></td> <td class="colLast"><code><strong><a href="../../../com/events/utils/ImageLoader.html#getImageFile(java.lang.String)">getImageFile</a></strong>(java.lang.String&nbsp;file)</code> <div class="block">Gets the image file.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>android.graphics.Bitmap</code></td> <td class="colLast"><code><strong><a href="../../../com/events/utils/ImageLoader.html#loadBitmap(java.lang.String)">loadBitmap</a></strong>(java.lang.String&nbsp;path)</code> <div class="block">Load bitmap.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>android.graphics.Bitmap</code></td> <td class="colLast"><code><strong><a href="../../../com/events/utils/ImageLoader.html#loadImage(java.lang.String, com.events.utils.ImageLoader.ImageLoadedListener)">loadImage</a></strong>(java.lang.String&nbsp;uri, <a href="../../../com/events/utils/ImageLoader.ImageLoadedListener.html" title="interface in com.events.utils">ImageLoader.ImageLoadedListener</a>&nbsp;listener)</code> <div class="block">Load image.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>android.graphics.Bitmap</code></td> <td class="colLast"><code><strong><a href="../../../com/events/utils/ImageLoader.html#loadSingleImage(java.lang.String, android.widget.BaseAdapter)">loadSingleImage</a></strong>(java.lang.String&nbsp;url, android.widget.BaseAdapter&nbsp;adapter)</code> <div class="block">Load single image.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../com/events/utils/ImageLoader.html#loadSingleImageBm(java.lang.String, android.widget.ImageView, int)">loadSingleImageBm</a></strong>(java.lang.String&nbsp;path, android.widget.ImageView&nbsp;v, int&nbsp;defImg)</code> <div class="block">Load single image bm.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>android.graphics.Bitmap</code></td> <td class="colLast"><code><strong><a href="../../../com/events/utils/ImageLoader.html#readBitmapFromCache(java.lang.String, boolean)">readBitmapFromCache</a></strong>(java.lang.String&nbsp;file, boolean&nbsp;compress)</code> <div class="block">Read bitmap from cache.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>private android.graphics.Bitmap</code></td> <td class="colLast"><code><strong><a href="../../../com/events/utils/ImageLoader.html#readBitmapFromNetwork(java.lang.String)">readBitmapFromNetwork</a></strong>(java.lang.String&nbsp;urlStr)</code> <div class="block">Read bitmap from network.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../com/events/utils/ImageLoader.html#setLocal(boolean)">setLocal</a></strong>(boolean&nbsp;local)</code> <div class="block">Sets the local.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../com/events/utils/ImageLoader.html#writeBitmapToCache(android.graphics.Bitmap, java.lang.String)">writeBitmapToCache</a></strong>(android.graphics.Bitmap&nbsp;bm, java.lang.String&nbsp;url)</code> <div class="block">Write bitmap to cache.</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_com.events.utils.ImageUtils"> <!-- --> </a> <h3>Methods inherited from class&nbsp;com.events.utils.<a href="../../../com/events/utils/ImageUtils.html" title="class in com.events.utils">ImageUtils</a></h3> <code><a href="../../../com/events/utils/ImageUtils.html#getCircularBitmap(android.graphics.Bitmap)">getCircularBitmap</a>, <a href="../../../com/events/utils/ImageUtils.html#getColorFramedBitmap(android.graphics.Bitmap)">getColorFramedBitmap</a>, <a href="../../../com/events/utils/ImageUtils.html#getCompressedBm(byte[], int, int, int)">getCompressedBm</a>, <a href="../../../com/events/utils/ImageUtils.html#getCompressedBm(java.io.File, int, int, int)">getCompressedBm</a>, <a href="../../../com/events/utils/ImageUtils.html#getFramedBitmap(android.graphics.Bitmap)">getFramedBitmap</a>, <a href="../../../com/events/utils/ImageUtils.html#getMaskShapedBitmap(android.graphics.Bitmap, int)">getMaskShapedBitmap</a>, <a href="../../../com/events/utils/ImageUtils.html#getOrientationFixedFramedImage(java.io.File, int, int, int)">getOrientationFixedFramedImage</a>, <a href="../../../com/events/utils/ImageUtils.html#getOrientationFixedImage(java.io.File, int, int, int)">getOrientationFixedImage</a>, <a href="../../../com/events/utils/ImageUtils.html#getPlaceHolderImage(int, int, int)">getPlaceHolderImage</a>, <a href="../../../com/events/utils/ImageUtils.html#getRoundedCornerBitmap(android.graphics.Bitmap)">getRoundedCornerBitmap</a>, <a href="../../../com/events/utils/ImageUtils.html#saveCompressedBm(java.lang.String, java.lang.String)">saveCompressedBm</a>, <a href="../../../com/events/utils/ImageUtils.html#saveOrientationFixImage(java.io.File, java.io.File, int, int, int)">saveOrientationFixImage</a></code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ FIELD DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="field_detail"> <!-- --> </a> <h3>Field Detail</h3> <a name="MAX_BM_SIZE"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>MAX_BM_SIZE</h4> <pre>private static final&nbsp;long MAX_BM_SIZE</pre> <div class="block">The Constant MAX_BM_SIZE.</div> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../constant-values.html#com.events.utils.ImageLoader.MAX_BM_SIZE">Constant Field Values</a></dd></dl> </li> </ul> <a name="Cache"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>Cache</h4> <pre>private final&nbsp;java.util.HashMap&lt;java.lang.String,java.lang.ref.SoftReference&lt;android.graphics.Bitmap&gt;&gt; Cache</pre> <div class="block">The Cache.</div> </li> </ul> <a name="w"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>w</h4> <pre>private&nbsp;int w</pre> <div class="block">The w.</div> </li> </ul> <a name="h"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>h</h4> <pre>private&nbsp;int h</pre> <div class="block">The h.</div> </li> </ul> <a name="scale"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>scale</h4> <pre>private&nbsp;int scale</pre> <div class="block">The scale.</div> </li> </ul> <a name="local"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>local</h4> <pre>private&nbsp;boolean local</pre> <div class="block">The local.</div> </li> </ul> <a name="saveInMainThread"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>saveInMainThread</h4> <pre>public&nbsp;boolean saveInMainThread</pre> <div class="block">The save in main thread.</div> </li> </ul> <a name="Queue"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>Queue</h4> <pre>private final&nbsp;java.util.ArrayList&lt;<a href="../../../com/events/utils/ImageLoader.QueueItem.html" title="class in com.events.utils">ImageLoader.QueueItem</a>&gt; Queue</pre> <div class="block">The Queue.</div> </li> </ul> <a name="handler"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>handler</h4> <pre>private final&nbsp;android.os.Handler handler</pre> <div class="block">The handler.</div> </li> </ul> <a name="thread"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>thread</h4> <pre>private&nbsp;java.lang.Thread thread</pre> <div class="block">The thread.</div> </li> </ul> <a name="runner"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>runner</h4> <pre>private&nbsp;<a href="../../../com/events/utils/ImageLoader.QueueRunner.html" title="class in com.events.utils">ImageLoader.QueueRunner</a> runner</pre> <div class="block">The runner.</div> </li> </ul> </li> </ul> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="ImageLoader(int, int)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>ImageLoader</h4> <pre>public&nbsp;ImageLoader(int&nbsp;w, int&nbsp;h)</pre> <div class="block">Instantiates a new image loader.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>w</code> - the w</dd><dd><code>h</code> - the h</dd></dl> </li> </ul> <a name="ImageLoader(int, int, int)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>ImageLoader</h4> <pre>public&nbsp;ImageLoader(int&nbsp;w, int&nbsp;h, int&nbsp;scale)</pre> <div class="block">Instantiates a new image loader.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>w</code> - the w</dd><dd><code>h</code> - the h</dd><dd><code>scale</code> - the scale</dd></dl> </li> </ul> <a name="ImageLoader(int, int, int, boolean)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>ImageLoader</h4> <pre>public&nbsp;ImageLoader(int&nbsp;w, int&nbsp;h, int&nbsp;scale, boolean&nbsp;local)</pre> <div class="block">Instantiates a new image loader.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>w</code> - the w</dd><dd><code>h</code> - the h</dd><dd><code>scale</code> - the scale</dd><dd><code>local</code> - the local</dd></dl> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="clear()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>clear</h4> <pre>public&nbsp;void&nbsp;clear()</pre> <div class="block">Clear.</div> </li> </ul> <a name="setLocal(boolean)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setLocal</h4> <pre>public&nbsp;void&nbsp;setLocal(boolean&nbsp;local)</pre> <div class="block">Sets the local.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>local</code> - the new local</dd></dl> </li> </ul> <a name="loadImage(java.lang.String, com.events.utils.ImageLoader.ImageLoadedListener)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>loadImage</h4> <pre>public&nbsp;android.graphics.Bitmap&nbsp;loadImage(java.lang.String&nbsp;uri, <a href="../../../com/events/utils/ImageLoader.ImageLoadedListener.html" title="interface in com.events.utils">ImageLoader.ImageLoadedListener</a>&nbsp;listener)</pre> <div class="block">Load image.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>uri</code> - the uri</dd><dd><code>listener</code> - the listener</dd> <dt><span class="strong">Returns:</span></dt><dd>the bitmap</dd></dl> </li> </ul> <a name="readBitmapFromCache(java.lang.String, boolean)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>readBitmapFromCache</h4> <pre>public&nbsp;android.graphics.Bitmap&nbsp;readBitmapFromCache(java.lang.String&nbsp;file, boolean&nbsp;compress)</pre> <div class="block">Read bitmap from cache.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>file</code> - the file</dd><dd><code>compress</code> - the compress</dd> <dt><span class="strong">Returns:</span></dt><dd>the bitmap</dd></dl> </li> </ul> <a name="writeBitmapToCache(android.graphics.Bitmap, java.lang.String)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>writeBitmapToCache</h4> <pre>public&nbsp;void&nbsp;writeBitmapToCache(android.graphics.Bitmap&nbsp;bm, java.lang.String&nbsp;url)</pre> <div class="block">Write bitmap to cache.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>bm</code> - the bm</dd><dd><code>url</code> - the url</dd></dl> </li> </ul> <a name="readBitmapFromNetwork(java.lang.String)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>readBitmapFromNetwork</h4> <pre>private&nbsp;android.graphics.Bitmap&nbsp;readBitmapFromNetwork(java.lang.String&nbsp;urlStr)</pre> <div class="block">Read bitmap from network.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>urlStr</code> - the url str</dd> <dt><span class="strong">Returns:</span></dt><dd>the bitmap</dd></dl> </li> </ul> <a name="loadSingleImage(java.lang.String, android.widget.BaseAdapter)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>loadSingleImage</h4> <pre>public&nbsp;android.graphics.Bitmap&nbsp;loadSingleImage(java.lang.String&nbsp;url, android.widget.BaseAdapter&nbsp;adapter)</pre> <div class="block">Load single image.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>url</code> - the url</dd><dd><code>adapter</code> - the adapter</dd> <dt><span class="strong">Returns:</span></dt><dd>the bitmap</dd></dl> </li> </ul> <a name="loadSingleImageBm(java.lang.String, android.widget.ImageView, int)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>loadSingleImageBm</h4> <pre>public&nbsp;void&nbsp;loadSingleImageBm(java.lang.String&nbsp;path, android.widget.ImageView&nbsp;v, int&nbsp;defImg)</pre> <div class="block">Load single image bm.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>path</code> - the path</dd><dd><code>v</code> - the v</dd><dd><code>defImg</code> - the def img</dd></dl> </li> </ul> <a name="loadBitmap(java.lang.String)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>loadBitmap</h4> <pre>public&nbsp;android.graphics.Bitmap&nbsp;loadBitmap(java.lang.String&nbsp;path)</pre> <div class="block">Load bitmap.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>path</code> - the path</dd> <dt><span class="strong">Returns:</span></dt><dd>the bitmap</dd></dl> </li> </ul> <a name="getImageFile(java.lang.String)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>getImageFile</h4> <pre>public&nbsp;java.io.File&nbsp;getImageFile(java.lang.String&nbsp;file)</pre> <div class="block">Gets the image file.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>file</code> - the file</dd> <dt><span class="strong">Returns:</span></dt><dd>the image file</dd></dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/ImageLoader.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-files/index-1.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../com/events/utils/ExceptionHandler.html" title="class in com.events.utils"><span class="strong">Prev Class</span></a></li> <li><a href="../../../com/events/utils/ImageLoader.ImageLoadedListener.html" title="interface in com.events.utils"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?com/events/utils/ImageLoader.html" target="_top">Frames</a></li> <li><a href="ImageLoader.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li><a href="#nested_class_summary">Nested</a>&nbsp;|&nbsp;</li> <li><a href="#field_summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field_detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html> <file_sep>/Events/src/com/events/web/WebHelper.java package com.events.web; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Comparator; import java.util.Locale; import java.util.TreeSet; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONObject; import com.events.database.DbHelper; import com.events.model.Event; import com.events.model.Feed; import com.events.model.Status; import com.events.utils.Commons; /** * The Class WebHelper class holds all the methods that communicate with server * API and parses the results in required Java Bean classes. */ public class WebHelper extends WebAccess { /** * Gets the events. * * @param page * the page * @param pageSize * the page size * @return the events */ public static ArrayList<Event> getEvents(int page, int pageSize) { try { String url = EVENT_LIST_URL; url = getPageParams(url, page, pageSize); // url=getUserParams(url); String res = executeGetRequest(url, true); return parseEvents(res); } catch (Exception e) { e.printStackTrace(); } return null; } /** * Parses the events. * * @param res * the res * @return the array list * @throws Exception * the exception */ private static ArrayList<Event> parseEvents(String res) throws Exception { JSONArray obj = new JSONArray(res); TreeSet<Event> al = new TreeSet<Event>(new Comparator<Event>() { @Override public int compare(Event lhs, Event rhs) { if (lhs.getStartDateTime() == rhs.getStartDateTime()) return rhs.getTitle().compareTo(lhs.getTitle()); return rhs.getStartDateTime() > lhs.getStartDateTime() ? -1 : 1; } }); for (int i = 0; i < obj.length(); i++) { JSONObject js = obj.getJSONObject(i); if (js.has("status") && js.has("message") && obj.length() == 1) return new ArrayList<Event>(); al.add(parseEvent(js)); } return new ArrayList<Event>(al); } /** * Parses the event. * * @param js * the js * @return the event * @throws Exception * the exception */ private static Event parseEvent(JSONObject js) throws Exception { Event e = new Event(); e.setTitle(js.getString("event_name")); e.setId(js.getString("event_id")); e.setStartDate(js.getString("event_start_date")); e.setStartTime(js.getString("event_start_time")); e.setImage(js.getString("event_image_url")); e.setDesc(js.getString("event_content")); e.setEndDate(js.getString("event_end_date")); e.setEndTime(js.getString("event_end_time")); e.setLocation(js.getString("location_address") + ", " + js.getString("location_town") + ", " + js.getString("location_state") + ", " + js.getString("location_region") + ", " + js.getString("location_country") + "- " + js.getString("location_postcode")); e.setLocation(e.getLocation().replaceAll(", null", "")); e.setLocation(e.getLocation().replaceAll("- null", "")); // e.setFav("1".equalsIgnoreCase(js.optString("is_favorite"))); e.setFav(DbHelper.isEventFavorite(e.getId())); e.setLatitude(Commons.strToDouble(js.getString("location_latitude"))); e.setLongitude(Commons.strToDouble(js.getString("location_longitude"))); try { e.setPrice(Commons.strToDouble(js.getJSONObject("ticket") .getString("ticket_price"))); e.setAvailSpace(Commons.strToInt(js.getJSONObject("ticket") .getString("avail_spaces"))); } catch (Exception e2) { e2.printStackTrace(); } /*while(e.getDesc().startsWith("/n")||e.getDesc().startsWith("/r")) e.setDesc(e.getDesc().substring(1)); while(e.getDesc().endsWith("/n")||e.getDesc().endsWith("/r")) e.setDesc(e.getDesc().substring(0,e.getDesc().length()-1));*/ return e; } /** * Parses the date. * * @param tw * the tw * @param str * the str * @return the long */ private static long parseDate(boolean tw, String str) { String format = tw ? "EEE MMM dd kk:mm:ss Z yyyy" : "yyyy-MM-dd'T'kk:mm:ssZ"; try { return new SimpleDateFormat(format, Locale.US).parse(str).getTime(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return System.currentTimeMillis(); } /** * Gets the feed list. * * @return the feed list */ public static ArrayList<Feed> getFeedList() { TreeSet<Feed> al = new TreeSet<Feed>(new Comparator<Feed>() { @Override public int compare(Feed lhs, Feed rhs) { if (lhs.getDate() == rhs.getDate()) return 1; return rhs.getDate() > lhs.getDate() ? 1 : -1; } }); try { String res = executePostRequest(FEED_URL, null, true); JSONObject obj = new JSONObject(res); JSONArray arr = obj.getJSONArray("twitter_feeds"); for (int i = 0; i < arr.length(); i++) { JSONObject js = arr.getJSONObject(i); Feed f = new Feed(); f.setType(Feed.FEED_TW); f.setDate(parseDate(true, js.getString("created_at"))); f.setImage(js.getJSONObject("user").optString( "profile_image_url")); f.setLink(js.optString("tweet_url")); f.setMsg(js.optString("text")); f.setTitle(js.getJSONObject("user").optString("name")); al.add(f); } arr = obj.getJSONArray("fb_feeds"); for (int i = 0; i < arr.length(); i++) { JSONObject js = arr.getJSONObject(i); Feed f = new Feed(); f.setType(Feed.FEED_FB); f.setDate(parseDate(false, js.getString("created_time"))); f.setImage(js.optString("picture")); f.setLink(js.optString("link")); f.setMsg(js.optString("message")); f.setTitle(js.optString("")); al.add(f); } arr = obj.getJSONArray("instagram_feeds"); for (int i = 0; i < arr.length(); i++) { JSONObject js = arr.getJSONObject(i); Feed f = new Feed(); f.setType(Feed.FEED_IG); f.setDate(Long.parseLong(js.getString("created_time")) * 1000); f.setImage(js.optJSONObject("images") .getJSONObject("low_resolution").getString("url")); f.setLink(js.optString("link")); f.setMsg(js.optString("text")); if (Commons.isEmpty(f.getMsg())) f.setMsg("@" + js.optJSONObject("user").getString("username")); f.setTitle(js.optJSONObject("user").getString("full_name")); al.add(f); } } catch (Exception e) { e.printStackTrace(); } return new ArrayList<Feed>(al); } /** * Gets the events by month. * * @param month * the month * @param year * the year * @return the events by month */ public static ArrayList<Event> getEventsByMonth(String month, String year) { try { ArrayList<NameValuePair> param = new ArrayList<NameValuePair>(); param.add(new BasicNameValuePair("month", month)); param.add(new BasicNameValuePair("year", year)); String res = executePostRequest(EVENT_BY_MONTH_URL, param, true); return parseEvents(res); } catch (Exception e) { e.printStackTrace(); } return null; } /** * Checks if is booked. * * @param e * the e * @return true, if is booked */ public static boolean isBooked(Event e) { try { ArrayList<NameValuePair> param = getUserParams(); param.add(new BasicNameValuePair("event_id", e.getId())); String res = executePostRequest(CHECK_BOOK_URL, param, true); e.setBooked(new Status(new JSONArray(res).getJSONObject(0)) .isSuccess()); return e.isBooked(); } catch (Exception ex) { ex.printStackTrace(); } return false; } /** * Do login. * * @param email * the email * @param pwd * the pwd * @return the status */ public static Status doLogin(String email, String pwd) { try { ArrayList<NameValuePair> param = new ArrayList<NameValuePair>(); param.add(new BasicNameValuePair("email", email)); param.add(new BasicNameValuePair("pwd", pwd)); String res = executePostRequest(LOGIN_URL, param, false); return new Status(res, "user_id"); } catch (Exception ex) { ex.printStackTrace(); } return new Status(); } /** * Do register. * * @param name * the name * @param email * the email * @param pwd * the pwd * @return the status */ public static Status doRegister(String name, String email, String pwd) { try { ArrayList<NameValuePair> param = new ArrayList<NameValuePair>(); param.add(new BasicNameValuePair("name", name)); param.add(new BasicNameValuePair("email", email)); param.add(new BasicNameValuePair("pwd", pwd)); String res = executePostRequest(REGISTER_URL, param, false); return new Status(res, "user_id"); } catch (Exception ex) { ex.printStackTrace(); } return new Status(); } /** * Book tkt. * * @param event_id * the event_id * @param space * the space * @param comment * the comment * @return the status */ public static Status bookTkt(String event_id, String space, String comment) { try { ArrayList<NameValuePair> param = getUserParams(); param.add(new BasicNameValuePair("event_id", event_id)); param.add(new BasicNameValuePair("booking_spaces", space)); param.add(new BasicNameValuePair("booking_comment", comment)); String res = executePostRequest(BOOK_TKT_URL, param, false); return new Status(res, "payment_page_link"); } catch (Exception ex) { ex.printStackTrace(); } return new Status(); } /** * Gets the booked events. * * @param page * the page * @param pageSize * the page size * @return the booked events */ public static ArrayList<Event> getBookedEvents(int page, int pageSize) { try { page++; ArrayList<NameValuePair> param = getUserParams(); param.add(new BasicNameValuePair("page", page + "")); param.add(new BasicNameValuePair("page_size", pageSize + "")); String res = executePostRequest(TKT_LIST_URL, param, true); return parseEvents(res); } catch (Exception e) { e.printStackTrace(); } return null; } } <file_sep>/Events/doc/serialized-form.html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_45) on Thu Nov 06 00:57:42 IST 2014 --> <title>Serialized Form</title> <meta name="date" content="2014-11-06"> <link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Serialized Form"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li>Use</li> <li><a href="overview-tree.html">Tree</a></li> <li><a href="deprecated-list.html">Deprecated</a></li> <li><a href="index-files/index-1.html">Index</a></li> <li><a href="help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="index.html?serialized-form.html" target="_top">Frames</a></li> <li><a href="serialized-form.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 title="Serialized Form" class="title">Serialized Form</h1> </div> <div class="serializedFormContainer"> <ul class="blockList"> <li class="blockList"> <h2 title="Package">Package&nbsp;com.events.model</h2> <ul class="blockList"> <li class="blockList"><a name="com.events.model.Event"> <!-- --> </a> <h3>Class <a href="com/events/model/Event.html" title="class in com.events.model">com.events.model.Event</a> extends java.lang.Object implements Serializable</h3> <dl class="nameValue"> <dt>serialVersionUID:</dt> <dd>2268007184591194673L</dd> </dl> <ul class="blockList"> <li class="blockList"><a name="serializedForm"> <!-- --> </a> <h3>Serialized Fields</h3> <ul class="blockList"> <li class="blockList"> <h4>title</h4> <pre>java.lang.String title</pre> <div class="block">The title.</div> </li> <li class="blockList"> <h4>desc</h4> <pre>java.lang.String desc</pre> <div class="block">The desc.</div> </li> <li class="blockList"> <h4>startDate</h4> <pre>java.lang.String startDate</pre> <div class="block">The start date.</div> </li> <li class="blockList"> <h4>startTime</h4> <pre>java.lang.String startTime</pre> <div class="block">The start time.</div> </li> <li class="blockList"> <h4>startDateTime</h4> <pre>long startDateTime</pre> <div class="block">The start date time.</div> </li> <li class="blockList"> <h4>endDate</h4> <pre>java.lang.String endDate</pre> <div class="block">The end date.</div> </li> <li class="blockList"> <h4>endTime</h4> <pre>java.lang.String endTime</pre> <div class="block">The end time.</div> </li> <li class="blockList"> <h4>endDateTime</h4> <pre>long endDateTime</pre> <div class="block">The end date time.</div> </li> <li class="blockList"> <h4>location</h4> <pre>java.lang.String location</pre> <div class="block">The location.</div> </li> <li class="blockList"> <h4>latitude</h4> <pre>double latitude</pre> <div class="block">The latitude.</div> </li> <li class="blockList"> <h4>longitude</h4> <pre>double longitude</pre> <div class="block">The longitude.</div> </li> <li class="blockList"> <h4>price</h4> <pre>double price</pre> <div class="block">The price.</div> </li> <li class="blockList"> <h4>availSpace</h4> <pre>int availSpace</pre> <div class="block">The avail space.</div> </li> <li class="blockList"> <h4>isFav</h4> <pre>boolean isFav</pre> <div class="block">The is fav.</div> </li> <li class="blockList"> <h4>isBooked</h4> <pre>boolean isBooked</pre> <div class="block">The is booked.</div> </li> <li class="blockList"> <h4>image</h4> <pre>java.lang.String image</pre> <div class="block">The image.</div> </li> <li class="blockListLast"> <h4>id</h4> <pre>java.lang.String id</pre> <div class="block">The id.</div> </li> </ul> </li> </ul> </li> <li class="blockList"><a name="com.events.model.Feed"> <!-- --> </a> <h3>Class <a href="com/events/model/Feed.html" title="class in com.events.model">com.events.model.Feed</a> extends java.lang.Object implements Serializable</h3> <dl class="nameValue"> <dt>serialVersionUID:</dt> <dd>1572509523380762055L</dd> </dl> <ul class="blockList"> <li class="blockList"><a name="serializedForm"> <!-- --> </a> <h3>Serialized Fields</h3> <ul class="blockList"> <li class="blockList"> <h4>title</h4> <pre>java.lang.String title</pre> <div class="block">The title.</div> </li> <li class="blockList"> <h4>msg</h4> <pre>java.lang.String msg</pre> <div class="block">The msg.</div> </li> <li class="blockList"> <h4>link</h4> <pre>java.lang.String link</pre> <div class="block">The link.</div> </li> <li class="blockList"> <h4>date</h4> <pre>long date</pre> <div class="block">The date.</div> </li> <li class="blockList"> <h4>image</h4> <pre>java.lang.String image</pre> <div class="block">The image.</div> </li> <li class="blockListLast"> <h4>type</h4> <pre>int type</pre> <div class="block">The type.</div> </li> </ul> </li> </ul> </li> <li class="blockList"><a name="com.events.model.Status"> <!-- --> </a> <h3>Class <a href="com/events/model/Status.html" title="class in com.events.model">com.events.model.Status</a> extends java.lang.Object implements Serializable</h3> <dl class="nameValue"> <dt>serialVersionUID:</dt> <dd>-589955733594172904L</dd> </dl> <ul class="blockList"> <li class="blockList"><a name="serializedForm"> <!-- --> </a> <h3>Serialized Fields</h3> <ul class="blockList"> <li class="blockList"> <h4>success</h4> <pre>boolean success</pre> <div class="block">The success.</div> </li> <li class="blockList"> <h4>message</h4> <pre>java.lang.String message</pre> <div class="block">The message.</div> </li> <li class="blockListLast"> <h4>data</h4> <pre>java.lang.String data</pre> <div class="block">The data.</div> </li> </ul> </li> </ul> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li>Use</li> <li><a href="overview-tree.html">Tree</a></li> <li><a href="deprecated-list.html">Deprecated</a></li> <li><a href="index-files/index-1.html">Index</a></li> <li><a href="help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="index.html?serialized-form.html" target="_top">Frames</a></li> <li><a href="serialized-form.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html> <file_sep>/Events/doc/index-files/index-7.html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_45) on Thu Nov 06 00:57:42 IST 2014 --> <title>G-Index</title> <meta name="date" content="2014-11-06"> <link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="G-Index"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li>Use</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-6.html">Prev Letter</a></li> <li><a href="index-8.html">Next Letter</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-filesindex-7.html" target="_top">Frames</a></li> <li><a href="index-7.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="contentContainer"><a href="index-1.html">A</a>&nbsp;<a href="index-2.html">B</a>&nbsp;<a href="index-3.html">C</a>&nbsp;<a href="index-4.html">D</a>&nbsp;<a href="index-5.html">E</a>&nbsp;<a href="index-6.html">F</a>&nbsp;<a href="index-7.html">G</a>&nbsp;<a href="index-8.html">H</a>&nbsp;<a href="index-9.html">I</a>&nbsp;<a href="index-10.html">L</a>&nbsp;<a href="index-11.html">M</a>&nbsp;<a href="index-12.html">N</a>&nbsp;<a href="index-13.html">O</a>&nbsp;<a href="index-14.html">P</a>&nbsp;<a href="index-15.html">Q</a>&nbsp;<a href="index-16.html">R</a>&nbsp;<a href="index-17.html">S</a>&nbsp;<a href="index-18.html">T</a>&nbsp;<a href="index-19.html">U</a>&nbsp;<a href="index-20.html">V</a>&nbsp;<a href="index-21.html">W</a>&nbsp;<a href="index-22.html">Z</a>&nbsp;<a name="_G_"> <!-- --> </a> <h2 class="title">G</h2> <dl> <dt><span class="strong"><a href="../com/events/database/DbConst.html#get1(java.lang.String)">get1(String)</a></span> - Static method in class com.events.database.<a href="../com/events/database/DbConst.html" title="class in com.events.database">DbConst</a></dt> <dd> <div class="block">Gets the 1.</div> </dd> <dt><span class="strong"><a href="../com/events/database/DbConst.html#get2(java.lang.String)">get2(String)</a></span> - Static method in class com.events.database.<a href="../com/events/database/DbConst.html" title="class in com.events.database">DbConst</a></dt> <dd> <div class="block">Gets the 2.</div> </dd> <dt><span class="strong"><a href="../com/events/custom/CustomFragment.html#getArg()">getArg()</a></span> - Method in class com.events.custom.<a href="../com/events/custom/CustomFragment.html" title="class in com.events.custom">CustomFragment</a></dt> <dd> <div class="block">Gets the arg.</div> </dd> <dt><span class="strong"><a href="../com/events/model/Event.html#getAvailSpace()">getAvailSpace()</a></span> - Method in class com.events.model.<a href="../com/events/model/Event.html" title="class in com.events.model">Event</a></dt> <dd> <div class="block">Gets the avail space.</div> </dd> <dt><span class="strong"><a href="../com/events/utils/Utils.html#getBase64ImageString(java.lang.String)">getBase64ImageString(String)</a></span> - Static method in class com.events.utils.<a href="../com/events/utils/Utils.html" title="class in com.events.utils">Utils</a></dt> <dd> <div class="block">Gets the base64 image string.</div> </dd> <dt><span class="strong"><a href="../com/events/web/WebHelper.html#getBookedEvents(int, int)">getBookedEvents(int, int)</a></span> - Static method in class com.events.web.<a href="../com/events/web/WebHelper.html" title="class in com.events.web">WebHelper</a></dt> <dd> <div class="block">Gets the booked events.</div> </dd> <dt><span class="strong"><a href="../com/events/utils/ImageUtils.html#getCircularBitmap(android.graphics.Bitmap)">getCircularBitmap(Bitmap)</a></span> - Static method in class com.events.utils.<a href="../com/events/utils/ImageUtils.html" title="class in com.events.utils">ImageUtils</a></dt> <dd> <div class="block">Gets the circular bitmap.</div> </dd> <dt><span class="strong"><a href="../com/events/utils/ImageUtils.html#getColorFramedBitmap(android.graphics.Bitmap)">getColorFramedBitmap(Bitmap)</a></span> - Static method in class com.events.utils.<a href="../com/events/utils/ImageUtils.html" title="class in com.events.utils">ImageUtils</a></dt> <dd> <div class="block">Gets the color framed bitmap.</div> </dd> <dt><span class="strong"><a href="../com/events/utils/ImageUtils.html#getCompressedBm(byte[], int, int, int)">getCompressedBm(byte[], int, int, int)</a></span> - Static method in class com.events.utils.<a href="../com/events/utils/ImageUtils.html" title="class in com.events.utils">ImageUtils</a></dt> <dd> <div class="block">Gets the compressed bm.</div> </dd> <dt><span class="strong"><a href="../com/events/utils/ImageUtils.html#getCompressedBm(java.io.File, int, int, int)">getCompressedBm(File, int, int, int)</a></span> - Static method in class com.events.utils.<a href="../com/events/utils/ImageUtils.html" title="class in com.events.utils">ImageUtils</a></dt> <dd> <div class="block">Gets the compressed bm.</div> </dd> <dt><span class="strong"><a href="../com/events/utils/ImageUtils.html#getCompressedBm(android.graphics.Bitmap, int, int, int)">getCompressedBm(Bitmap, int, int, int)</a></span> - Static method in class com.events.utils.<a href="../com/events/utils/ImageUtils.html" title="class in com.events.utils">ImageUtils</a></dt> <dd> <div class="block">Gets the compressed bm.</div> </dd> <dt><span class="strong"><a href="../com/events/calendar/CalendarAdapter.html#getCount()">getCount()</a></span> - Method in class com.events.calendar.<a href="../com/events/calendar/CalendarAdapter.html" title="class in com.events.calendar">CalendarAdapter</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../com/events/calendar/CalendarView.EventAdapter.html#getCount()">getCount()</a></span> - Method in class com.events.calendar.<a href="../com/events/calendar/CalendarView.EventAdapter.html" title="class in com.events.calendar">CalendarView.EventAdapter</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../com/events/ui/FeedList.ProgramAdapter.html#getCount()">getCount()</a></span> - Method in class com.events.ui.<a href="../com/events/ui/FeedList.ProgramAdapter.html" title="class in com.events.ui">FeedList.ProgramAdapter</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../com/events/ui/LeftNavAdapter.html#getCount()">getCount()</a></span> - Method in class com.events.ui.<a href="../com/events/ui/LeftNavAdapter.html" title="class in com.events.ui">LeftNavAdapter</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../com/events/ui/MyTickets.TicketAdapter.html#getCount()">getCount()</a></span> - Method in class com.events.ui.<a href="../com/events/ui/MyTickets.TicketAdapter.html" title="class in com.events.ui">MyTickets.TicketAdapter</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../com/events/ui/Programs.ProgramAdapter.html#getCount()">getCount()</a></span> - Method in class com.events.ui.<a href="../com/events/ui/Programs.ProgramAdapter.html" title="class in com.events.ui">Programs.ProgramAdapter</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../com/events/database/DbConst.html#getCreateString(java.lang.String, com.events.database.DbConst.Fields[])">getCreateString(String, DbConst.Fields[])</a></span> - Static method in class com.events.database.<a href="../com/events/database/DbConst.html" title="class in com.events.database">DbConst</a></dt> <dd> <div class="block">Gets the creates the string.</div> </dd> <dt><span class="strong"><a href="../com/events/model/Status.html#getData()">getData()</a></span> - Method in class com.events.model.<a href="../com/events/model/Status.html" title="class in com.events.model">Status</a></dt> <dd> <div class="block">Gets the data.</div> </dd> <dt><span class="strong"><a href="../com/events/model/Feed.html#getDate()">getDate()</a></span> - Method in class com.events.model.<a href="../com/events/model/Feed.html" title="class in com.events.model">Feed</a></dt> <dd> <div class="block">Gets the date.</div> </dd> <dt><span class="strong"><a href="../com/events/utils/Commons.html#getDateTime()">getDateTime()</a></span> - Static method in class com.events.utils.<a href="../com/events/utils/Commons.html" title="class in com.events.utils">Commons</a></dt> <dd> <div class="block">Gets the date time.</div> </dd> <dt><span class="strong"><a href="../com/events/model/Data.html#getDesc()">getDesc()</a></span> - Method in class com.events.model.<a href="../com/events/model/Data.html" title="class in com.events.model">Data</a></dt> <dd> <div class="block">Gets the desc.</div> </dd> <dt><span class="strong"><a href="../com/events/model/Event.html#getDesc()">getDesc()</a></span> - Method in class com.events.model.<a href="../com/events/model/Event.html" title="class in com.events.model">Event</a></dt> <dd> <div class="block">Gets the desc.</div> </dd> <dt><span class="strong"><a href="../com/events/utils/StaticData.html#getDIP(int)">getDIP(int)</a></span> - Static method in class com.events.utils.<a href="../com/events/utils/StaticData.html" title="class in com.events.utils">StaticData</a></dt> <dd> <div class="block">Gets the dip.</div> </dd> <dt><span class="strong"><a href="../com/events/MainActivity.html#getDummyLeftNavItems()">getDummyLeftNavItems()</a></span> - Method in class com.events.<a href="../com/events/MainActivity.html" title="class in com.events">MainActivity</a></dt> <dd> <div class="block">This method returns a list of dummy items for left navigation slider.</div> </dd> <dt><span class="strong"><a href="../com/events/model/Event.html#getEndDate()">getEndDate()</a></span> - Method in class com.events.model.<a href="../com/events/model/Event.html" title="class in com.events.model">Event</a></dt> <dd> <div class="block">Gets the end date.</div> </dd> <dt><span class="strong"><a href="../com/events/model/Event.html#getEndDateTime()">getEndDateTime()</a></span> - Method in class com.events.model.<a href="../com/events/model/Event.html" title="class in com.events.model">Event</a></dt> <dd> <div class="block">Gets the end date time.</div> </dd> <dt><span class="strong"><a href="../com/events/model/Event.html#getEndTime()">getEndTime()</a></span> - Method in class com.events.model.<a href="../com/events/model/Event.html" title="class in com.events.model">Event</a></dt> <dd> <div class="block">Gets the end time.</div> </dd> <dt><span class="strong"><a href="../com/events/utils/StaticData.html#getErrorMessage()">getErrorMessage()</a></span> - Static method in class com.events.utils.<a href="../com/events/utils/StaticData.html" title="class in com.events.utils">StaticData</a></dt> <dd> <div class="block">Gets the error message.</div> </dd> <dt><span class="strong"><a href="../com/events/web/WebHelper.html#getEvents(int, int)">getEvents(int, int)</a></span> - Static method in class com.events.web.<a href="../com/events/web/WebHelper.html" title="class in com.events.web">WebHelper</a></dt> <dd> <div class="block">Gets the events.</div> </dd> <dt><span class="strong"><a href="../com/events/web/WebHelper.html#getEventsByMonth(java.lang.String, java.lang.String)">getEventsByMonth(String, String)</a></span> - Static method in class com.events.web.<a href="../com/events/web/WebHelper.html" title="class in com.events.web">WebHelper</a></dt> <dd> <div class="block">Gets the events by month.</div> </dd> <dt><span class="strong"><a href="../com/events/database/DbHelper.html#getFavouriteEvents(int)">getFavouriteEvents(int)</a></span> - Static method in class com.events.database.<a href="../com/events/database/DbHelper.html" title="class in com.events.database">DbHelper</a></dt> <dd> <div class="block">Gets the favourite events.</div> </dd> <dt><span class="strong"><a href="../com/events/web/WebHelper.html#getFeedList()">getFeedList()</a></span> - Static method in class com.events.web.<a href="../com/events/web/WebHelper.html" title="class in com.events.web">WebHelper</a></dt> <dd> <div class="block">Gets the feed list.</div> </dd> <dt><span class="strong"><a href="../com/events/web/WebAccess.html#getFile(java.lang.String, java.util.ArrayList)">getFile(String, ArrayList&lt;NameValuePair&gt;)</a></span> - Static method in class com.events.web.<a href="../com/events/web/WebAccess.html" title="class in com.events.web">WebAccess</a></dt> <dd> <div class="block">Gets the file.</div> </dd> <dt><span class="strong"><a href="../com/events/utils/Utils.html#getFormattedCount(int)">getFormattedCount(int)</a></span> - Static method in class com.events.utils.<a href="../com/events/utils/Utils.html" title="class in com.events.utils">Utils</a></dt> <dd> <div class="block">Gets the formatted count.</div> </dd> <dt><span class="strong"><a href="../com/events/utils/ImageUtils.html#getFramedBitmap(android.graphics.Bitmap)">getFramedBitmap(Bitmap)</a></span> - Static method in class com.events.utils.<a href="../com/events/utils/ImageUtils.html" title="class in com.events.utils">ImageUtils</a></dt> <dd> <div class="block">Gets the framed bitmap.</div> </dd> <dt><span class="strong"><a href="../com/events/model/Event.html#getId()">getId()</a></span> - Method in class com.events.model.<a href="../com/events/model/Event.html" title="class in com.events.model">Event</a></dt> <dd> <div class="block">Gets the id.</div> </dd> <dt><span class="strong"><a href="../com/events/model/Event.html#getImage()">getImage()</a></span> - Method in class com.events.model.<a href="../com/events/model/Event.html" title="class in com.events.model">Event</a></dt> <dd> <div class="block">Gets the image.</div> </dd> <dt><span class="strong"><a href="../com/events/model/Feed.html#getImage()">getImage()</a></span> - Method in class com.events.model.<a href="../com/events/model/Feed.html" title="class in com.events.model">Feed</a></dt> <dd> <div class="block">Gets the image.</div> </dd> <dt><span class="strong"><a href="../com/events/model/Data.html#getImage1()">getImage1()</a></span> - Method in class com.events.model.<a href="../com/events/model/Data.html" title="class in com.events.model">Data</a></dt> <dd> <div class="block">Gets the image1.</div> </dd> <dt><span class="strong"><a href="../com/events/model/Data.html#getImage2()">getImage2()</a></span> - Method in class com.events.model.<a href="../com/events/model/Data.html" title="class in com.events.model">Data</a></dt> <dd> <div class="block">Gets the image2.</div> </dd> <dt><span class="strong"><a href="../com/events/utils/ImageLoader.html#getImageFile(java.lang.String)">getImageFile(String)</a></span> - Method in class com.events.utils.<a href="../com/events/utils/ImageLoader.html" title="class in com.events.utils">ImageLoader</a></dt> <dd> <div class="block">Gets the image file.</div> </dd> <dt><span class="strong"><a href="../com/events/calendar/CalendarAdapter.html#getItem(int)">getItem(int)</a></span> - Method in class com.events.calendar.<a href="../com/events/calendar/CalendarAdapter.html" title="class in com.events.calendar">CalendarAdapter</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../com/events/calendar/CalendarView.EventAdapter.html#getItem(int)">getItem(int)</a></span> - Method in class com.events.calendar.<a href="../com/events/calendar/CalendarView.EventAdapter.html" title="class in com.events.calendar">CalendarView.EventAdapter</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../com/events/ui/FeedList.ProgramAdapter.html#getItem(int)">getItem(int)</a></span> - Method in class com.events.ui.<a href="../com/events/ui/FeedList.ProgramAdapter.html" title="class in com.events.ui">FeedList.ProgramAdapter</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../com/events/ui/LeftNavAdapter.html#getItem(int)">getItem(int)</a></span> - Method in class com.events.ui.<a href="../com/events/ui/LeftNavAdapter.html" title="class in com.events.ui">LeftNavAdapter</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../com/events/ui/MyTickets.TicketAdapter.html#getItem(int)">getItem(int)</a></span> - Method in class com.events.ui.<a href="../com/events/ui/MyTickets.TicketAdapter.html" title="class in com.events.ui">MyTickets.TicketAdapter</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../com/events/ui/Programs.ProgramAdapter.html#getItem(int)">getItem(int)</a></span> - Method in class com.events.ui.<a href="../com/events/ui/Programs.ProgramAdapter.html" title="class in com.events.ui">Programs.ProgramAdapter</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../com/events/calendar/CalendarAdapter.html#getItemId(int)">getItemId(int)</a></span> - Method in class com.events.calendar.<a href="../com/events/calendar/CalendarAdapter.html" title="class in com.events.calendar">CalendarAdapter</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../com/events/calendar/CalendarView.EventAdapter.html#getItemId(int)">getItemId(int)</a></span> - Method in class com.events.calendar.<a href="../com/events/calendar/CalendarView.EventAdapter.html" title="class in com.events.calendar">CalendarView.EventAdapter</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../com/events/ui/FeedList.ProgramAdapter.html#getItemId(int)">getItemId(int)</a></span> - Method in class com.events.ui.<a href="../com/events/ui/FeedList.ProgramAdapter.html" title="class in com.events.ui">FeedList.ProgramAdapter</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../com/events/ui/LeftNavAdapter.html#getItemId(int)">getItemId(int)</a></span> - Method in class com.events.ui.<a href="../com/events/ui/LeftNavAdapter.html" title="class in com.events.ui">LeftNavAdapter</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../com/events/ui/MyTickets.TicketAdapter.html#getItemId(int)">getItemId(int)</a></span> - Method in class com.events.ui.<a href="../com/events/ui/MyTickets.TicketAdapter.html" title="class in com.events.ui">MyTickets.TicketAdapter</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../com/events/ui/Programs.ProgramAdapter.html#getItemId(int)">getItemId(int)</a></span> - Method in class com.events.ui.<a href="../com/events/ui/Programs.ProgramAdapter.html" title="class in com.events.ui">Programs.ProgramAdapter</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../com/events/model/Event.html#getLatitude()">getLatitude()</a></span> - Method in class com.events.model.<a href="../com/events/model/Event.html" title="class in com.events.model">Event</a></dt> <dd> <div class="block">Gets the latitude.</div> </dd> <dt><span class="strong"><a href="../com/events/model/Feed.html#getLink()">getLink()</a></span> - Method in class com.events.model.<a href="../com/events/model/Feed.html" title="class in com.events.model">Feed</a></dt> <dd> <div class="block">Gets the link.</div> </dd> <dt><span class="strong"><a href="../com/events/model/Event.html#getLocation()">getLocation()</a></span> - Method in class com.events.model.<a href="../com/events/model/Event.html" title="class in com.events.model">Event</a></dt> <dd> <div class="block">Gets the location.</div> </dd> <dt><span class="strong"><a href="../com/events/model/Event.html#getLongitude()">getLongitude()</a></span> - Method in class com.events.model.<a href="../com/events/model/Event.html" title="class in com.events.model">Event</a></dt> <dd> <div class="block">Gets the longitude.</div> </dd> <dt><span class="strong"><a href="../com/events/utils/ImageUtils.html#getMaskShapedBitmap(android.graphics.Bitmap, int)">getMaskShapedBitmap(Bitmap, int)</a></span> - Static method in class com.events.utils.<a href="../com/events/utils/ImageUtils.html" title="class in com.events.utils">ImageUtils</a></dt> <dd> <div class="block">Gets the mask shaped bitmap.</div> </dd> <dt><span class="strong"><a href="../com/events/calendar/CalendarAdapter.html#getMaxP()">getMaxP()</a></span> - Method in class com.events.calendar.<a href="../com/events/calendar/CalendarAdapter.html" title="class in com.events.calendar">CalendarAdapter</a></dt> <dd> <div class="block">Gets the previous month maximum day.</div> </dd> <dt><span class="strong"><a href="../com/events/utils/Utils.html#getMD5String(java.lang.String)">getMD5String(String)</a></span> - Static method in class com.events.utils.<a href="../com/events/utils/Utils.html" title="class in com.events.utils">Utils</a></dt> <dd> <div class="block">Gets the m d5 string.</div> </dd> <dt><span class="strong"><a href="../com/events/model/Status.html#getMessage()">getMessage()</a></span> - Method in class com.events.model.<a href="../com/events/model/Status.html" title="class in com.events.model">Status</a></dt> <dd> <div class="block">Gets the message.</div> </dd> <dt><span class="strong"><a href="../com/events/model/Feed.html#getMsg()">getMsg()</a></span> - Method in class com.events.model.<a href="../com/events/model/Feed.html" title="class in com.events.model">Feed</a></dt> <dd> <div class="block">Gets the msg.</div> </dd> <dt><span class="strong"><a href="../com/events/utils/ImageUtils.html#getOrientationFixedFramedImage(java.io.File, int, int, int)">getOrientationFixedFramedImage(File, int, int, int)</a></span> - Static method in class com.events.utils.<a href="../com/events/utils/ImageUtils.html" title="class in com.events.utils">ImageUtils</a></dt> <dd> <div class="block">Gets the orientation fixed framed image.</div> </dd> <dt><span class="strong"><a href="../com/events/utils/ImageUtils.html#getOrientationFixedImage(java.io.File, int, int, int)">getOrientationFixedImage(File, int, int, int)</a></span> - Static method in class com.events.utils.<a href="../com/events/utils/ImageUtils.html" title="class in com.events.utils">ImageUtils</a></dt> <dd> <div class="block">Gets the orientation fixed image.</div> </dd> <dt><span class="strong"><a href="../com/events/web/WebAccess.html#getPageParams(java.lang.String, int, int)">getPageParams(String, int, int)</a></span> - Static method in class com.events.web.<a href="../com/events/web/WebAccess.html" title="class in com.events.web">WebAccess</a></dt> <dd> <div class="block">Gets the page params.</div> </dd> <dt><span class="strong"><a href="../com/events/utils/ImageUtils.html#getPlaceHolderImage(int, int, int)">getPlaceHolderImage(int, int, int)</a></span> - Static method in class com.events.utils.<a href="../com/events/utils/ImageUtils.html" title="class in com.events.utils">ImageUtils</a></dt> <dd> <div class="block">Gets the place holder image.</div> </dd> <dt><span class="strong"><a href="../com/events/model/Event.html#getPrice()">getPrice()</a></span> - Method in class com.events.model.<a href="../com/events/model/Event.html" title="class in com.events.model">Event</a></dt> <dd> <div class="block">Gets the price.</div> </dd> <dt><span class="strong"><a href="../com/events/utils/ImageUtils.html#getRoundedCornerBitmap(android.graphics.Bitmap)">getRoundedCornerBitmap(Bitmap)</a></span> - Static method in class com.events.utils.<a href="../com/events/utils/ImageUtils.html" title="class in com.events.utils">ImageUtils</a></dt> <dd> <div class="block">Gets the rounded corner bitmap.</div> </dd> <dt><span class="strong"><a href="../com/events/model/Event.html#getStartDate()">getStartDate()</a></span> - Method in class com.events.model.<a href="../com/events/model/Event.html" title="class in com.events.model">Event</a></dt> <dd> <div class="block">Gets the date.</div> </dd> <dt><span class="strong"><a href="../com/events/model/Event.html#getStartDateTime()">getStartDateTime()</a></span> - Method in class com.events.model.<a href="../com/events/model/Event.html" title="class in com.events.model">Event</a></dt> <dd> <div class="block">Gets the start date time.</div> </dd> <dt><span class="strong"><a href="../com/events/model/Event.html#getStartTime()">getStartTime()</a></span> - Method in class com.events.model.<a href="../com/events/model/Event.html" title="class in com.events.model">Event</a></dt> <dd> <div class="block">Gets the time.</div> </dd> <dt><span class="strong"><a href="../com/events/utils/Utils.html#getStringFromAsset(java.lang.String)">getStringFromAsset(String)</a></span> - Static method in class com.events.utils.<a href="../com/events/utils/Utils.html" title="class in com.events.utils">Utils</a></dt> <dd> <div class="block">Gets the string from asset.</div> </dd> <dt><span class="strong"><a href="../com/events/utils/Commons.html#getTimeSpan(long)">getTimeSpan(long)</a></span> - Static method in class com.events.utils.<a href="../com/events/utils/Commons.html" title="class in com.events.utils">Commons</a></dt> <dd> <div class="block">Gets the time span.</div> </dd> <dt><span class="strong"><a href="../com/events/model/Event.html#getTitle()">getTitle()</a></span> - Method in class com.events.model.<a href="../com/events/model/Event.html" title="class in com.events.model">Event</a></dt> <dd> <div class="block">Gets the title.</div> </dd> <dt><span class="strong"><a href="../com/events/model/Feed.html#getTitle()">getTitle()</a></span> - Method in class com.events.model.<a href="../com/events/model/Feed.html" title="class in com.events.model">Feed</a></dt> <dd> <div class="block">Gets the title.</div> </dd> <dt><span class="strong"><a href="../com/events/model/Data.html#getTitle1()">getTitle1()</a></span> - Method in class com.events.model.<a href="../com/events/model/Data.html" title="class in com.events.model">Data</a></dt> <dd> <div class="block">Gets the title1.</div> </dd> <dt><span class="strong"><a href="../com/events/model/Data.html#getTitle2()">getTitle2()</a></span> - Method in class com.events.model.<a href="../com/events/model/Data.html" title="class in com.events.model">Data</a></dt> <dd> <div class="block">Gets the title2.</div> </dd> <dt><span class="strong"><a href="../com/events/model/Feed.html#getType()">getType()</a></span> - Method in class com.events.model.<a href="../com/events/model/Feed.html" title="class in com.events.model">Feed</a></dt> <dd> <div class="block">Gets the type.</div> </dd> <dt><span class="strong"><a href="../com/events/utils/StaticData.html#getUDID()">getUDID()</a></span> - Static method in class com.events.utils.<a href="../com/events/utils/StaticData.html" title="class in com.events.utils">StaticData</a></dt> <dd> <div class="block">Gets the udid.</div> </dd> <dt><span class="strong"><a href="../com/events/web/WebAccess.html#getUserParams()">getUserParams()</a></span> - Static method in class com.events.web.<a href="../com/events/web/WebAccess.html" title="class in com.events.web">WebAccess</a></dt> <dd> <div class="block">Gets the user params.</div> </dd> <dt><span class="strong"><a href="../com/events/calendar/CalendarAdapter.html#getView(int, android.view.View, android.view.ViewGroup)">getView(int, View, ViewGroup)</a></span> - Method in class com.events.calendar.<a href="../com/events/calendar/CalendarAdapter.html" title="class in com.events.calendar">CalendarAdapter</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../com/events/calendar/CalendarView.EventAdapter.html#getView(int, android.view.View, android.view.ViewGroup)">getView(int, View, ViewGroup)</a></span> - Method in class com.events.calendar.<a href="../com/events/calendar/CalendarView.EventAdapter.html" title="class in com.events.calendar">CalendarView.EventAdapter</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../com/events/ui/FeedList.ProgramAdapter.html#getView(int, android.view.View, android.view.ViewGroup)">getView(int, View, ViewGroup)</a></span> - Method in class com.events.ui.<a href="../com/events/ui/FeedList.ProgramAdapter.html" title="class in com.events.ui">FeedList.ProgramAdapter</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../com/events/ui/LeftNavAdapter.html#getView(int, android.view.View, android.view.ViewGroup)">getView(int, View, ViewGroup)</a></span> - Method in class com.events.ui.<a href="../com/events/ui/LeftNavAdapter.html" title="class in com.events.ui">LeftNavAdapter</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../com/events/ui/MyTickets.TicketAdapter.html#getView(int, android.view.View, android.view.ViewGroup)">getView(int, View, ViewGroup)</a></span> - Method in class com.events.ui.<a href="../com/events/ui/MyTickets.TicketAdapter.html" title="class in com.events.ui">MyTickets.TicketAdapter</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../com/events/ui/Programs.ProgramAdapter.html#getView(int, android.view.View, android.view.ViewGroup)">getView(int, View, ViewGroup)</a></span> - Method in class com.events.ui.<a href="../com/events/ui/Programs.ProgramAdapter.html" title="class in com.events.ui">Programs.ProgramAdapter</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../com/events/R.integer.html#google_play_services_version">google_play_services_version</a></span> - Static variable in class com.events.<a href="../com/events/R.integer.html" title="class in com.events">R.integer</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../com/google/android/gms/R.integer.html#google_play_services_version">google_play_services_version</a></span> - Static variable in class com.google.android.gms.<a href="../com/google/android/gms/R.integer.html" title="class in com.google.android.gms">R.integer</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../com/events/R.color.html#gray_light">gray_light</a></span> - Static variable in class com.events.<a href="../com/events/R.color.html" title="class in com.events">R.color</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../com/events/R.id.html#gridview">gridview</a></span> - Static variable in class com.events.<a href="../com/events/R.id.html" title="class in com.events">R.id</a></dt> <dd>&nbsp;</dd> </dl> <a href="index-1.html">A</a>&nbsp;<a href="index-2.html">B</a>&nbsp;<a href="index-3.html">C</a>&nbsp;<a href="index-4.html">D</a>&nbsp;<a href="index-5.html">E</a>&nbsp;<a href="index-6.html">F</a>&nbsp;<a href="index-7.html">G</a>&nbsp;<a href="index-8.html">H</a>&nbsp;<a href="index-9.html">I</a>&nbsp;<a href="index-10.html">L</a>&nbsp;<a href="index-11.html">M</a>&nbsp;<a href="index-12.html">N</a>&nbsp;<a href="index-13.html">O</a>&nbsp;<a href="index-14.html">P</a>&nbsp;<a href="index-15.html">Q</a>&nbsp;<a href="index-16.html">R</a>&nbsp;<a href="index-17.html">S</a>&nbsp;<a href="index-18.html">T</a>&nbsp;<a href="index-19.html">U</a>&nbsp;<a href="index-20.html">V</a>&nbsp;<a href="index-21.html">W</a>&nbsp;<a href="index-22.html">Z</a>&nbsp;</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li>Use</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-6.html">Prev Letter</a></li> <li><a href="index-8.html">Next Letter</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-filesindex-7.html" target="_top">Frames</a></li> <li><a href="index-7.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html> <file_sep>/README.md # maimasjid for android default from my template app
4f7bdd4ed1ac7ce7440a36f02786c57d56c663f7
[ "Markdown", "Java", "HTML" ]
8
Java
erliyusnaidi/maimasjid
74a28245a7bb4085562c0888a9fb4235f3df4125
6aee7bcbcf8b681ad3b89462eb12d6dca83d221f
refs/heads/master
<repo_name>micahbrich/homebrew-tap<file_sep>/ga-cohort.rb class GaCohort < Formula desc "A tiny little app to get your GA Baseline-copied Trello ready to go" homepage "https://github.com/micahbrich/ga-cohort/" url "https://github.com/micahbrich/ga-cohort/archive/0.0.2.tar.gz" version "0.0.2" sha256 "e55afe2dcb7eb27806c33953fe4f4d677791c09a329638f72155f9309aa2dafd" def install bin.install "cohort" end end <file_sep>/README.md # micah's homebrew taps A tiny collection of personal homebrew taps, for easy installation. ``` $ brew tap micahbrich/tap $ brew install <whatever> ``` Ta-da, super easy. ## taps - [GA Cohort](https://github.com/micahbrich/ga-cohort) - A tiny little app to get your GA Baseline-copied Trello ready to go_ - [git trello](https://github.com/micahbrich/ga-git-trello) - A git tool, pretty specifically for making new baseline materials, that does a bunch of boring setup for you<file_sep>/git-trello.rb class GitTrello < Formula desc "A tiny little git tool to do some standard setup for you when creating a new baseline resource" homepage "https://github.com/micahbrich/git-trello/" url "https://github.com/micahbrich/git-trello/archive/0.2.0.tar.gz" version "0.2.0" sha256 'b49611cee2c4e48f3fefc4820c37fd14174fc347e2832af81e860ec7e886fa3e' def install bin.install "git-trello" end end
1e61882de55aa3fdb45a423c2184f30e666da679
[ "Markdown", "Ruby" ]
3
Ruby
micahbrich/homebrew-tap
20fe93d48720503238f13f32b77305c505e3d2a1
308058ecd574f2ce1088ff641356bf93453491b1
refs/heads/main
<file_sep>#P4 E4 - rgion #Pida al usuario tres números y un cuarto número, y compruebe si éste #último es divisor de los tres números primeros. numero1=float(input("introduza el primer numero")) numero2=float(input("introduzca el segundo numero")) numero3=float(input("introduzca el tercer numero")) numero4=float(input("introduzca un numero para comprobar si es divisor de los tres primeros")) if(numero1%numero4==0): print(numero4,"es divisor de",numero1) if(numero2%numero4==0): print(numero4,"es divisor de",numero2) if(numero3%numero4==0): print(numero4,"es divisor de",numero3) <file_sep>#P4 E2 - rgion #Pida al usuario 5 números y diga si estos estaban en orden decreciente, #creciente o desordenados. numero1=float(input("Introduzca el primer número ")) numero2=float(input("Introduzca el segundo número ")) numero3=float(input("Introduzca el tercero número ")) numero4=float(input("Introduzca el cuarto número ")) numero5=float(input("Introduzca el quinto número ")) if (numero1<numero2)and(numero2<numero3)and(numero3<numero4)and(numero4<numero5): print("los numeros",numero1,numero2,numero3,numero4,numero5,"estan en orden ascendente") elif (numero1>numero2)and(numero2>numero3)and(numero3>numero4)and(numero4>numero5): print ("los numeros",numero1,numero2,numero3,numero4,numero5,"estan en orden descendiente") else: print ("los numeros estan desordenados")<file_sep>#P4 E3 - rgion #Pida al usuario si quiere calcular el área de un triángulo o un cuadrado, #y pida los datos según que caso y muestre el resultado area=input("quiere calcular el área de un cuadrado o de un triangulo?") if(area=="triangulo"): base=float(input("introduzca la bse del triangulo")) altura=float(input("introduzca la altura del triangulo")) area=(base*altura)/2 print("El area del triangulo es de",area) if(area=="cuadrado"): lado=float(input("introduce la longitud del lado del cuadrado")) area=lado**2 print("el area del cuadrado es de",area) else: print("introduca una geometria válida")<file_sep>numero1=float(input("Introduzca el primer número ")) numero2=float(input("Introduzca el segundo número ")) numero3=float(input("Introduzca el tercero número ")) numero4=float(input("Introduzca el cuarto número ")) numero5=float(input("Introduzca el quinto número ")) if(numero1==numero2==numero3==numero4==numero5): print("Todos los numeros son iguales") else: if(numero1>numero2): mayor=numero1 menor=numero2 else: mayor=numero2 menor=numero1 if(numero3>mayor): mayor=numero3 if(numero3<menor): menor=numero3 if(numero4>mayor): mayor=numero4 if(numero4<menor): menor=numero4 if(numero5>mayor): mayor=numero5 if(numero5<menor): menor=numero5 print(mayor, "es el mayor y" ,menor, "es el menor")
551ff2928bbb1969274a0cb7cccb1519ef89608e
[ "Python" ]
4
Python
cifpfbmoll/practica-4-python-jmjimenezn
53a98d9545f7c83395ee843ae5083ffb1fcd603a
dcadbd0ac6a7a9a0ffa7b519df4020a9baf775d9
refs/heads/main
<file_sep>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-titles-showcase', templateUrl: './titles-showcase.component.html', styleUrls: ['./titles-showcase.component.scss'], }) export class TitlesShowcaseComponent implements OnInit { constructor() {} ngOnInit() {} } <file_sep>import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { MaskedInputComponent } from './masked-input.component'; import { ElementRef } from '@angular/core'; import { MaskedTextBoxComponent } from '@progress/kendo-angular-inputs'; export class MockElementRef extends ElementRef<MaskedTextBoxComponent> {} describe('MaskedInputComponent', () => { let component: MaskedInputComponent; let fixture: ComponentFixture<MaskedInputComponent>; let inputElement: HTMLInputElement; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ declarations: [MaskedInputComponent], providers: [ { provide: ElementRef, useClass: MockElementRef, }, ], }).compileComponents(); }) ); beforeEach(() => { fixture = TestBed.createComponent(MaskedInputComponent); component = fixture.componentInstance; inputElement = fixture.debugElement.nativeElement.shadowRoot.querySelector('.masked-input__field'); fixture.detectChanges(); }); }); <file_sep>import { Component, OnInit } from '@angular/core'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; @Component({ selector: 'app-autocomplete-dropdown-showcase', templateUrl: 'autocomplete-dropdown-showcase.component.html', styleUrls: ['./autocomplete-dropdown-showcase.component.scss'], }) export class AutocompleteDropdownShowcaseComponent implements OnInit { dropdownForm: FormGroup; dropdownPlaceholder = 'Enter Country Name'; dropdownLabel = 'Country of Nationality'; dropDownData = [ { text: 'Singapore', key: '1' }, { text: 'Malaysia', key: '2' }, { text: 'Hongkong', key: '3' }, { text: 'China', key: '4' }, { text: 'India', key: '5' }, { text: 'Sri Lanka', key: '6' }, { text: 'Thailand', key: '7' }, { text: 'India South', key: '8' }, { text: 'India North', key: '9' }, ]; disabled = false; constructor(private formBuilder: FormBuilder) {} ngOnInit() { this.dropdownForm = this.formBuilder.group({ transaction: [this.dropDownData[1].key, Validators.required], }); } get transaction() { return this.dropdownForm.controls.transaction; } patchValue() { this.dropdownForm.patchValue({ transaction: this.dropDownData[2].key, }); } onDropdownSelect(event: any) { console.log(event); } toggle() { if (this.dropdownForm.controls.transaction.dirty) { this.dropdownForm.controls.transaction.reset(); } else { this.dropdownForm.controls.transaction.markAsDirty(); } } disable() { this.disabled = !this.disabled; } reset() { this.dropdownForm.patchValue({ transaction: null, }); } resetForm() { this.dropdownForm.patchValue({ transaction: null, }); this.dropdownForm.reset(); } changeList() { this.dropDownData = [ { text: 'Data1', key: '1', }, { text: 'Data2', key: '2', }, ]; this.dropdownForm.controls.transaction.reset(); } } <file_sep>export type TAssetRootPathNameTypes = 'icons' | 'images' | 'css'; export const loadAsset = ({ type, assetName }: { type: TAssetRootPathNameTypes; assetName: string }) => { const origin = location.origin; return ( (origin.startsWith('https://localhost') || origin.startsWith('http://localhost') ? 'https://irin3.dev.irasgcc.gov.sg' : origin) + `/estamping/assets/${type}/${assetName}` ); }; <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { StepperViewComponent } from './stepper-view.component'; import { DialogStepperModule } from '../dialog-stepper/dialog-stepper.module'; @NgModule({ declarations: [StepperViewComponent], imports: [CommonModule, DialogStepperModule], exports: [StepperViewComponent, DialogStepperModule], }) export class IrasStepperViewModule {} <file_sep>import { Component, OnDestroy } from '@angular/core'; import { MediaObserver } from '@angular/flex-layout'; import { Router } from '@angular/router'; import { Subscription } from 'rxjs'; import { map } from 'rxjs/operators'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'], }) export class AppComponent implements OnDestroy { title = 'common-ui-lib-showcase'; routes = [ { path: 'menu', text: 'split-view', }, ]; mediaSubscription: Subscription; constructor(private router: Router, private mediaObserver: MediaObserver) { this.mediaSubscription = this.mediaObserver .asObservable() .pipe(map((mc) => mc.find((c) => c.mqAlias.length === 2).mqAlias)) .subscribe((alias) => { console.log({ breakpoint: alias }); }); } ngOnDestroy(): void { this.mediaSubscription.unsubscribe(); } } <file_sep>import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { HttpClientTestingModule } from '@angular/common/http/testing'; import { PaginationComponent } from './pagination.component'; describe('PaginationComponent', () => { let component: PaginationComponent; let fixture: ComponentFixture<PaginationComponent>; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ declarations: [PaginationComponent], imports: [HttpClientTestingModule], }).compileComponents(); }) ); beforeEach(() => { fixture = TestBed.createComponent(PaginationComponent); component = fixture.componentInstance; component.activePageIndex = 2; component.numPages = 2; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('#changePage should emit the stateChanged with actie page index', () => { const spy = spyOn(component.stateChanged, 'emit').and.callThrough(); const option = 2; component.changePage(option); expect(spy).toHaveBeenCalledWith(option); }); it('#changePageByAddOne should change the page by adding page index one', () => { const spy = spyOn(component.stateChanged, 'emit').and.callThrough(); const currentPage = 1; component.changePageByAddOne(currentPage); expect(spy).toHaveBeenCalledWith(2); }); it('#changePageByAddOne should return if active page and pageIndex are equal', () => { const spy = spyOn(component.stateChanged, 'emit').and.callThrough(); const currentPage = 2; component.activePage = 2; component.numPages = 2; fixture.detectChanges(); component.changePageByAddOne(currentPage); expect(spy).not.toHaveBeenCalledWith(2); }); it('#changePageByMinusOne should change the page by reducing page index one', () => { const spy = spyOn(component.stateChanged, 'emit').and.callThrough(); const currentPage = 2; component.activePage = 2; fixture.detectChanges(); component.changePageByMinusOne(currentPage); expect(spy).toHaveBeenCalledWith(1); }); it('#changePageByMinusOne should return if active page is equal 1', () => { const spy = spyOn(component.stateChanged, 'emit').and.callThrough(); const currentPage = 1; component.activePage = 1; fixture.detectChanges(); component.changePageByMinusOne(currentPage); expect(spy).not.toHaveBeenCalledWith(1); }); it('#jumpToFirstPage should reset the pages array slice', () => { const spy = spyOn(component.stateChanged, 'emit').and.callThrough(); component.paginationSizeMax = 10; fixture.detectChanges(); component.jumpToFirstPage(); expect(spy).toHaveBeenCalledWith(1); }); it('#jumpToLastPage should change the last page index', () => { const spy = spyOn(component.stateChanged, 'emit').and.callThrough(); component.numPages = 10; component.paginationSizeMax = 10; fixture.detectChanges(); component.jumpToLastPage(); expect(spy).toHaveBeenCalledWith(10); }); it('#pageLengthAddOne should return if paginationMinDisplay is equal current page index', () => { const spy = spyOn(component, 'pageLengthAddOne').and.callThrough(); component.paginationMinDisplay = 32; component.numPages = 33; component.paginationSizeMax = 1; fixture.detectChanges(); component.pageLengthAddOne(); expect(spy).toHaveBeenCalled(); }); it('#pageLengthMinusOne should change the paginationMinDisplay and paginationNumMaxDisplay ', () => { component.numPages = 3; component.paginationSizeMax = 3; component.paginationMinDisplay = 3; component.paginationNumMaxDisplay = 3; fixture.detectChanges(); component.pageLengthMinusOne(); expect(component.paginationMinDisplay).toEqual(2); expect(component.paginationNumMaxDisplay).toEqual(2); }); }); <file_sep>// <NAME> - Temp Solution export enum FileUploadErrorStatus { UnsupportedFileType = 0, FileInvalidFileName = 1, FileExceed50Characters = 2, FileExceed10MB = 3, FileExceed50MB = 4, NoError = 5, } <file_sep>import { Component, ViewEncapsulation, Input, TemplateRef, ViewContainerRef, ChangeDetectorRef, AfterViewInit, } from '@angular/core'; import { TemplatePortal } from '@angular/cdk/portal'; @Component({ selector: 'iras-link', templateUrl: './link.component.html', styleUrls: ['./link.component.scss'], encapsulation: ViewEncapsulation.ShadowDom, }) export class LinkComponent implements AfterViewInit { @Input() templateContentRef: TemplateRef<any>; @Input() cssClass: string[]; @Input() color: string; @Input() includeChar: string; templatePortal: TemplatePortal<any>; constructor(private _viewContainerRef: ViewContainerRef, private cdr: ChangeDetectorRef) {} ngAfterViewInit() { if (this.templateContentRef) { this.templatePortal = new TemplatePortal(this.templateContentRef, this._viewContainerRef); } this.cdr.detectChanges(); } } <file_sep>import { Component, OnInit, ViewChild, TemplateRef } from '@angular/core'; import { ModalService } from '../../../../../common-ui-lib/src/lib/modal/modal.service'; @Component({ selector: 'app-stepper-view-showcase.component', templateUrl: './stepper-view-showcase.component.html', styleUrls: ['./stepper-view-showcase.component.scss'], }) export class StepperViewShowcaseComponent implements OnInit { @ViewChild('modalContentRef', { static: false }) modalContentRef: TemplateRef<any>; // Stepper View headingTitles: Array<string> = [ '1 Getting Started', '2 Property/ Land', '3 ABSD Rate (if applicable)', '4 Remission (if applicable)', '5 Summary', '6 Payment (if applicable)', '7 Acknowledgement', ]; public dialog2Opened = false; currentIndex = 0; constructor(private modalService: ModalService) {} ngOnInit(): void {} onStepBack() { if (this.currentIndex === 0) { return; } this.currentIndex = this.currentIndex - 1; } onStepNext() { if (this.currentIndex >= this.headingTitles.length || this.currentIndex === this.headingTitles.length - 1) { return; } this.currentIndex = this.currentIndex + 1; } onDialogContinue(event: any) { console.log('[onDialogContinue] ', event); } showModal() { this.modalService.show({ data: { templateContentRef: this.modalContentRef, }, panelClass: 'modal-showcase', backdropClass: 'modal-showcase-backdrop', }); } hideModal() { this.modalService.hide(); } } <file_sep>import { Component, OnInit, Input, ViewEncapsulation } from '@angular/core'; @Component({ selector: 'iras-maintenance-layout', templateUrl: './maintenance-layout.component.html', styleUrls: ['./maintenance-layout.component.scss'], encapsulation: ViewEncapsulation.ShadowDom, }) export class MaintenanceLayoutComponent implements OnInit { @Input() header: string; @Input() description: string; @Input() cssClass: string; constructor() {} ngOnInit(): void {} getContainerClassList() { return `${this.cssClass || ''}`; } } <file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { HighlightPanelShowcaseComponent } from './highlight-panel-showcase.component'; describe('HighlightPanelShowcaseComponent', () => { let component: HighlightPanelShowcaseComponent; let fixture: ComponentFixture<HighlightPanelShowcaseComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [HighlightPanelShowcaseComponent], }).compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(HighlightPanelShowcaseComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>export * from './color.type'; export * from './month.enum'; <file_sep>import { AutocompleteDropdownShowcaseComponent } from '../components/autocomplete-dropdown-showcase/autocomplete-dropdown-showcase.component'; import { ButtonMenuShowcaseComponent } from '../components/button-menu-showcase/button-menu-showcase.component'; import { ButtonShowcaseComponent } from '../components/button-showcase/button-showcase.component'; import { CardShowcaseComponent } from '../components/card-showcase/card-showcase.component'; import { CheckboxInputShowcaseComponent } from '../components/checkbox-input-showcase/checkbox-input-showcase.component'; import { DatePickersShowcaseComponent } from '../components/datepickers-showcase/datepickers-showcase.component'; import { DialogPopupShowcaseComponent } from '../components/dialog-popup-showcase/dialog-popup-showcase.component'; import { DropdownShowcaseComponent } from '../components/dropdown-showcase/dropdown-showcase.component'; import { FileUploadShowcaseComponent } from '../components/file-upload-showcase/file-upload-showcase/file-upload-showcase.component'; import { IconsShowcaseComponent } from '../components/icons-showcase/icons-showcase.component'; import { InputShowcaseComponent } from '../components/input-showcase/input-showcase.component'; import { IrasDateTimePickerShowcaseComponent } from '../components/date-time-picker-showcase/iras-date-time-picker-showcase.component'; import { MaskedInputShowcaseComponent } from '../components/masked-input-showcase/masked-input-showcase.component'; import { ModalShowcaseComponent } from '../components/modal-showcase/modal-showcase.component'; import { PaginationShowcaseComponent } from '../components/pagination-showcase/pagination-showcase.component'; import { PdfExportShowcaseComponent } from '../components/pdf-export-showcase/pdf-export-showcase.component'; import { PostSubmitErrorShowcaseComponent } from '../components/post-submit-error-showcase/post-submit-error-showcase.component'; import { RadioInputShowcaseComponent } from '../components/radio-input-showcase/radio-input-showcase.component'; import { SnackBarComponentShowcaseComponent } from '../components/snack-bar-showcase/snack-bar-showcase.component'; import { MultiSnackBarComponentShowcaseComponent } from '../components/multi-snack-bar-showcase/multi-snack-bar-showcase.component'; import { SpinnerShowcaseComponent } from '../components/spinner-showcase/spinner-showcase.component'; import { StepperViewShowcaseComponent } from '../components/stepper-view-showcase/stepper-view-showcase.component'; import { TabsShowcaseComponent } from '../components/tabs-showcase/tabs-showcase.component'; import { TitlesShowcaseComponent } from '../components/titles-showcase/titles-showcase.component'; import { TooltipShowcaseComponent } from '../components/tooltip-showcase/tooltip-showcase.component'; import { TypographyShowcaseComponent } from '../components/typography-showcase/typography-showcase.component'; import { MultiSelectDropdownShowcaseComponent } from '../components/multi-select-dropdown-showcase/multi-select-dropdown-showcase.component'; import { MultiSelectNestedDropdownShowcaseComponent } from '../components/multi-select-nested-dropdown-showcase/multi-select-nested-dropdown-showcase.component'; import { MaintenanceLayoutShowcaseComponent } from '../components/maintenance-layout-showcase/maintenance-layout-showcase.component'; import { EmptyStateBoxShowcaseComponent } from '../components/empty-state-box-showcase/empty-state-box-showcase.component'; import { NumericStepperShowcaseComponent } from '../components/numeric-stepper-showcase/numeric-stepper-showcase.component'; import { ErrorShowcaseComponent } from '../components/error-showcase/error-showcase.component'; import { HighlightPanelShowcaseComponent } from '../components/highlight-panel-showcase/highlight-panel-showcase.component'; export const sortedRoutes = [ { path: 'autocomplete-dropdown', component: AutocompleteDropdownShowcaseComponent }, { path: 'button', component: ButtonShowcaseComponent }, { path: 'button-menu', component: ButtonMenuShowcaseComponent }, { path: 'card', component: CardShowcaseComponent }, { path: 'checkbox', component: CheckboxInputShowcaseComponent }, { path: 'datepickers', component: DatePickersShowcaseComponent }, { path: 'dialog-popups', component: DialogPopupShowcaseComponent }, { path: 'dropdown', component: DropdownShowcaseComponent }, { path: 'empty-state-box', component: EmptyStateBoxShowcaseComponent }, { path: 'multi-select-dropdown', component: MultiSelectDropdownShowcaseComponent }, { path: 'multi-select-nested-dropdown', component: MultiSelectNestedDropdownShowcaseComponent }, { path: 'maintenance-layout', component: MaintenanceLayoutShowcaseComponent }, { path: 'file-upload', component: FileUploadShowcaseComponent }, { path: 'icons', component: IconsShowcaseComponent }, { path: 'input', component: InputShowcaseComponent }, { path: 'masked-input', component: MaskedInputShowcaseComponent }, { path: 'modal', component: ModalShowcaseComponent }, { path: 'pagination', component: PaginationShowcaseComponent }, { path: 'pdf-export', component: PdfExportShowcaseComponent }, { path: 'post-submit-error', component: PostSubmitErrorShowcaseComponent }, { path: 'radio', component: RadioInputShowcaseComponent }, { path: 'snack-bar', component: SnackBarComponentShowcaseComponent }, { path: 'multi-snack-bar', component: MultiSnackBarComponentShowcaseComponent }, { path: 'spinner', component: SpinnerShowcaseComponent }, { path: 'stepper', component: StepperViewShowcaseComponent }, { path: 'tabs', component: TabsShowcaseComponent }, { path: 'titles', component: TitlesShowcaseComponent }, { path: 'popover', component: TooltipShowcaseComponent }, { path: 'typography', component: TypographyShowcaseComponent }, { path: 'error', component: ErrorShowcaseComponent }, { path: 'highlight-panel', component: HighlightPanelShowcaseComponent }, { path: 'datetime-picker', component: IrasDateTimePickerShowcaseComponent }, { path: 'numeric-stepper', component: NumericStepperShowcaseComponent }, ].sort((a, b) => (a.path > b.path ? 1 : -1)); sortedRoutes.push({ path: '**', component: InputShowcaseComponent }); export const MENU_ROUTES_CHILDREN = sortedRoutes; <file_sep>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-pagination-showcase', templateUrl: './pagination-showcase.component.html', }) export class PaginationShowcaseComponent implements OnInit { constructor() {} ngOnInit() {} updateActivePage(activePageIdx: number) { console.log('[Pagination] Current Page: ', activePageIdx); } } <file_sep>import { Component, OnInit, ChangeDetectionStrategy, ViewChild, ElementRef, Input, Output, EventEmitter, } from '@angular/core'; import { FileUploadErrorStatus } from './models/file-upload-error-status.model'; import { SupportingDocumentError, Document, SupportingDocument } from './models/attachment.model'; @Component({ selector: 'iras-file-upload', templateUrl: './file-upload.component.html', styleUrls: ['./file-upload.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class IrasFileUploadComponent implements OnInit { // max no. of files @Input() maxNoFiles = 25; @Output() fileUploaded = new EventEmitter(); // Array to store the raw 'File' from upload files: any[] = []; document = new Document(); listOfUploadedFileThatHasErrors: Array<SupportingDocumentError>; listOfSupportingFileThatHasErrors: Array<SupportingDocumentError>; // For duplicate file handling isDuplicateFilePopupShown: boolean; filesContainingDuplicate: any[] = []; showErrorDialogTitleIcon: boolean; // validations validFileFormats = ['pdf', 'jpg', 'png', 'xlsx']; // Reference from: SIT\IRAS.ISDSSolution\IRAS.ISDS.UI\UserControls\UserControl\ucFileUploadDragAndDrop_RWD.ascx // Line: 121 englishPattern = /^[a-zA-Z0-9._-\s]+$/; maxNoChar = 50; maxFileSize = 10; maxTotalFileSize = 50; // For error handling of File upload isFileUploadErrorMessageShown: boolean; fileUploadErrorMessage: string; totalFilesSize: number; fileFormatErrorMessageArray = [ 'Unsupported file type', 'Filename contains invalid character(s)', `File name exceed ${this.maxNoChar} characters`, `File size exceeded ${this.maxFileSize}.00 MB`, `Total file size exceeded ${this.maxTotalFileSize}.00 MB`, ]; @ViewChild('fileDropRef', { static: false }) fileDropEl: ElementRef; constructor() {} ngOnInit(): void { this.isFileUploadErrorMessageShown = true; this.isDuplicateFilePopupShown = false; this.fileUploadErrorMessage = ''; this.totalFilesSize = 0; this.showErrorDialogTitleIcon = false; this.listOfSupportingFileThatHasErrors = []; this.document.supportingDocuments = []; } // On file drop handler onFileDropped($event: any) { if (this.filesContainingDuplicate && this.filesContainingDuplicate.length <= 0) { this.prepareFilesList($event); } } // Handle file from browsing fileBrowseHandler(files: any) { this.prepareFilesList(files); } // Delete file from files list // @param index (File index) deleteFile(index: number, fileSize: number) { // Update the "totalFilesSize", since a file is removed this.totalFilesSize -= fileSize; this.files.splice(index, 1); this.updateStore('delete', '', index); } deleteFileForErrorRow(index: number) { this.listOfSupportingFileThatHasErrors.splice(index, 1); } onDuplicateFileOkClick(params: any) { // Upload and replace, Apply for all conflicts if (params.toBeUpload && params.index === -1) { this.onDuplicateFilesOkClick(); } // Skip this file, Apply for all conflicts if (!params.toBeUpload && params.index === -1) { // Close the Popup window this.onDuplicateFilesCancelClick(); } // Upload and replace, Not apply for all conflicts(only selected) if (params.toBeUpload && params.index > -1) { // Replace the old uploaded file from new file this.replaceUploadSelectedFile(params.index); // Close the Popup window if no conflicts/duplicated if (this.filesContainingDuplicate.length === params.index + 1) { this.isDuplicateFilePopupShown = false; // Clear the array holding the duplicate files this.filesContainingDuplicate = []; } } // Skip this file, Not apply for all conflicts(only selected) if (!params.toBeUpload && params.index > -1) { // Close the Popup window if no conflicts/duplicated if (this.filesContainingDuplicate.length === params.index + 1) { this.isDuplicateFilePopupShown = false; // Clear the array holding the duplicate files this.filesContainingDuplicate = []; } } } onDuplicateFilesCancelClick() { // Close the Popup window this.isDuplicateFilePopupShown = false; // Clear the array holding the duplicate files this.filesContainingDuplicate = []; } onDuplicateFilesOkClick() { for (const item of this.filesContainingDuplicate) { // For checking if there is files already updated. For duplicate file handling let isFileAlreadyUploaded = -1; let sizeOfTheFileToBeDeleted = 0; // Return "-1" if file name is not a exact match isFileAlreadyUploaded = this.files.findIndex((file) => file.name.toLowerCase() === item.name.toLowerCase()); // Delete the previous file to avoid duplicate if (isFileAlreadyUploaded !== -1) { // Get the size of the file to be removed sizeOfTheFileToBeDeleted = this.files[isFileAlreadyUploaded].size; this.deleteFile(isFileAlreadyUploaded, sizeOfTheFileToBeDeleted); } this.files.push(item); this.updateStore('create', item, 0); } // Close the Popup window this.onDuplicateFilesCancelClick(); } replaceUploadSelectedFile(index: number) { var toBeReplaced = this.filesContainingDuplicate[index]; // For checking if there is files already updated. For duplicate file handling let isFileAlreadyUploaded = -1; let sizeOfTheFileToBeDeleted = 0; // Return "-1" if file name is not a exact match isFileAlreadyUploaded = this.files.findIndex((file) => file.name.toLowerCase() === toBeReplaced.name.toLowerCase()); // Delete the previous file to avoid duplicate if (isFileAlreadyUploaded !== -1) { // Get the size of the file to be removed sizeOfTheFileToBeDeleted = this.files[isFileAlreadyUploaded].size; this.deleteFile(isFileAlreadyUploaded, sizeOfTheFileToBeDeleted); } this.files.push(toBeReplaced); this.updateStore('create', toBeReplaced, 0); } checkIsFileValidForUpload(file: any) { // e.g. sample_file.pdf const fileName: string = file.name; const indexOfLastDot = fileName.lastIndexOf('.'); // Check to see if the file has an extension if (indexOfLastDot === -1) { return FileUploadErrorStatus.UnsupportedFileType; } // e.g. it will return "sample_file" const fileNameWithoutExtension = fileName.substring(0, indexOfLastDot); // Check File name cannot exceed 50 characters long if (fileNameWithoutExtension.length > this.maxNoChar) { return FileUploadErrorStatus.FileExceed50Characters; } // Check File name = English if (!this.englishPattern.test(fileNameWithoutExtension)) { return FileUploadErrorStatus.FileInvalidFileName; } // e.g. it will return "pdf" const fileExtension = fileName.substring(indexOfLastDot + 1).toLowerCase(); // Check for correct file format: PDF, JPG, PNG if (!this.validFileFormats.includes(fileExtension)) { return FileUploadErrorStatus.UnsupportedFileType; } // Maximum size allowed for one file should not exceed 10 MB (10,000,000). if (file.size > this.maxFileSize * 1024 * 1000) { return FileUploadErrorStatus.FileExceed10MB; } // Total file size uploaded should not exceed 50 MB (50,000,000). if (this.totalFilesSize + file.size > this.maxTotalFileSize * 1024 * 1000) { return FileUploadErrorStatus.FileExceed50MB; } // Set File Upload error back to default this.isFileUploadErrorMessageShown = false; this.fileUploadErrorMessage = ''; return FileUploadErrorStatus.NoError; } // format bytes // @param bytes (File size in bytes) // @param decimals (Decimals point) formatBytes(bytes: any, decimals: any = 2) { if (bytes === 0) { return '0 Bytes'; } const k = 1024; const dm = decimals <= 0 ? 0 : decimals; const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]; } onUploadedFilePreviewClick(indexOfFileToShow: number) { // YY > TO DO > Need to find a more "elegant" solution const fileReader = new FileReader(); fileReader.readAsDataURL(this.files[indexOfFileToShow]); fileReader.onload = (event) => { const pdfWindow = window.open(''); pdfWindow.document.write('<iframe src="' + event.target.result + '" width="100%" height="100%"></iframe>'); }; } // Convert Files list to normal array list // @param files (Files List) private prepareFilesList(files: Array<any>) { // > YY > TO DO: // There is a bug where drag & drop a group of files and the files are sorted in a weird order // Clear the temporary file error list this.listOfUploadedFileThatHasErrors = []; for (const item of files) { // Check the validity of the file that was being uploaded const isThereFileUploadError = this.checkIsFileValidForUpload(item); if (isThereFileUploadError === FileUploadErrorStatus.FileExceed50MB) { this.isFileUploadErrorMessageShown = true; this.fileUploadErrorMessage = `Total file size exceeded ${this.maxTotalFileSize}.00 MB`; } else { // For Files that cleared the validation rule for file upload if (isThereFileUploadError === FileUploadErrorStatus.NoError) { // Clear the inline error (50 MB), when user managed to add in a new file this.isFileUploadErrorMessageShown = false; this.fileUploadErrorMessage = ''; // For checking if there is files already updated. For duplicate file handling let isFileAlreadyUploaded = -1; // Return "-1" if file name is not a exact match isFileAlreadyUploaded = this.files.findIndex((file) => file.name.toLowerCase() === item.name.toLowerCase()); // Delete the previous file to avoid duplicate if (isFileAlreadyUploaded !== -1) { this.filesContainingDuplicate.push(item); } else { if (this.files.length !== this.maxNoFiles) { this.files.push(item); this.updateStore('create', item, 0); } } } else { const errorFile: SupportingDocumentError = { fileName: item.name.length > this.maxNoChar + 1 ? item.name.substring(0, this.maxNoChar) + '...' : item.name, fileFormatErrorMsg: this.fileFormatErrorMessageArray[isThereFileUploadError], }; this.listOfUploadedFileThatHasErrors.push(errorFile); } } } if (this.listOfUploadedFileThatHasErrors.length > 0) { this.listOfSupportingFileThatHasErrors = Object.assign([], this.listOfUploadedFileThatHasErrors); } // Throw Duplicate Popup if there are duplicate records in the array if (this.filesContainingDuplicate.length > 0) { this.isDuplicateFilePopupShown = true; } this.fileDropEl.nativeElement.value = ''; } private updateStore(action: string, file: any, index: number) { const tempSupportingDocuments = JSON.parse(JSON.stringify(this.document.supportingDocuments)); switch (action) { case 'create': const newFile: SupportingDocument = { fileName: file.name, fileSizeText: this.formatBytes(file.size), fileSizeActual: file.size, }; this.totalFilesSize += file.size; tempSupportingDocuments.push(newFile); break; case 'delete': tempSupportingDocuments.splice(index, 1); break; default: break; } this.document.supportingDocuments = tempSupportingDocuments; this.fileUploaded.emit(this.files); } } <file_sep>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-icons-showcase', templateUrl: './icons-showcase.component.html', styleUrls: ['./icons-showcase.component.scss'], }) export class IconsShowcaseComponent implements OnInit { icons = [ 'add-account.svg', 'add-capsule-blue.svg', 'add-capsule-grey.svg', 'add-white.svg', 'amend.svg', 'calendar.svg', 'caret.svg', 'check.svg', 'clip.svg', 'close-20px.svg', 'close-blue.svg', 'close-grey.svg', 'close-white.svg', 'close_blue_active.svg', 'close_grey_active.svg', 'close_white_active.svg', 'download.svg', 'download-empty.svg', 'download-retry.svg', 'download-success.svg', 'edit.svg', 'error.svg', 'expand.svg', 'expand-selected.svg', 'help.svg', 'invalid.png', 'inbox_iras.svg', 'inbox_user.svg', 'info.svg', 'minimise.svg', 'minus.svg', 'notification-masthead.svg', 'login.svg', 'pay-taxes.svg', 'password.svg', 'png-attention.svg', 'ribbon.svg', 'save-pdf.svg', 'save-draft2.svg', 'search.svg', 'sortdown.svg', 'sortup.svg', 'sortupdown.svg', 'sort-up-down-blue.svg', 'stepper-add.svg', 'stepper-minus.svg', 'svg-undo.svg', 'success.svg', 'trash-bin-grey.svg', 'trash-bin.svg', 'leasetenancy.svg', 'payment-plan.svg', 'switch.svg', 'location.svg', 'print.svg', 'tax-bill.svg', 'copy.svg', 'location-grey.svg', 'qr-code.svg', 'unp.svg', 'export.svg', 'markallasread-active.svg', 'refund.svg', 'update-contact.svg', 'giro.svg', 'markallasread-grey.svg', 'request-extension.svg', 'view.svg', 'giro-black.svg', 'mortgage.svg', 'saleandpurchase.svg', 'view-acc-summary.svg', 'giro-grey.svg', 'mtm.svg', 'savedraft.svg', 'view-notices.svg', 'hyperlink.svg', 'pay.svg', 'sharetransfer.svg', 'warning.svg', ]; constructor() {} ngOnInit() {} } <file_sep>import { FormGroup } from '@angular/forms'; export const printFormValueAndValidity = (form: FormGroup) => { const controls = Object.keys(form.controls).map((k) => { return { controlName: k, value: form.controls[k].value, valid: form.controls[k].valid, pristine: form.controls[k].valid, touched: form.controls[k].touched, dirty: form.controls[k].dirty, }; }); console.log(controls); }; <file_sep>import { CommonModule } from '@angular/common'; import { HttpClientModule } from '@angular/common/http'; import { CUSTOM_ELEMENTS_SCHEMA, NgModule } from '@angular/core'; import { FlexLayoutModule } from '@angular/flex-layout'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { LayoutModule } from '@progress/kendo-angular-layout'; import { PDFExportModule } from '@progress/kendo-angular-pdf-export'; import { CommonUiLibraryModule } from '../../../../common-ui-lib/src/lib/common-ui-library.module'; import { AutocompleteDropdownShowcaseComponent } from '../components/autocomplete-dropdown-showcase/autocomplete-dropdown-showcase.component'; import { ButtonMenuShowcaseComponent } from '../components/button-menu-showcase/button-menu-showcase.component'; import { ButtonShowcaseComponent } from '../components/button-showcase/button-showcase.component'; import { CardShowcaseComponent } from '../components/card-showcase/card-showcase.component'; import { CheckboxInputShowcaseComponent } from '../components/checkbox-input-showcase/checkbox-input-showcase.component'; import { DatePickersShowcaseComponent } from '../components/datepickers-showcase/datepickers-showcase.component'; import { DialogPopupShowcaseComponent } from '../components/dialog-popup-showcase/dialog-popup-showcase.component'; import { DropdownShowcaseComponent } from '../components/dropdown-showcase/dropdown-showcase.component'; import { FileUploadShowcaseComponent } from '../components/file-upload-showcase/file-upload-showcase/file-upload-showcase.component'; import { IconsShowcaseComponent } from '../components/icons-showcase/icons-showcase.component'; import { InputShowcaseComponent } from '../components/input-showcase/input-showcase.component'; import { MaskedInputShowcaseComponent } from '../components/masked-input-showcase/masked-input-showcase.component'; import { ModalShowcaseComponent } from '../components/modal-showcase/modal-showcase.component'; import { PaginationShowcaseComponent } from '../components/pagination-showcase/pagination-showcase.component'; import { PdfExportShowcaseComponent } from '../components/pdf-export-showcase/pdf-export-showcase.component'; import { PostSubmitErrorShowcaseComponent } from '../components/post-submit-error-showcase/post-submit-error-showcase.component'; import { RadioInputShowcaseComponent } from '../components/radio-input-showcase/radio-input-showcase.component'; import { SnackBarComponentShowcaseComponent } from '../components/snack-bar-showcase/snack-bar-showcase.component'; import { MultiSnackBarComponentShowcaseComponent } from '../components/multi-snack-bar-showcase/multi-snack-bar-showcase.component'; import { SpinnerShowcaseComponent } from '../components/spinner-showcase/spinner-showcase.component'; import { StepperViewShowcaseComponent } from '../components/stepper-view-showcase/stepper-view-showcase.component'; import { TabsShowcaseComponent } from '../components/tabs-showcase/tabs-showcase.component'; import { TitlesShowcaseComponent } from '../components/titles-showcase/titles-showcase.component'; import { TooltipShowcaseComponent } from '../components/tooltip-showcase/tooltip-showcase.component'; import { TypographyShowcaseComponent } from '../components/typography-showcase/typography-showcase.component'; import { MaterialModule } from '../material.module'; import { MenuRoutingModule } from './menu-routing.module'; import { MenuComponent } from './menu.component'; import { IrasDateTimePickerShowcaseComponent } from '../components/date-time-picker-showcase/iras-date-time-picker-showcase.component'; import { MultiSelectDropdownShowcaseComponent } from '../components/multi-select-dropdown-showcase/multi-select-dropdown-showcase.component'; import { MultiSelectNestedDropdownShowcaseComponent } from '../components/multi-select-nested-dropdown-showcase/multi-select-nested-dropdown-showcase.component'; import { MaintenanceLayoutShowcaseComponent } from '../components/maintenance-layout-showcase/maintenance-layout-showcase.component'; import { EmptyStateBoxShowcaseComponent } from '../components/empty-state-box-showcase/empty-state-box-showcase.component'; import { NumericStepperShowcaseComponent } from '../components/numeric-stepper-showcase/numeric-stepper-showcase.component'; import { ErrorShowcaseComponent } from '../components/error-showcase/error-showcase.component'; import { HighlightPanelShowcaseComponent } from '../components/highlight-panel-showcase/highlight-panel-showcase.component'; @NgModule({ declarations: [ MenuComponent, CheckboxInputShowcaseComponent, InputShowcaseComponent, RadioInputShowcaseComponent, MaskedInputShowcaseComponent, ModalShowcaseComponent, ButtonMenuShowcaseComponent, ButtonShowcaseComponent, CardShowcaseComponent, SpinnerShowcaseComponent, DropdownShowcaseComponent, DatePickersShowcaseComponent, TabsShowcaseComponent, StepperViewShowcaseComponent, MultiSelectDropdownShowcaseComponent, MultiSelectNestedDropdownShowcaseComponent, MaintenanceLayoutShowcaseComponent, AutocompleteDropdownShowcaseComponent, DialogPopupShowcaseComponent, PaginationShowcaseComponent, TitlesShowcaseComponent, TypographyShowcaseComponent, IconsShowcaseComponent, PdfExportShowcaseComponent, PostSubmitErrorShowcaseComponent, SnackBarComponentShowcaseComponent, MultiSnackBarComponentShowcaseComponent, FileUploadShowcaseComponent, TooltipShowcaseComponent, IrasDateTimePickerShowcaseComponent, EmptyStateBoxShowcaseComponent, NumericStepperShowcaseComponent, ErrorShowcaseComponent, HighlightPanelShowcaseComponent, ], imports: [ FlexLayoutModule, ReactiveFormsModule, FormsModule, CommonModule, MaterialModule, HttpClientModule, MenuRoutingModule, CommonUiLibraryModule, LayoutModule, PDFExportModule, ], exports: [], schemas: [CUSTOM_ELEMENTS_SCHEMA], }) export class MenuModule {} <file_sep>import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'app-button-showcase', templateUrl: './button-showcase.component.html', styleUrls: ['./button-showcase.component.scss'], }) export class ButtonShowcaseComponent implements OnInit { inputForm: FormGroup; showSpinner = false; constructor(private formBuilder: FormBuilder) { } ngOnInit(): void { this.inputForm = this.formBuilder.group({ fullName: ['', Validators.required], }); } onInputFormSubmit() { if (!this.inputForm.valid) { return; } console.log('valid'); } onSpinnerButtonClick() { this.showSpinner = !this.showSpinner; } onButtonClick() { console.log('Button Click'); } get fullName(): any { return this.inputForm.controls.fullName; } } <file_sep># IRAS Common UI Component Libraries Project Contains Angular Library projects representing eServices and internal UI components and themes. # Getting Started ## eService UI component library npm package name: @iras/irin3-eservices Run eServices UI components showcase ``` npm start showcase will run on https://localhost:4300/ ``` For any 401 auth issues, please verify the user .npmrc is up-to-date with a valid PAT, https://dev.azure.com/IRAS-GOV-SG/IRIN3/_packaging?_a=connect&feed=IRIN3-NPM ## internal UI component library TBD Last Updated At: 2020-08-19 2.43 PM <file_sep>import { Component, OnInit, ViewEncapsulation } from '@angular/core'; @Component({ selector: 'app-file-upload-showcase', templateUrl: './file-upload-showcase.component.html', styleUrls: ['./file-upload-showcase.component.scss'], encapsulation: ViewEncapsulation.ShadowDom, }) export class FileUploadShowcaseComponent implements OnInit { maxNoFiles = 2; constructor() {} ngOnInit(): void {} handleFiles(fileArray: any) { console.log('files uploaded', fileArray); } } <file_sep>import { Component, ViewEncapsulation } from '@angular/core'; @Component({ selector: 'app-empty-state-box-showcase', templateUrl: './empty-state-box-showcase.component.html', styleUrls: ['./empty-state-box-showcase.component.scss'], encapsulation: ViewEncapsulation.ShadowDom, }) export class EmptyStateBoxShowcaseComponent { headerText = 'No records found'; descriptionText = 'There are no records for this month. We recommend that you use the search function to locate other records.'; headerTextOnly = 'No records found'; headerTextSearchResult = 'No records found'; headerTextSearchDescription = 'There are no records for this month. We recommend that you use the search function to locate other records.'; } <file_sep>import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root', }) export class PdfExportService { private pdfContent: any; public exportPDF(pdf: any, pdfContent: any, pdfName: string = 'document.pdf') { this.pdfContent = pdfContent; this.replaceShadowDomsWithHtml(this.pdfContent.nativeElement); const savePdf = new Promise((resolve, reject) => { pdf.saveAs(pdfName); setTimeout(() => { resolve(); }, 1000); }); savePdf.then(() => { this.removeShadowHostInnerHTML(this.pdfContent.nativeElement); }); } private replaceShadowDomsWithHtml(element: any) { for (const el of element.querySelectorAll('*')) { if (el.shadowRoot) { this.replaceShadowDomsWithHtml(el.shadowRoot); el.innerHTML += this.getShadowDomHtml(el.shadowRoot); } } } private getShadowDomHtml(shadowRoot: any) { let shadowHTML = ''; for (const el of shadowRoot.childNodes) { let html = el.nodeValue || el.outerHTML; html = html.replace(':host', ':root'); shadowHTML += html; } return shadowHTML; } private removeShadowHostInnerHTML(element: any) { for (const el of element.querySelectorAll('*')) { if (el.shadowRoot) { this.removeShadowHostInnerHTML(el.shadowRoot); el.innerHTML = ''; } } } } <file_sep>import { NgModule } from '@angular/core'; import { IrasButtonsModule } from './button/button.module'; import { IrasCardsModule } from './card/cards.module'; import { IrasCheckboxModule } from './checkbox/checkbox.module'; import { IrasDialogPopupModule } from './dialog-popup/dialog-popup.module'; import { IrasDropdownsModule } from './dropdowns/dropdowns.module'; import { FormInputErrorModule as IrasFormInputErrorModule } from './form-input-error/form-input-error.module'; import { IrasInputModule } from './input/input.module'; import { IrasNumericStepperModule } from './numeric-stepper/numeric-stepper.module'; import { IrasLinkModule } from './link/link.module'; import { IrasMaskedInputModule } from './masked-input/masked-input.module'; import { ModalComponent } from './modal/modal.component'; import { IrasModalModule } from './modal/modal.module'; import { ModalService } from './modal/modal.service'; import { IrasPaginationModule } from './pagination/pagination.module'; import { IrasPopoverModule } from './popover/popover.module'; import { PopoverService } from './popover/popover.service'; import { IrasRadioButtonModule } from './radio-button/radio-button.module'; import { IrasSpinnerModule } from './spinner/spinner.module'; import { IrasStepperViewModule } from './stepper-view/stepper-view.module'; import { IrasTitleModule } from './title/title.module'; import { IrasTooltipModule } from './tooltip/tooltip.module'; import { IrasMonthYearPickerModule } from './datepickers/iras-month-year-picker/iras-month-year-picker.module'; import { IrasMonthPickerModule } from './datepickers/iras-month-picker/iras-month-picker.module'; import { IrasYearPickerModule } from './datepickers/iras-year-picker/iras-year-picker.module'; import { IrasDatePickerModule } from './datepickers/iras-date-picker/iras-date-picker.module'; import { IrasDateRangePickerModule } from './datepickers/iras-date-range-picker/iras-date-range-picker.module'; import { RequiredSymbolModule } from './required-symbol/required-symbol.module'; import { IrasTextAreaModule } from './text-area/text-area.module'; import { SnackbarComponent } from './snack-bar/snack-bar.component'; import { SnackbarService } from './snack-bar/snack-bar.service'; import { IrasSnackbarModule } from './snack-bar/snack-bar.module'; import { MultiSnackbarComponent } from './multi-snack-bar/multi-snack-bar.component'; import { MultiSnackbarService } from './multi-snack-bar/multi-snack-bar.service'; import { IrasMultiSnackbarModule } from './multi-snack-bar/multi-snack-bar.module'; import { IrasFileUploadModule } from './file-upload/file-upload.module'; import { DialogStepperModule } from './dialog-stepper/dialog-stepper.module'; import { IrasEmptyStateBoxModule } from './empty-state-box/empty-state-box.module'; import { IrasTimePickerModule } from './time-picker/time-picker.module'; import { IrasMaintenanceLayoutModule } from './maintenance-layout/maintenance-layout.module'; import { IrasErrorModule } from './error/error.module'; import { IrasHighlightPanelModule } from './highlight-panel/highlight-panel.module'; @NgModule({ exports: [ // Common Component Modules IrasButtonsModule, IrasTitleModule, IrasStepperViewModule, IrasPaginationModule, IrasDropdownsModule, IrasDialogPopupModule, IrasCheckboxModule, IrasRadioButtonModule, IrasCardsModule, IrasMaintenanceLayoutModule, IrasLinkModule, IrasInputModule, IrasNumericStepperModule, IrasTextAreaModule, IrasMaskedInputModule, IrasFormInputErrorModule, IrasMaskedInputModule, IrasModalModule, IrasTooltipModule, IrasPopoverModule, IrasSpinnerModule, IrasFileUploadModule, DialogStepperModule, IrasEmptyStateBoxModule, // Date Pickers IrasDatePickerModule, IrasMonthYearPickerModule, IrasMonthPickerModule, IrasYearPickerModule, IrasDateRangePickerModule, RequiredSymbolModule, IrasSnackbarModule, IrasTimePickerModule, IrasErrorModule, IrasHighlightPanelModule, IrasMultiSnackbarModule, ], providers: [ModalService, SnackbarService, MultiSnackbarService, PopoverService], entryComponents: [ModalComponent, SnackbarComponent, MultiSnackbarComponent], declarations: [], }) export class CommonUiLibraryModule {} <file_sep>import { ComponentFixture, ComponentFixtureAutoDetect, TestBed, waitForAsync } from '@angular/core/testing'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { IrasMonthPickerComponent } from './iras-month-picker.component'; import { IrasMonthPickerModule } from './iras-month-picker.module'; describe('IrasMonthPickerComponent', () => { let component: IrasMonthPickerComponent; let fixture: ComponentFixture<IrasMonthPickerComponent>; let inputElement: HTMLInputElement; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ imports: [IrasMonthPickerModule, BrowserAnimationsModule], providers: [{ provide: ComponentFixtureAutoDetect, useValue: true }], }) .compileComponents() .then(() => { fixture = TestBed.createComponent(IrasMonthPickerComponent); component = fixture.componentInstance; inputElement = fixture.debugElement.nativeElement.shadowRoot.querySelector('.iras-monthpicker__masked-input'); }); }) ); it('should create', () => { expect(component).toBeTruthy(); }); it('#maskedInputValue should be undefined if write value passes undefined', () => { component.value = undefined; expect(component.maskedInputValue).toBeUndefined(); }); it('#maskedInputValue should be null', () => { component.value = '' as any; fixture.detectChanges(); expect(component.maskedInputValue).toBeNull(); }); it('#maskedInputValue should change if correct date provided', () => { component.value = '2020-01-14' as any; fixture.detectChanges(); expect(component.maskedInputValue).toBe('01/2020'); }); it('#maskedInputValue should change when new date is picked', () => { component.value = '2020-01-14' as any; fixture.detectChanges(); component.value = new Date('2020-Aug-30'); fixture.detectChanges(); const expectedValue = '08/2020'; expect(component.maskedInputValue).toBe(expectedValue); }); // Function test it('getFormattedDate() - tests', () => { let dateStr: string; // display date tests dateStr = component.getFormattedDate({ date: '', formatType: 'display' }); expect(dateStr).toBeFalsy(); dateStr = component.getFormattedDate({ date: new Date('2020-30-Aug'), formatType: 'display' }); expect(dateStr).toBe('08/2020', 'dint format new Date() correctly'); dateStr = component.getFormattedDate({ date: '2020-09-01', formatType: 'display' }); expect(dateStr).toBe('09/2020', 'dint format date string correctly'); dateStr = component.getFormattedDate({ date: '', formatType: 'output' }); expect(dateStr).toBeFalsy(); dateStr = component.getFormattedDate({ date: new Date('2020-30-Aug'), formatType: 'output' }); expect(dateStr).toBe('2020-08', 'dint format new Date() correctly'); dateStr = component.getFormattedDate({ date: '2020-09-01', formatType: 'output' }); expect(dateStr).toBe('2020-09', 'dint format date string correctly'); }); it('#datePicker should not open on input click', () => { component.setDisabledState(true); fixture.detectChanges(); inputElement.click(); fixture.detectChanges(); const datePickerPopupRef = document.querySelector<HTMLElement>('.cdk-overlay-pane.mat-datepicker-popup'); expect(datePickerPopupRef).toBeFalsy('datepicker should not open'); }); // functional tests for open it('#open() - should open if not disabled', () => { component.setDisabledState(false); fixture.detectChanges(); component.open(); fixture.detectChanges(); const datePickerPopupRef = document.querySelector<HTMLElement>('.cdk-overlay-pane.mat-datepicker-popup'); expect(datePickerPopupRef).toBeTruthy('datepicker should open'); }); it('#open() - should not open if disabled', () => { component.setDisabledState(true); fixture.detectChanges(); component.open(); fixture.detectChanges(); const datePickerPopupRef = document.querySelector<HTMLElement>('.cdk-overlay-pane.mat-datepicker-popup'); expect(datePickerPopupRef).toBeFalsy('datepicker should not open'); }); it('#registerOnChange should call onChange', () => { component.registerOnChange(() => {}); expect(component.onChange).toBeTruthy(); }); it('#registerOnTouched should call onTouch', () => { component.registerOnTouched(() => {}); expect(component.onTouch).toBeTruthy(); }); it('#onMonthPickerKeyDown should prevent space', () => { const spy = spyOn(component, 'onMonthPickerKeyDown').and.callThrough(); var e = { code: 'Space', preventDefault: () => { return 'test'; }, }; component.onMonthPickerKeyDown(e); expect(spy).toHaveBeenCalled(); }); it('#writeValue should change value', () => { const month = '12'; component.currentYear = 2020; fixture.detectChanges(); component.writeValue(month); expect(component.maskedInputValue).toEqual('12/2020'); }); it('#onDatePickerClose should work', () => { const spyNext = spyOn(component.monthPickerClosed$, 'next').and.callThrough(); const spyComplete = spyOn(component.monthPickerClosed$, 'complete').and.callThrough(); component.onDatePickerClose(); expect(spyNext).toHaveBeenCalled(); expect(spyComplete).toHaveBeenCalled(); }); it('#onBackspacePressed should work', () => { const spy = spyOn(component, 'onMaskedInputValueChange').and.callThrough(); component.maskedInputValue = ''; fixture.detectChanges(); component.onBackspacePressed(''); expect(spy).toHaveBeenCalled(); }); it('#onMonthSelected should change the value and emit the date picker close', () => { const spy = spyOn(component.datePicker, 'close').and.callThrough(); const option = new Date('2020'); component.onMonthSelected(option); expect(component.maskedInputValue).toEqual('01/2020'); expect(spy).toHaveBeenCalled(); }); it('#ngOnInit should change selectedDate', () => { const currentYear = 2020; const selectedMonth = '12'; const selectedDate = new Date(`${currentYear}-${selectedMonth}`); component.selectedMonth = selectedMonth; component.currentYear = currentYear; fixture.detectChanges(); component.ngOnInit(); expect(component.selectedDate).toEqual(selectedDate); }); }); <file_sep>import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { IrasFileUploadComponent } from './file-upload.component'; import { FileUploadErrorStatus } from './models/file-upload-error-status.model'; import { SupportingDocument } from './models/attachment.model'; import { ComponentMessages } from '@progress/kendo-angular-l10n'; describe('FileUploadComponent', () => { let component: IrasFileUploadComponent; let fixture: ComponentFixture<IrasFileUploadComponent>; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ declarations: [IrasFileUploadComponent], }).compileComponents(); }) ); beforeEach(() => { fixture = TestBed.createComponent(IrasFileUploadComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should format bytes correctly', () => { // Act const result = component.formatBytes('20485', 2); expect(result).toEqual('20 KB'); }); it('should show invalid file type correctly', () => { // Arrange const keyName = 'name'; const blob = new Blob([''], { type: 'text/html' }); blob[keyName] = 'testFile.txt'; // Act const result = component.checkIsFileValidForUpload(blob); // Assert expect(result).toEqual(FileUploadErrorStatus.UnsupportedFileType); }); it('shoul show max file size collectly', () => { // Arrange const keyName = 'name'; const blob = new Blob([''], { type: 'text/html' }); blob[keyName] = 'testFile123456789012345678901234567890123456789012345678901234567890.txt'; // Act const result = component.checkIsFileValidForUpload(blob); // Assert expect(result).toEqual(FileUploadErrorStatus.FileExceed50Characters); }); it('should show invalid file size correctly', () => { // Arrange const keyName = 'name'; const blob = new Blob([''], { type: 'image/png' }); blob[keyName] = 'testFile.jpg'; Object.defineProperty(blob, 'size', { value: 11000000, writable: false }); // Act const result = component.checkIsFileValidForUpload(blob); // Assert expect(result).toEqual(FileUploadErrorStatus.FileExceed10MB); }); it('should show invalid file name correctly', () => { // Arrange const keyName = 'name'; const blob = new Blob([''], { type: 'image/png' }); blob[keyName] = 'testFile().jpg'; Object.defineProperty(blob, 'size', { value: 10000001, writable: false }); // Act const result = component.checkIsFileValidForUpload(blob); // Assert expect(result).toEqual(FileUploadErrorStatus.FileInvalidFileName); }); it('should show valid file correctly', () => { // Arrange const keyName = 'name'; const blob = new Blob([''], { type: 'image/png' }); blob[keyName] = 'testFile.jpg'; Object.defineProperty(blob, 'size', { value: 10000000, writable: false }); // Act const result = component.checkIsFileValidForUpload(blob); // Assert expect(result).toEqual(FileUploadErrorStatus.NoError); }); it('should show valid file extension', () => { // Arrange const keyName = 'name'; const blob = new Blob([''], { type: 'image/png' }); blob[keyName] = 'testFile'; Object.defineProperty(blob, 'size', { value: 10000000, writable: false }); // Act const result = component.checkIsFileValidForUpload(blob); // Assert expect(result).toEqual(FileUploadErrorStatus.UnsupportedFileType); }); it('should prepare files correctly', () => { // Arrange const listOfSupportingDocument: Array<SupportingDocument> = [ { fileName: 'file1.jpg', fileSizeText: '20 KB', fileSizeActual: 20484, }, { fileName: 'file2.jpg', fileSizeText: '10 KB', fileSizeActual: 10245, }, { fileName: 'file3.jpg', fileSizeText: '20 KB', fileSizeActual: 20484, }, ]; const listOfRawFiles: any[] = []; const keyName = 'name'; const blob1 = new Blob([''], { type: 'image/png' }); blob1[keyName] = '<KEY>'; Object.defineProperty(blob1, 'size', { value: 20484, writable: false }); const blob2 = new Blob([''], { type: 'image/png' }); blob2[keyName] = '<KEY>'; Object.defineProperty(blob2, 'size', { value: 10245, writable: false }); const blob3 = new Blob([''], { type: 'image/png' }); blob3[keyName] = '<KEY>'; Object.defineProperty(blob3, 'size', { value: 20484, writable: false }); listOfRawFiles.push(blob1); listOfRawFiles.push(blob2); listOfRawFiles.push(blob3); // Act component.fileBrowseHandler(listOfRawFiles); // Assert expect(component.document.supportingDocuments).toEqual(listOfSupportingDocument); }); it('should delete files correctly', () => { // Arrange const listOfSupportingDocument: Array<SupportingDocument> = [ { fileName: 'file1.jpg', fileSizeText: '20 KB', fileSizeActual: 20484, }, { fileName: 'file3.jpg', fileSizeText: '20 KB', fileSizeActual: 20484, }, ]; const listOfRawFiles: any[] = []; const keyName = 'name'; const blob1 = new Blob([''], { type: 'image/png' }); blob1[keyName] = '<KEY>'; Object.defineProperty(blob1, 'size', { value: 20484, writable: false }); const blob2 = new Blob([''], { type: 'image/png' }); blob2[keyName] = '<KEY>'; Object.defineProperty(blob2, 'size', { value: 10245, writable: false }); const blob3 = new Blob([''], { type: 'image/png' }); blob3[keyName] = '<KEY>'; Object.defineProperty(blob3, 'size', { value: 20484, writable: false }); listOfRawFiles.push(blob1); listOfRawFiles.push(blob2); listOfRawFiles.push(blob3); // Act component.fileBrowseHandler(listOfRawFiles); component.deleteFile(1, 10245); // Assert expect(component.document.supportingDocuments).toEqual(listOfSupportingDocument); }); it('should call on duplicate file ok', () => { spyOn(component, 'onDuplicateFilesOkClick').and.callThrough(); spyOn(component, 'replaceUploadSelectedFile').and.callThrough(); component.onDuplicateFileOkClick({ toBeUpload: true, index: -1 }); component.onDuplicateFileOkClick({ toBeUpload: false, index: -1 }); }); it('should run for all duplicate files ok', () => { component.filesContainingDuplicate = [ { name: '1 TESTJPG.jpg', size: 5332, type: 'image/jpeg', }, { name: '2 TESTJPG.jpg', size: 5332, type: 'image/jpeg', }, { name: '3 TESTJPG.jpg', size: 5332, type: 'image/jpeg', }, ]; component.files = [ { name: '1 TESTJPG.jpg', size: 5332, type: 'image/jpeg', }, { name: '2 TESTJPG.jpg', size: 5332, type: 'image/jpeg', }, { name: '3 TESTJPG.jpg', size: 5332, type: 'image/jpeg', }, ]; component.onDuplicateFilesOkClick(); }); it('should replace uploaded selected file', () => { component.filesContainingDuplicate = [ { name: '1 TESTJPG.jpg', size: 5332, type: 'image/jpeg', }, { name: '2 TESTJPG.jpg', size: 5332, type: 'image/jpeg', }, { name: '3 TESTJPG.jpg', size: 5332, type: 'image/jpeg', }, ]; component.files = [ { name: '1 TESTJPG.jpg', size: 5332, type: 'image/jpeg', }, { name: '2 TESTJPG.jpg', size: 5332, type: 'image/jpeg', }, { name: '3 TESTJPG.jpg', size: 5332, type: 'image/jpeg', }, ]; component.replaceUploadSelectedFile(1); }); it(' shoud delete file for error row', () => { component.deleteFileForErrorRow(0); }); it('should upload dropped files', () => { const listOfRawFiles: any[] = []; const keyName = 'name'; const blob1 = new Blob([''], { type: 'image/png' }); blob1[keyName] = 'file1.jpg'; Object.defineProperty(blob1, 'size', { value: 256, writable: false }); const blob2 = new Blob([''], { type: 'image/png' }); blob2[keyName] = 'file2.jpg'; Object.defineProperty(blob2, 'size', { value: 256, writable: false }); listOfRawFiles.push(blob1); listOfRawFiles.push(blob2); component.files = []; component.onFileDropped(listOfRawFiles); expect(component.files.length).toEqual(2); }); it('should preview upload file', () => { const listOfRawFiles: any[] = []; const keyName = 'name'; const blob1 = new Blob([''], { type: 'image/png' }); blob1[keyName] = 'file1.jpg'; Object.defineProperty(blob1, 'size', { value: 256, writable: false }); component.files = []; listOfRawFiles.push(blob1); component.fileBrowseHandler(listOfRawFiles); component.onUploadedFilePreviewClick(0); }); }); <file_sep>export class Attachment { id: string; createdBy: string; dateTimeCreated: Date; updatedBy: string; dateTimeUpdated: Date; codeAuditReason: number; codeAuditSource: number; blobUrl: string; fileName: string; fileExtension: string; fileSize: number; // in KB codeFileProcessStatus: number; taxMailMessageId: string; } export class Document { supportingDocuments: Array<SupportingDocument>; // Used in Details page supportingDocumentsRaw: any[]; } export class SupportingDocument { fileName: string; fileSizeText: string; // 8.71 MB fileSizeActual: number; // 9,135,668 bytes } export class SupportingDocumentError { fileName: string; fileFormatErrorMsg: string; } <file_sep>import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { FlexLayoutModule } from '@angular/flex-layout'; import { IrasLinkModule } from '../link/link.module'; import { ButtonComponent } from './button/button.component'; import { FloatingButtonMenuComponent } from './floating-button-menu/button-menu.component'; import { IconButtonComponent } from './icon-button/icon-button.component'; @NgModule({ declarations: [ButtonComponent, FloatingButtonMenuComponent, IconButtonComponent], imports: [CommonModule, FlexLayoutModule, IrasLinkModule], exports: [ButtonComponent, FloatingButtonMenuComponent, IconButtonComponent, FlexLayoutModule, IrasLinkModule], }) export class IrasButtonsModule {} <file_sep>import { PortalModule } from '@angular/cdk/portal'; import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { HighlightPanelComponent } from './highlight-panel.component'; @NgModule({ declarations: [HighlightPanelComponent], imports: [CommonModule, PortalModule], exports: [PortalModule, HighlightPanelComponent], }) export class IrasHighlightPanelModule {} <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FlexLayoutModule } from '@angular/flex-layout'; import { IrasButtonsModule } from '../button/button.module'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { DialogStepperComponent } from './dialog-stepper.component'; @NgModule({ declarations: [DialogStepperComponent], imports: [CommonModule, IrasButtonsModule, FlexLayoutModule, FormsModule, ReactiveFormsModule], exports: [IrasButtonsModule, FlexLayoutModule, FormsModule, ReactiveFormsModule, DialogStepperComponent], }) export class DialogStepperModule {} <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RadioButtonComponent } from './radio-button.component'; import { FormsModule } from '@angular/forms'; import { FlexLayoutModule } from '@angular/flex-layout'; @NgModule({ declarations: [RadioButtonComponent], imports: [CommonModule, FormsModule, FlexLayoutModule], exports: [FormsModule, FlexLayoutModule, RadioButtonComponent], }) export class IrasRadioButtonModule {} <file_sep>import { loadAsset } from './asset-loader.util'; let location = { origin: 'https://localhost' }; describe('ModifyValueOnPaste', () => { it('localhost should load dev URL', () => { const url = loadAsset({ type: 'icons', assetName: 'close.svg' }); console.log(url); expect(url).toContain('https://irin3.dev.irasgcc.gov.sg'); }); it('uat should load uat URL', () => { location.origin = 'https://irin3.uat.irasgcc.gov.sg'; const url = loadAsset({ type: 'icons', assetName: 'close.svg' }); console.log(url); expect(url).toContain('estamping/assets/icons/close.svg'); }); }); <file_sep>import { Injectable } from '@angular/core'; import { fromEvent } from 'rxjs'; import { takeUntil } from 'rxjs/operators'; @Injectable() export abstract class DatePickerUtilities { openDatePicker(controls: any) { if (controls.disabled) { return; } controls.datePicker.startAt = new Date('en-SG'); controls.datePicker.open(); controls.onTouch(); } onDatePickerOpened(controls: any) { const source = fromEvent(document, 'click').pipe(takeUntil(controls.datePickerClosed$)); source.subscribe((event) => { if (controls.monthViewActive) { const clickedTargetClosestPeriodButton = (event.target as any).closest( 'button.mat-focus-indicator.mat-calendar-period-button.mat-button.mat-button-base' ); if (!!clickedTargetClosestPeriodButton && clickedTargetClosestPeriodButton.click) { clickedTargetClosestPeriodButton.click(); } } controls.monthViewActive = document.querySelectorAll('.mat-calendar-body-cell-content').length === 12; }); } onDatePickerClosed(controls: any) { controls.datePickerClosed$.next(); controls.datePickerClosed$.complete(); } } <file_sep>import { Component, OnInit, ElementRef, ViewChild } from '@angular/core'; import { PdfExportService } from './service/pdf-export.service'; import { PDFExportComponent } from '@progress/kendo-angular-pdf-export'; @Component({ selector: 'app-pdf-export', templateUrl: 'pdf-export-showcase.component.html', styleUrls: ['./pdf-export.showcase.component.scss'], }) export class PdfExportShowcaseComponent implements OnInit { @ViewChild('pdfContent') pdfContent: ElementRef; @ViewChild('pdf') pdf: PDFExportComponent; scale = 0.8; constructor(private pdfExportService: PdfExportService) {} ngOnInit() {} exportPdf() { console.log('Exporting PDF...'); this.pdfExportService.exportPDF(this.pdf, this.pdfContent, 'stamp-duty-receipt.pdf'); } } <file_sep>import { ComponentFixture, ComponentFixtureAutoDetect, TestBed, waitForAsync } from '@angular/core/testing'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { IrasYearPickerComponent } from './iras-year-picker.component'; import { IrasYearPickerModule } from './iras-year-picker.module'; describe('IrasYearPickerComponent', () => { let component: IrasYearPickerComponent; let fixture: ComponentFixture<IrasYearPickerComponent>; let inputElement: HTMLInputElement; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ imports: [IrasYearPickerModule, BrowserAnimationsModule], providers: [{ provide: ComponentFixtureAutoDetect, useValue: true }], }) .compileComponents() .then(() => { fixture = TestBed.createComponent(IrasYearPickerComponent); component = fixture.componentInstance; inputElement = fixture.debugElement.nativeElement.shadowRoot.querySelector('.iras-year-picker__masked-input'); }); }) ); it('should create', () => { expect(component).toBeTruthy(); }); it('#maskedInputValue should be undefined if write value passes undefined', () => { component.value = undefined; expect(component.maskedInputValue).toBeUndefined(); }); it('#maskedInputValue should be null', () => { component.value = '' as any; fixture.detectChanges(); expect(component.maskedInputValue).toBeNull(); }); it('#maskedInputValue should change if correct date provided', () => { component.value = '2020-01-14' as any; fixture.detectChanges(); expect(component.maskedInputValue).toBe('2020'); }); it('#maskedInputValue should change when new date is picked', () => { component.value = '2020-01-14' as any; fixture.detectChanges(); component.value = new Date('2020-Aug-30'); fixture.detectChanges(); const expectedValue = '2020'; expect(component.maskedInputValue).toBe(expectedValue); }); // Function test it('getFormattedDate() - tests', () => { let dateStr: string; const expectedValue = '2020'; // display date tests dateStr = component.getFormattedDate({ date: '', formatType: 'display' }); expect(dateStr).toBeFalsy(); dateStr = component.getFormattedDate({ date: new Date('2020-30-Aug'), formatType: 'display' }); expect(dateStr).toBe(expectedValue, 'dint format new Date() correctly'); dateStr = component.getFormattedDate({ date: '2020-09-01', formatType: 'display' }); expect(dateStr).toBe(expectedValue, 'dint format date string correctly'); dateStr = component.getFormattedDate({ date: '', formatType: 'output' }); expect(dateStr).toBeFalsy(); dateStr = component.getFormattedDate({ date: new Date('2020-30-Aug'), formatType: 'output' }); expect(dateStr).toBe(expectedValue, 'dint format new Date() correctly'); dateStr = component.getFormattedDate({ date: '2020-09-01', formatType: 'output' }); expect(dateStr).toBe(expectedValue, 'dint format date string correctly'); }); it('#datePicker should not open on input click', () => { component.setDisabledState(true); fixture.detectChanges(); inputElement.click(); fixture.detectChanges(); const datePickerPopupRef = document.querySelector<HTMLElement>('.cdk-overlay-pane.mat-datepicker-popup'); expect(datePickerPopupRef).toBeFalsy('datepicker should not open'); }); // functional tests for open it('#open() - should open if not disabled', () => { component.setDisabledState(false); fixture.detectChanges(); component.open(); fixture.detectChanges(); const datePickerPopupRef = document.querySelector<HTMLElement>('.cdk-overlay-pane.mat-datepicker-popup'); expect(datePickerPopupRef).toBeTruthy('datepicker should open'); }); // functional tests for open it('#open() - should open with monthActive true if not disabled', () => { component.setDisabledState(false); component.monthViewActive = true; fixture.detectChanges(); component.open(); fixture.detectChanges(); const datePickerPopupRef = document.querySelector<HTMLElement>('.cdk-overlay-pane.mat-datepicker-popup'); expect(datePickerPopupRef).toBeTruthy('datepicker should open'); }); it('#open() - should not open if disabled', () => { component.setDisabledState(true); fixture.detectChanges(); component.open(); fixture.detectChanges(); const datePickerPopupRef = document.querySelector<HTMLElement>('.cdk-overlay-pane.mat-datepicker-popup'); expect(datePickerPopupRef).toBeFalsy('datepicker should not open'); }); it('#ngOnInit should change maxDate minDate and selectedDate', () => { const maxYear = '2020'; const minYear = '2020'; const selectedYear = '2020'; component.maxYear = maxYear; component.minYear = minYear; component.selectedYear = selectedYear; fixture.detectChanges(); component.ngOnInit(); expect(component.maxDate).toEqual(new Date(`${maxYear}-Jan`)); expect(component.minDate).toEqual(new Date(`${minYear}-Jan`)); expect(component.selectedDate).toEqual(new Date(`${selectedYear}-Jan`)); }); it('#writeValue should change value', () => { const year = '2020'; component.writeValue(year); expect(component.maskedInputValue).toEqual(year); }); it('#writeValue should change value with default value', () => { component.writeValue(undefined); expect(component.value).toEqual(undefined); }); it('#registerOnChange should call onChange', () => { component.registerOnChange(() => {}); expect(component.onChange).toBeTruthy(); }); it('#registerOnTouched should call onTouch', () => { component.registerOnTouched(() => {}); expect(component.onTouch).toBeTruthy(); }); it('#onDateChange should emit the dateChanged event', () => { const spy = spyOn(component.dateChanged, 'emit').and.callThrough(); component.onDateChange(new Date()); expect(spy).toHaveBeenCalled(); }); it('#onDatePickerClose should work', () => { const spyNext = spyOn(component.datePickerClosed$, 'next').and.callThrough(); const spyComplete = spyOn(component.datePickerClosed$, 'complete').and.callThrough(); component.onDatePickerClose(); expect(spyNext).toHaveBeenCalled(); expect(spyComplete).toHaveBeenCalled(); }); it('#onBackspacePressed should work', () => { const spy = spyOn(component, 'onMaskedInputValueChange').and.callThrough(); component.maskedInputValue = ''; fixture.detectChanges(); component.onBackspacePressed(''); expect(spy).toHaveBeenCalled(); }); it('#onYearSelected should change the value and emit the date picker close', () => { const spy = spyOn(component.datePicker, 'close').and.callThrough(); const option = new Date('2020'); component.onYearSelected(option); expect(component.maskedInputValue).toEqual('2020'); expect(spy).toHaveBeenCalled(); }); it('#onYearPickerKeyDown should prevent space', () => { const spy = spyOn(component, 'onYearPickerKeyDown').and.callThrough(); var e = { code: 'Space', preventDefault: () => { return 'test'; }, }; component.onYearPickerKeyDown(e); expect(spy).toHaveBeenCalled(); }); }); <file_sep># Component: @iras/irin3-eservices Installation guide for the Library: https://dev.azure.com/isds3/ISDS/_wiki/wikis/PMO.wiki/348/Angular-Common-UI-Library Contains: - <ngi-button> <ngi-button type="IrasPrimaryBtn" text="Search"></ngi-button> <ngi-button type="IrasPrimaryInvertBtn" text="Clear"></ngi-button> <ngi-button [isSpinnerShown]=isLoading type="IrasPrimaryBtn" text="RETRIEVE"></ngi-button> - <ngi-title-header> <ngi-title-header [title]="'Getting Started'"></ngi-title-header> <file_sep>import { Component, EventEmitter, Output, Input } from '@angular/core'; @Component({ selector: 'dialog-stepper', templateUrl: './dialog-stepper.component.html', styleUrls: ['./dialog-stepper.component.scss'], }) export class DialogStepperComponent { @Input() headings: Array<string>; @Input() activeIndex: number; isCancelAction = true; @Input() cancelActionText = 'Close'; @Input() cancelActionStyle = 'btn btn-primary-invert'; @Output() dialogClose = new EventEmitter(); constructor() {} closeButton() { this.dialogClose.emit(); } } <file_sep>import { Component, EventEmitter, Input, Output, OnInit, TemplateRef, ViewChild, OnChanges, SimpleChanges, } from '@angular/core'; import { MatDialogRef } from '@angular/material/dialog'; import { ModalService } from '../modal/modal.service'; import { ModalComponent } from '../modal/modal.component'; @Component({ selector: 'iras-dialog-popup', templateUrl: './dialog-popup.component.html', styleUrls: ['./dialog-popup.component.scss'], }) export class DialogPopupComponent implements OnInit, OnChanges { @Input() title: string; @Input() description1: string; @Input() description2: string; @Input() isOkAction = true; @Input() okActionText = 'Continue'; @Input() okActionStyle = 'btn btn-primary'; @Input() isCancelAction = true; @Input() cancelActionText = 'Cancel'; @Input() cancelActionStyle = 'btn btn-primary-invert'; @Input() showTitleIcon = true; @Input() showFileUploadConflictPanel = false; @Input() dialogOpen = false; @Input() width = '414px'; @Input() height = 'auto'; @Input() fileUploadDuplicates: any[]; @Output() dialogClose: EventEmitter<string> = new EventEmitter(); @Output() dialogContinue: EventEmitter<any> = new EventEmitter(); currentDuplicateFileName: string; replaceDuplicateSelected: boolean; replaceAllDuplicateSelected: boolean; hasSingleConflict: boolean; duplicateFileIndex: number; dialogRef: MatDialogRef<ModalComponent>; dialogClosedStatus: string; uploadConflictRadioOptions = [ { label: 'Upload and replace', selected: false, buttonTheme: 'primary', disabled: false, }, { label: 'Skip this file', selected: false, buttonTheme: 'primary', disabled: false, }, ]; @ViewChild('dialogContentRef', { static: false }) dialogModalContentRef: TemplateRef<any>; constructor(public modalService: ModalService) {} ngOnInit() { if (this.fileUploadDuplicates?.length > 0) { this.initUpload(); } } ngOnChanges(changes: SimpleChanges): void { if ( this.dialogModalContentRef && changes.dialogOpen && changes.dialogOpen.previousValue !== changes.dialogOpen.currentValue ) { if (changes.dialogOpen.currentValue) { this.dialogRef = this.modalService.show({ data: { templateContentRef: this.dialogModalContentRef, }, panelClass: 'default-modal', backdropClass: 'default-modal-dialog-backdrop', disableClose: true, }); this.dialogRef.afterClosed().subscribe((_) => { this.dialogClose.emit(this.dialogClosedStatus); }); } } } public onBack(status) { this.dialogClosedStatus = status; this.dialogRef.close(); } public onContinue(status) { if (this.fileUploadDuplicates?.length > 0) { this.onFileUploadDuplicates(); } else { this.dialogContinue.emit(status); } this.dialogRef.close(); } initUpload() { if (this.fileUploadDuplicates?.length > 0) { if (this.fileUploadDuplicates.length === 1) { this.uploadConflictRadioOptions.splice(1, 1); this.hasSingleConflict = true; } else { this.hasSingleConflict = false; } this.currentDuplicateFileName = this.fileUploadDuplicates[0].name; this.duplicateFileIndex = 0; this.replaceAllDuplicateSelected = true; } } onRadioChecked(event: any) { if ( event.target.nextElementSibling.textContent.toLowerCase() === this.uploadConflictRadioOptions[0].label.toLowerCase() && event.target.checked ) { this.replaceDuplicateSelected = true; } else { this.replaceDuplicateSelected = false; } } onFileUploadDuplicates() { if (this.replaceAllDuplicateSelected) { if (this.replaceDuplicateSelected) { // Replace all files this.dialogContinue.emit({ toBeUpload: true, index: -1 }); } else { // Skip all files this.dialogContinue.emit({ toBeUpload: false, index: -1 }); } } else { if (this.replaceDuplicateSelected) { // Replace selected file and load the next file if (this.fileUploadDuplicates.length > this.duplicateFileIndex) { this.dialogContinue.emit({ toBeUpload: true, index: this.duplicateFileIndex }); this.updateCurrentFileIndex(); } } else { // Skip the selected file and load the next file if (this.fileUploadDuplicates.length > this.duplicateFileIndex) { this.dialogContinue.emit({ toBeUpload: false, index: this.duplicateFileIndex }); this.updateCurrentFileIndex(); } } } } updateCurrentFileIndex() { if (this.fileUploadDuplicates && this.fileUploadDuplicates.length > 0) { this.duplicateFileIndex++; if (this.duplicateFileIndex === this.fileUploadDuplicates.length - 1) { this.hasSingleConflict = true; if (this.uploadConflictRadioOptions.length > 1) { this.uploadConflictRadioOptions.splice(1, 1); } } if (this.duplicateFileIndex < this.fileUploadDuplicates.length) { this.currentDuplicateFileName = this.fileUploadDuplicates[this.duplicateFileIndex].name; } } } } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { DialogPopupComponent } from './dialog-popup.component'; import { FlexLayoutModule } from '@angular/flex-layout'; import { IrasButtonsModule } from '../button/button.module'; import { IrasRadioButtonModule } from '../radio-button/radio-button.module'; import { IrasModalModule } from '../modal/modal.module'; @NgModule({ declarations: [DialogPopupComponent], imports: [CommonModule, IrasButtonsModule, FlexLayoutModule, IrasRadioButtonModule, IrasModalModule], exports: [IrasButtonsModule, FlexLayoutModule, DialogPopupComponent], }) export class IrasDialogPopupModule {} <file_sep>import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { IrasModalModule } from '../modal/modal.module'; import { ModalService } from '../modal/modal.service'; import { DialogPopupComponent } from './dialog-popup.component'; describe('DialogPopupComponent', () => { let component: DialogPopupComponent; let fixture: ComponentFixture<DialogPopupComponent>; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ declarations: [DialogPopupComponent], imports: [IrasModalModule, NoopAnimationsModule], providers: [ModalService], }).compileComponents(); }) ); beforeEach(() => { fixture = TestBed.createComponent(DialogPopupComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should update current file index', () => { component.updateCurrentFileIndex(); }); it('should init', () => { component.fileUploadDuplicates = [ { name: '1 TESTJPG.jpg', size: 5332, type: 'image/jpeg', }, ]; component.uploadConflictRadioOptions = [ { label: 'Upload and replace', selected: false, buttonTheme: 'primary', disabled: false, }, { label: 'Skip this file', selected: false, buttonTheme: 'primary', disabled: false, }, ]; component.ngOnInit(); // Assert expect(component.hasSingleConflict).toEqual(true); }); it('should replace duplicate file uploads', () => { component.replaceAllDuplicateSelected = false; component.replaceDuplicateSelected = true; component.duplicateFileIndex = 0; component.fileUploadDuplicates = [ { name: '1 TESTJPG.jpg', size: 5332, type: 'image/jpeg', }, { name: '2 TESTJPG.jpg', size: 5332, type: 'image/jpeg', }, ]; component.onFileUploadDuplicates(); }); it('should skip duplicate file uploads', () => { component.replaceAllDuplicateSelected = false; component.replaceDuplicateSelected = false; component.duplicateFileIndex = 0; component.fileUploadDuplicates = [ { name: '1 TESTJPG.jpg', size: 5332, type: 'image/jpeg', }, { name: '2 TESTJPG.jpg', size: 5332, type: 'image/jpeg', }, ]; component.onFileUploadDuplicates(); }); it('#ngOnChanges should work', () => { component.ngOnChanges({ dialogOpen: { isFirstChange: () => false, previousValue: false, currentValue: true, firstChange: false, }, }); component.onBack('ClosedButton Clicked'); expect(component.onBack).toBeTruthy(); expect(component.ngOnChanges).toBeTruthy(); component.fileUploadDuplicates = [ { name: '1 TESTJPG.jpg', size: 5332, type: 'image/jpeg', }, ]; component.replaceAllDuplicateSelected = true; fixture.detectChanges(); component.onContinue('Continue Clicked'); expect(component.onContinue).toBeTruthy(); }); }); <file_sep>import { Component, Input, ViewChild, TemplateRef, OnInit } from '@angular/core'; import { ModalService } from '../modal/modal.service'; @Component({ selector: 'iras-stepper-view', templateUrl: './stepper-view.component.html', styleUrls: ['./stepper-view.component.scss'], }) export class StepperViewComponent implements OnInit { currentIndex = 0; @ViewChild('modalContentRef', { static: false }) modalContentRef: TemplateRef<any>; @Input() headings: Array<string> = []; @Input() activeIndex = 0; public dialog2Opened = false; constructor(public modalService: ModalService) {} ngOnInit(): void {} showModal() { this.modalService.show({ data: { templateContentRef: this.modalContentRef, }, panelClass: 'default-modal', backdropClass: 'default-modal-dialog-backdrop', }); } hideModal() { this.modalService.hide(); } } <file_sep>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-maintenance-layout-showcase', templateUrl: './maintenance-layout-showcase.component.html', styleUrls: ['./maintenance-layout-showcase.component.scss'], }) export class MaintenanceLayoutShowcaseComponent implements OnInit { header = 'Maintenance in progress'; description = 'myTax Portal will not be available from 2:00 AM to 5:00 AM (Singapore Time) on 6 Jan 2021 (Wed)'; constructor() {} ngOnInit(): void {} } <file_sep>export * from './helpers'; // Full library export * from './lib/button/button.module'; export * from './lib/card/cards.module'; export * from './lib/checkbox/checkbox-options.type'; export * from './lib/checkbox/checkbox.module'; export * from './lib/common-ui-library.module'; export * from './lib/datepickers/iras-date-picker/iras-date-picker.module'; export * from './lib/datepickers/iras-date-range-picker/iras-date-range-picker.module'; export * from './lib/datepickers/iras-month-picker/iras-month-picker.module'; // Date Picker export * from './lib/datepickers/iras-month-year-picker/iras-month-year-picker.module'; export * from './lib/datepickers/iras-year-picker/iras-year-picker.module'; export * from './lib/dialog-popup/dialog-popup.module'; export * from './lib/dropdowns/dropdowns.module'; // File Upload export * from './lib/file-upload/file-upload.module'; // form-input-error export * from './lib/form-input-error/form-input-error.module'; // Input export * from './lib/input/input.module'; export * from './lib/link/link.module'; export * from './lib/masked-input/mask.enum'; // Masked Input export * from './lib/masked-input/masked-input.module'; // modal module export * from './lib/modal/modal.module'; export * from './lib/modal/modal.service'; export * from './lib/pagination/pagination.module'; // Radio Button export * from './lib/radio-button/radio-button.module'; export * from './lib/radio-button/radio-button.type'; export * from './lib/required-symbol/required-symbol.module'; // snack bar module export * from './lib/snack-bar/snack-bar.module'; export * from './lib/snack-bar/snack-bar.service'; // spinner module export * from './lib/spinner/spinner.module'; export * from './lib/stepper-view/stepper-view.module'; // Text Area export * from './lib/text-area/text-area.module'; export * from './lib/time-picker/time-picker.module'; export * from './lib/title/title.module'; // types export * from './types'; //Stepper RWD export * from './lib/dialog-stepper/dialog-stepper.module'; // Error export * from './lib/error/error.module'; // Highlight Panel export * from './lib/highlight-panel/highlight-panel.module'; // multi snack bar module export * from './lib/multi-snack-bar/multi-snack-bar.module'; export * from './lib/multi-snack-bar/multi-snack-bar.service'; <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { TitleHeaderComponent } from './title-header.component'; @NgModule({ declarations: [TitleHeaderComponent], imports: [CommonModule], exports: [TitleHeaderComponent], }) export class IrasTitleModule {} <file_sep>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-highlight-panel-showcase', templateUrl: './highlight-panel-showcase.component.html', styleUrls: ['./highlight-panel-showcase.component.scss'], }) export class HighlightPanelShowcaseComponent implements OnInit { cardItem2Valid = false; constructor() {} ngOnInit(): void {} } <file_sep>import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { ButtonComponent } from './button.component'; describe('ButtonComponent', () => { let component: ButtonComponent; let fixture: ComponentFixture<ButtonComponent>; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ declarations: [ButtonComponent], }).compileComponents(); }) ); beforeEach(() => { fixture = TestBed.createComponent(ButtonComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('#stateDisabled, container element has disabled class', () => { component.disabled = true; fixture.detectChanges(); const element = fixture.debugElement.nativeElement; const classList = element.shadowRoot.querySelector('.iras-button__container').getAttribute('class'); expect(classList.includes('iras-button__container--disabled')).toBeTrue(); }); it('#stateEnabled, container element does not have disabled class', () => { component.disabled = false; fixture.detectChanges(); const element = fixture.debugElement.nativeElement; const classList = element.shadowRoot.querySelector('.iras-button__container').getAttribute('class'); expect(classList.includes('iras-button__container--disabled')).not.toBeTrue(); }); it('#onButtonClick should emit buttonClicked', () => { const spy = spyOn(component.buttonClicked, 'emit').and.callThrough(); component.buttonType = 'button'; fixture.detectChanges(); component.onButtonClick(''); expect(spy).toHaveBeenCalled(); }); it('#onButtonClick should emit buttonClicked', () => { const spy = spyOn(component.buttonClicked, 'emit').and.callThrough(); component.buttonType = 'submit'; fixture.detectChanges(); component.onButtonClick(''); expect(spy).toHaveBeenCalled(); }); it('#computeButtonClass, should emit with custom style', () => { component.fill = 'outline'; component.shape = 'custom'; component.size = 'small'; component.color = 'danger'; fixture.detectChanges(); expect(component.computeButtonClass()).toEqual( JSON.parse( '{ "iras-button__fill--outline": true, "iras-button__shape--custom": true, "iras-button__size--small": true, "iras-color iras-color-danger iras-button__color--danger": true }' ) ); }); it('#computeButtonClass, should emit default style', () => { expect(component.computeButtonClass()).toEqual( JSON.parse( '{ "iras-button__fill--solid": true, "iras-button__shape--default": true, "iras-button__size--default": true, "iras-color iras-color-primary iras-button__color--primary": true }' ) ); }); it('#ngOnChanges should work', () => { const spy = spyOn(component, 'computeButtonClass').and.callThrough(); component.ngOnChanges({ defaultValue: { isFirstChange: () => false, previousValue: 'With Duty', currentValue: 'Relief', firstChange: false, }, }); expect(spy).toHaveBeenCalledWith(); }); }); <file_sep>export * from './date-range.model'; <file_sep>import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { FlexLayoutModule } from '@angular/flex-layout'; import { IrasLinkModule } from '../link/link.module'; import { IrasFileUploadComponent } from './file-upload.component'; import { IrasDialogPopupModule } from '../dialog-popup/dialog-popup.module'; import { FormInputErrorModule } from '../form-input-error/form-input-error.module'; import { DragAndDropDirective } from './drag-drop.directive'; @NgModule({ declarations: [IrasFileUploadComponent, DragAndDropDirective], imports: [CommonModule, FlexLayoutModule, IrasLinkModule, IrasDialogPopupModule, FormInputErrorModule], exports: [IrasFileUploadComponent, FlexLayoutModule, IrasLinkModule, IrasDialogPopupModule, FormInputErrorModule], }) export class IrasFileUploadModule {} <file_sep>export const regexAmountInputPattern = { amountThousandSeparator: new RegExp('(\\-?\\d)(?=(\\d{3})+(?!\\d))', 'g'), }; export function getThousandSeparatedAmount(val: string | number, decimalLength?: number) { decimalLength = decimalLength ? decimalLength : 2; if (val === '-') { return val; } if (!!!val) { return; } const tmp = +val.toString(); let value = val; const res = val.toString().split('.'); if (res.length > 0 || (res.length > 1 && res[1].length < decimalLength + 1)) { value = tmp.toFixed(decimalLength); } let convertedValue = value.toString().split('.'); return convertedValue[0].replace(regexAmountInputPattern.amountThousandSeparator, '$1,') + '.' + convertedValue[1]; } export function getThousandSeparatedForAmountFilter(val: string | number) { if (val === '-') { return val; } const res = val.toString().split('.'); if (res.length > 1 && res[1].length > 2) { return res[0].replace(regexAmountInputPattern.amountThousandSeparator, '$1,') + '.' + res[1]; } return val.toString().replace(regexAmountInputPattern.amountThousandSeparator, '$1,'); } <file_sep>import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { MatDialogRef } from '@angular/material/dialog'; import { ModalService } from '../modal/modal.service'; import { StepperViewComponent } from './stepper-view.component'; import { TemplateRef } from '@angular/core'; import { By } from '@angular/platform-browser'; describe('StepperViewComponent', () => { let component: StepperViewComponent; let fixture: ComponentFixture<StepperViewComponent>; let service: ModalService; let modalContentRef: TemplateRef<any>; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ declarations: [StepperViewComponent], providers: [ { provide: ModalService, useClass: ModalServiceStub }, { provide: MatDialogRef, useValue: { close: () => {}, }, }, ], }).compileComponents(); }) ); beforeEach(() => { fixture = TestBed.createComponent(StepperViewComponent); component = fixture.componentInstance; component.headings = ['Getting Started', 'Assets']; component.activeIndex = 1; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should call show modal when clicking icon', () => { spyOn(fixture.componentInstance, 'showModal').and.callThrough(); const continueButton = fixture.debugElement.query(By.css('#stepper-icon')); continueButton.triggerEventHandler('click', null); fixture.detectChanges(); expect(component.showModal).toHaveBeenCalled(); }); }); class ModalServiceStub { hide() {} show() {} } <file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { TabStripComponent } from '@progress/kendo-angular-layout'; @Component({ selector: 'app-tabs-showcase.component', templateUrl: './tabs-showcase.component.html', }) export class TabsShowcaseComponent implements OnInit { tabTitles = ['Financial Records', 'Non-Financial Records/ In-Progress']; @ViewChild('tabStrip', { static: false }) tabStrip: TabStripComponent; ngOnInit(): void {} onTabSelect(tab: any) { console.log(tab.title); } }
1bb8949786ad18b2dd8616da06aee617e8fbdb1e
[ "Markdown", "TypeScript" ]
52
TypeScript
yenaungideal/iras-eservices
f2fa3bb87507b1a6815c609c8aaf5f9b7ef97406
7cd53df2caf6008268af770e9cecd75d31649c80
refs/heads/master
<file_sep>// TreeShowDlg.h : 头文件 // #pragma once #include "afxcmn.h" // CTreeShowDlg 对话框 class CTreeShowDlg : public CDialogEx { // 构造 public: CTreeShowDlg(CWnd* pParent = NULL); // 标准构造函数 ~CTreeShowDlg(); // 对话框数据 enum { IDD = IDD_TREESHOW_DIALOG }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 // 实现 protected: HICON m_hIcon; // 生成的消息映射函数 virtual BOOL OnInitDialog(); afx_msg void OnSysCommand(UINT nID, LPARAM lParam); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); DECLARE_MESSAGE_MAP() public: CListCtrl m_list; //列表控件 IDC_LIST CTreeCtrl m_tree; //树形控件 IDC_TREE CImageList m_ImageList; //图像列表(相同大小图像集合) HTREEITEM m_hRoot; //句柄 CTreeCtrl的根结点"我的电脑" protected: CString m_strPath = _T("C:\\Users\\Yang\\Downloads\\TreeShow\\TreeShow"); public: void GetLogicalDrives(HTREEITEM hParent); //获取驱动 void GetDriveDir(HTREEITEM hParent); //获取子项 afx_msg void OnItemexpandedTree(NMHDR* pNMHDR, LRESULT* pResult); void AddSubDir(HTREEITEM hParent); //添加子目录 CString GetFullPath(HTREEITEM hCurrent); //获取树项目全根路径 afx_msg void OnSelchangedTree(NMHDR* pNMHDR, LRESULT* pResult); void ShowFile(HTREEITEM tree_Root, CString str_Dir); void FindDir(HTREEITEM pItem, const CString& dirPath); void FindFile(HTREEITEM pItem, const CString& filePath); BOOL DeleteDirectory(const CString& DirName); afx_msg void OnNMRClickTree_RCLICK(NMHDR* pNMHDR, LRESULT* pResult); }; <file_sep>// TreeShowDlg.cpp : 实现文件 // #include "stdafx.h" #include "TreeShow.h" #include "TreeShowDlg.h" #include "afxdialogex.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // 用于应用程序“关于”菜单项的 CAboutDlg 对话框 class CAboutDlg : public CDialogEx { public: CAboutDlg(); // 对话框数据 enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 // 实现 protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() // CTreeShowDlg 对话框 CTreeShowDlg::CTreeShowDlg(CWnd* pParent /*=NULL*/) : CDialogEx(CTreeShowDlg::IDD, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } CTreeShowDlg::~CTreeShowDlg() { } void CTreeShowDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Control(pDX, IDC_LIST, m_list); DDX_Control(pDX, IDC_TREE, m_tree); } BEGIN_MESSAGE_MAP(CTreeShowDlg, CDialogEx) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_NOTIFY(TVN_ITEMEXPANDED, IDC_TREE, &CTreeShowDlg::OnItemexpandedTree) ON_NOTIFY(TVN_SELCHANGED, IDC_TREE, &CTreeShowDlg::OnSelchangedTree) ON_NOTIFY(NM_RCLICK, IDC_TREE, &CTreeShowDlg::OnNMRClickTree_RCLICK) END_MESSAGE_MAP() // CTreeShowDlg 消息处理程序 BOOL CTreeShowDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // 将“关于...”菜单项添加到系统菜单中。 // IDM_ABOUTBOX 必须在系统命令范围内。 ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if(pSysMenu != NULL) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if(!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // 设置此对话框的图标。当应用程序主窗口不是对话框时,框架将自动 // 执行此操作 SetIcon(m_hIcon, TRUE); // 设置大图标 SetIcon(m_hIcon, FALSE); // 设置小图标 // TODO: 在此添加额外的初始化代码 m_ImageList.Create(32, 32, ILC_COLOR32, 10, 30); //创建图像序列CImageList对象 HICON hIcon = theApp.LoadIcon(IDI_ICON1); //图标句柄 m_ImageList.Add(hIcon); //图标添加到图像序列 m_list.SetImageList(&m_ImageList, LVSIL_NORMAL); //为树形控件设置图像序列 m_tree.ModifyStyle(NULL, TVS_HASBUTTONS | TVS_HASLINES | TVS_LINESATROOT | TVS_EDITLABELS); //m_hRoot = m_tree.InsertItem("TreeShow"); //插入根节点 //GetLogicalDrives(m_hRoot); //自定义函数 获取驱动 //GetDriveDir(m_hRoot); //自定义函数 获取驱动子项 FindDir(nullptr, m_strPath); //m_tree.Expand(m_hRoot, TVE_EXPAND); //展开或折叠子项列表 TVE_EXPAND展开列表 return TRUE; // 除非将焦点设置到控件,否则返回 TRUE } void CTreeShowDlg::OnSysCommand(UINT nID, LPARAM lParam) { if((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialogEx::OnSysCommand(nID, lParam); } } // 如果向对话框添加最小化按钮,则需要下面的代码 // 来绘制该图标。对于使用文档/视图模型的 MFC 应用程序, // 这将由框架自动完成。 void CTreeShowDlg::OnPaint() { if(IsIconic()) { CPaintDC dc(this); // 用于绘制的设备上下文 SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // 使图标在工作区矩形中居中 int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // 绘制图标 dc.DrawIcon(x, y, m_hIcon); } else { CDialogEx::OnPaint(); } } //当用户拖动最小化窗口时系统调用此函数取得光标 //显示。 HCURSOR CTreeShowDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } //******************************************************* //添加自定义函数 //函数功能:获取驱动器 参数:路径名 void CTreeShowDlg::GetLogicalDrives(HTREEITEM hParent) { //获取系统分区驱动器字符串信息 size_t szAllDriveStrings = GetLogicalDriveStrings(0, NULL); //驱动器总长度 //char* pDriveStrings = new char[szAllDriveStrings + sizeof(_T(""))]; //建立数组 char data[240]; char* pDriveStrings = data; GetLogicalDriveStrings(szAllDriveStrings, pDriveStrings); size_t szDriveString = strlen(pDriveStrings); //驱动大小 while(szDriveString > 0) { m_tree.InsertItem(pDriveStrings, hParent); //在父节点hParent添加盘符 pDriveStrings += szDriveString + 1; //pDriveStrings即C:\ D:\ E:\盘 szDriveString = strlen(pDriveStrings); } } //函数功能:获取驱动盘符下所有子项文件夹 void CTreeShowDlg::GetDriveDir(HTREEITEM hParent) { HTREEITEM hChild = m_tree.GetChildItem(hParent); //获取指定位置中的子项 while(hChild) { CString strText = m_tree.GetItemText(hChild); //检索列表中项目文字 if(strText.Right(1) != "\\") //从右边1开始获取从右向左nCount个字符 strText += _T("\\"); strText += "*.*"; //将当前目录下文件枚举并InsertItem树状显示 CFileFind file; //定义本地文件查找 BOOL bContinue = file.FindFile(strText); //查找包含字符串的文件 while(bContinue) { bContinue = file.FindNextFile(); //查找下一个文件 if(file.IsDirectory() && !file.IsDots()) //找到文件为内容且不为点"." m_tree.InsertItem(file.GetFileName(), hChild); //添加盘符路径下树状文件夹 } GetDriveDir(hChild); //递归调用 hChild = m_tree.GetNextItem(hChild, TVGN_NEXT); //获取树形控件(TVGN_NEXT)下一兄弟项 } } //函数功能:展开事件函数 void CTreeShowDlg::OnItemexpandedTree(NMHDR* pNMHDR, LRESULT* pResult) { LPNMTREEVIEW pNMTreeView = reinterpret_cast<LPNMTREEVIEW>(pNMHDR); // TODO: 在此添加控件通知处理程序代码 TVITEM item = pNMTreeView->itemNew; //发送\接受关于树形视图项目信息 if(item.hItem == m_hRoot) return; HTREEITEM hChild = m_tree.GetChildItem(item.hItem); //获取指定位置中的子项 while(hChild) { AddSubDir(hChild); //添加子目录 hChild = m_tree.GetNextItem(hChild, TVGN_NEXT); //获取树形控件TVGN_NEXT下兄弟项 } *pResult = 0; } //函数功能:添加子目录 void CTreeShowDlg::AddSubDir(HTREEITEM hParent) { CString strPath = GetFullPath(hParent); //获取全路径 if(strPath.Right(1) != "\\") strPath += "\\"; strPath += "*.*"; CFileFind file; BOOL bContinue = file.FindFile(strPath); //查找包含字符串的文件 while(bContinue) { bContinue = file.FindNextFile(); //查找下一个文件 if(file.IsDirectory() && !file.IsDots()) m_tree.InsertItem(file.GetFileName(), hParent); } } //函数功能:获取树项目全根路径 CString CTreeShowDlg::GetFullPath(HTREEITEM hCurrent) { CString strTemp; CString strReturn = ""; while(hCurrent != m_hRoot) { strTemp = m_tree.GetItemText(hCurrent); //检索列表中项目文字 if(strTemp.Right(1) != "\\") strTemp += "\\"; strReturn = strTemp + strReturn; hCurrent = m_tree.GetParentItem(hCurrent); //返回父项目句柄 } return /*m_strPath + _T("\\") + */strReturn; } //函数功能:选中事件显示图标 void CTreeShowDlg::OnSelchangedTree(NMHDR* pNMHDR, LRESULT* pResult) { //LPNMTREEVIEW pNMTreeView = reinterpret_cast<LPNMTREEVIEW>(pNMHDR); // TODO: 在此添加控件通知处理程序代码 m_list.DeleteAllItems(); NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR; TVITEM item = pNMTreeView->itemNew; if(item.hItem == m_hRoot) return; CString str = GetFullPath(item.hItem); if(str.Right(1) != "\\") str += "\\"; str += "*.*"; CFileFind file; BOOL bContinue = file.FindFile(str); while(bContinue) { bContinue = file.FindNextFile(); if(!file.IsDirectory() && !file.IsDots()) { SHFILEINFO info; CString temp = str; int index = temp.Find("*.*"); temp.Delete(index, 3); SHGetFileInfo(temp + file.GetFileName(), 0, &info, sizeof(&info), SHGFI_DISPLAYNAME | SHGFI_ICON); int i = m_ImageList.Add(info.hIcon); m_list.InsertItem(i, info.szDisplayName, i); } } *pResult = 0; } void CTreeShowDlg::ShowFile(HTREEITEM tree_Root, CString str_Dir) { CFileFind FileFind; //临时变量,用以记录返回的树节点 HTREEITEM tree_Temp; //判断输入目录最后是否存在'\',不存在则补充 if(str_Dir.Right(1) != "\\") str_Dir += "\\"; str_Dir += "*.*"; BOOL res = FileFind.FindFile(str_Dir); while(res) { tree_Temp = tree_Root; res = FileFind.FindNextFile(); if(FileFind.IsDirectory() && !FileFind.IsDots())//目录是文件夹 { CString strPath = FileFind.GetFilePath(); //得到路径,做为递归调用的开始 CString strTitle = FileFind.GetFileName();//得到目录名,做为树控的结点 tree_Temp = m_tree.InsertItem(strTitle, 0, 0, tree_Root); ShowFile(tree_Temp, strPath); } else if(!FileFind.IsDirectory() && !FileFind.IsDots())//如果是文件 { CString strPath = FileFind.GetFilePath(); //得到路径,做为递归调用的开始 CString strTitle = FileFind.GetFileName();//得到文件名,做为树控的结点 m_tree.InsertItem(strTitle, 0, 0, tree_Temp); } } FileFind.Close(); } void CTreeShowDlg::FindDir(HTREEITEM pItem, const CString& dirPath)//HTREEITEM 为一个CtreeCtel节点,此处实现将文件夹映射到CtreeCtrl控件中去 { CFileFind tempFind; BOOL bFound = tempFind.FindFile(dirPath + "\\*.*"); HTREEITEM pItem2; if(pItem == NULL) { pItem2 = m_tree.InsertItem(dirPath, 0, 1, TVI_ROOT, TVI_LAST);//插入根节点 } else { pItem2 = m_tree.InsertItem(dirPath.Right(dirPath.GetLength() - dirPath.ReverseFind('\\') - 1), 0, 1, pItem, TVI_LAST);//插入子节点 } while(bFound) { bFound = tempFind.FindNextFile(); if(tempFind.IsDots()) continue; tempFind.IsDirectory() ? FindDir(pItem2, tempFind.GetFilePath()) : //找到的是文件夹 FindFile(pItem2, tempFind.GetFileName()); //找到的是文件 } tempFind.Close(); } void CTreeShowDlg::FindFile(HTREEITEM pItem, const CString& filePath) { m_tree.InsertItem(filePath, 0, 1, pItem, TVI_LAST); //插入子节点 } BOOL CTreeShowDlg::DeleteDirectory(const CString& DirName) { CFileFind tempFind; BOOL IsFinded = tempFind.FindFile(DirName + "\\*.*"); while(IsFinded) { IsFinded = tempFind.FindNextFile(); if(tempFind.IsDots()) continue; if(tempFind.IsDirectory()) { DeleteDirectory(tempFind.GetFilePath()); } else { DeleteFile(tempFind.GetFilePath()); } } tempFind.Close(); if(!RemoveDirectory(DirName)) { MessageBox(_T("删除目录失败!"), _T("警告信息"), MB_OK); return FALSE; } return TRUE; } void CTreeShowDlg::OnNMRClickTree_RCLICK(NMHDR* pNMHDR, LRESULT* pResult) { CPoint point; GetCursorPos(&point); //获取鼠标坐标 m_tree.ScreenToClient(&point);//映射到CtreeCtrl中 UINT nFlags; HTREEITEM hItems = m_tree.HitTest(point, &nFlags);//根据坐标获取节点 CString m_treeChangeFile = m_tree.GetItemText(hItems); hItems = m_tree.GetParentItem(hItems); while(hItems) //循环获取父节点,获取节点全路径 { m_treeChangeFile = m_tree.GetItemText(hItems) + L"\\" + m_treeChangeFile; hItems = m_tree.GetParentItem(hItems); } // 菜单显示 CMenu menu; menu.LoadMenu(IDR_MENU_TREE); CMenu* pPopup = menu.GetSubMenu(0); POINT pt; ::GetCursorPos((LPPOINT)&pt); pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, pt.x, pt.y, this); *pResult = 0; }
a9ac3fbc84cc9053b91862820ecfdd75d6952285
[ "C++" ]
2
C++
halforc/TreeShow
6b95f5525ff04bd27efd5a04321cbe600aa789fa
0c8bf0ab99979ffa179c379d57935b297aa4346c
refs/heads/master
<repo_name>daschne8/your-own-js-and-css-in-rails-online-web-ft-031119<file_sep>/app/assets/javascripts/hide.js function hideWhenClicked(element){ $(element.target).hide() } $('#hide_this').click(hideWhenClicked);
050fd797146782192274fbc330d723d6df906b5e
[ "JavaScript" ]
1
JavaScript
daschne8/your-own-js-and-css-in-rails-online-web-ft-031119
83bbd11e61a5af41663b495721913072569c0d95
dd75913c6bb4ebbda7a5db05c0706a0c6c16957e
refs/heads/main
<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Description; using WebApiCAR.Models; namespace WebApiCAR.Controllers { public class EvaluacionesController : ApiController { private DbCoopeAlfaroRuizEntities db = new DbCoopeAlfaroRuizEntities(); // GET: api/Evaluaciones public IQueryable<Evaluaciones> GetEvaluaciones() { return db.Evaluaciones; } // GET: api/Evaluaciones/5 [ResponseType(typeof(Evaluaciones))] public IHttpActionResult GetEvaluaciones(int id) { Evaluaciones evaluaciones = db.Evaluaciones.Find(id); if (evaluaciones == null) { return NotFound(); } return Ok(evaluaciones); } // PUT: api/Evaluaciones/5 [ResponseType(typeof(void))] public IHttpActionResult PutEvaluaciones(int id, Evaluaciones evaluaciones) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != evaluaciones.IdEvaluacion) { return BadRequest(); } db.Entry(evaluaciones).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!EvaluacionesExists(id)) { return NotFound(); } else { throw; } } return StatusCode(HttpStatusCode.NoContent); } // POST: api/Evaluaciones [ResponseType(typeof(Evaluaciones))] public IHttpActionResult PostEvaluaciones(Evaluaciones evaluaciones) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.Evaluaciones.Add(evaluaciones); db.SaveChanges(); return CreatedAtRoute("DefaultApi", new { id = evaluaciones.IdEvaluacion }, evaluaciones); } // DELETE: api/Evaluaciones/5 [ResponseType(typeof(Evaluaciones))] public IHttpActionResult DeleteEvaluaciones(int id) { Evaluaciones evaluaciones = db.Evaluaciones.Find(id); if (evaluaciones == null) { return NotFound(); } db.Evaluaciones.Remove(evaluaciones); db.SaveChanges(); return Ok(evaluaciones); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } private bool EvaluacionesExists(int id) { return db.Evaluaciones.Count(e => e.IdEvaluacion == id) > 0; } } }<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Description; using WebApiCAR.Models; namespace WebApiCAR.Controllers { public class CursosMatriculadosController : ApiController { private DbCoopeAlfaroRuizEntities db = new DbCoopeAlfaroRuizEntities(); // GET: api/CursosMatriculados public IQueryable<CursosMatriculados> GetCursosMatriculados() { return db.CursosMatriculados; } // GET: api/CursosMatriculados/5 [ResponseType(typeof(CursosMatriculados))] public IHttpActionResult GetCursosMatriculados(int id) { CursosMatriculados cursosMatriculados = db.CursosMatriculados.Find(id); if (cursosMatriculados == null) { return NotFound(); } return Ok(cursosMatriculados); } // PUT: api/CursosMatriculados/5 [ResponseType(typeof(void))] public IHttpActionResult PutCursosMatriculados(int id, CursosMatriculados cursosMatriculados) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != cursosMatriculados.IdCursoMatriculado) { return BadRequest(); } db.Entry(cursosMatriculados).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!CursosMatriculadosExists(id)) { return NotFound(); } else { throw; } } return StatusCode(HttpStatusCode.NoContent); } // POST: api/CursosMatriculados [ResponseType(typeof(CursosMatriculados))] public IHttpActionResult PostCursosMatriculados(CursosMatriculados cursosMatriculados) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.CursosMatriculados.Add(cursosMatriculados); db.SaveChanges(); return CreatedAtRoute("DefaultApi", new { id = cursosMatriculados.IdCursoMatriculado }, cursosMatriculados); } // DELETE: api/CursosMatriculados/5 [ResponseType(typeof(CursosMatriculados))] public IHttpActionResult DeleteCursosMatriculados(int id) { CursosMatriculados cursosMatriculados = db.CursosMatriculados.Find(id); if (cursosMatriculados == null) { return NotFound(); } db.CursosMatriculados.Remove(cursosMatriculados); db.SaveChanges(); return Ok(cursosMatriculados); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } private bool CursosMatriculadosExists(int id) { return db.CursosMatriculados.Count(e => e.IdCursoMatriculado == id) > 0; } } }<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Description; using WebApiCAR.Models; namespace WebApiCAR.Controllers { public class RegistroController : ApiController { private DbCoopeAlfaroRuizEntities db = new DbCoopeAlfaroRuizEntities(); // GET: api/Registro public IQueryable<Registro> GetRegistro() { return db.Registro; } // GET: api/Registro/5 [ResponseType(typeof(Registro))] public IHttpActionResult GetRegistro(int id) { Registro registro = db.Registro.Find(id); if (registro == null) { return NotFound(); } return Ok(registro); } // PUT: api/Registro/5 [ResponseType(typeof(void))] public IHttpActionResult PutRegistro(int id, Registro registro) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != registro.IdRegistro) { return BadRequest(); } db.Entry(registro).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!RegistroExists(id)) { return NotFound(); } else { throw; } } return StatusCode(HttpStatusCode.NoContent); } // POST: api/Registro [ResponseType(typeof(Registro))] public IHttpActionResult PostRegistro(Registro registro) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.Registro.Add(registro); db.SaveChanges(); return CreatedAtRoute("DefaultApi", new { id = registro.IdRegistro }, registro); } // DELETE: api/Registro/5 [ResponseType(typeof(Registro))] public IHttpActionResult DeleteRegistro(int id) { Registro registro = db.Registro.Find(id); if (registro == null) { return NotFound(); } db.Registro.Remove(registro); db.SaveChanges(); return Ok(registro); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } private bool RegistroExists(int id) { return db.Registro.Count(e => e.IdRegistro == id) > 0; } } }<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Description; using WebApiCAR.Models; namespace WebApiCAR.Controllers { public class LeccionesController : ApiController { private DbCoopeAlfaroRuizEntities db = new DbCoopeAlfaroRuizEntities(); // GET: api/Lecciones public IQueryable<Lecciones> GetLecciones() { return db.Lecciones; } // GET: api/Lecciones/5 [ResponseType(typeof(Lecciones))] public IHttpActionResult GetLecciones(int id) { Lecciones lecciones = db.Lecciones.Find(id); if (lecciones == null) { return NotFound(); } return Ok(lecciones); } // PUT: api/Lecciones/5 [ResponseType(typeof(void))] public IHttpActionResult PutLecciones(int id, Lecciones lecciones) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != lecciones.IdLeccion) { return BadRequest(); } db.Entry(lecciones).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!LeccionesExists(id)) { return NotFound(); } else { throw; } } return StatusCode(HttpStatusCode.NoContent); } // POST: api/Lecciones [ResponseType(typeof(Lecciones))] public IHttpActionResult PostLecciones(Lecciones lecciones) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.Lecciones.Add(lecciones); db.SaveChanges(); return CreatedAtRoute("DefaultApi", new { id = lecciones.IdLeccion }, lecciones); } // DELETE: api/Lecciones/5 [ResponseType(typeof(Lecciones))] public IHttpActionResult DeleteLecciones(int id) { Lecciones lecciones = db.Lecciones.Find(id); if (lecciones == null) { return NotFound(); } db.Lecciones.Remove(lecciones); db.SaveChanges(); return Ok(lecciones); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } private bool LeccionesExists(int id) { return db.Lecciones.Count(e => e.IdLeccion == id) > 0; } } }<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Description; using WebApiCAR.Models; namespace WebApiCAR.Controllers { public class CursosController : ApiController { private DbCoopeAlfaroRuizEntities db = new DbCoopeAlfaroRuizEntities(); // GET: api/Cursos public IQueryable<Cursos> GetCursos() { return db.Cursos; } // GET: api/Cursos/5 [ResponseType(typeof(Cursos))] public IHttpActionResult GetCursos(int id) { Cursos cursos = db.Cursos.Find(id); if (cursos == null) { return NotFound(); } return Ok(cursos); } // PUT: api/Cursos/5 [ResponseType(typeof(void))] public IHttpActionResult PutCursos(int id, Cursos cursos) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != cursos.IdCurso) { return BadRequest(); } db.Entry(cursos).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!CursosExists(id)) { return NotFound(); } else { throw; } } return StatusCode(HttpStatusCode.NoContent); } // POST: api/Cursos [ResponseType(typeof(Cursos))] public IHttpActionResult PostCursos(Cursos cursos) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.Cursos.Add(cursos); db.SaveChanges(); return CreatedAtRoute("DefaultApi", new { id = cursos.IdCurso }, cursos); } // DELETE: api/Cursos/5 [ResponseType(typeof(Cursos))] public IHttpActionResult DeleteCursos(int id) { Cursos cursos = db.Cursos.Find(id); if (cursos == null) { return NotFound(); } db.Cursos.Remove(cursos); db.SaveChanges(); return Ok(cursos); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } private bool CursosExists(int id) { return db.Cursos.Count(e => e.IdCurso == id) > 0; } } }<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Description; using WebApiCAR.Models; namespace WebApiCAR.Controllers { public class AsigCursoRolController : ApiController { private DbCoopeAlfaroRuizEntities db = new DbCoopeAlfaroRuizEntities(); // GET: api/AsigCursoRol public IQueryable<AsigCursoRol> GetAsigCursoRol() { return db.AsigCursoRol; } // GET: api/AsigCursoRol/5 [ResponseType(typeof(AsigCursoRol))] public IHttpActionResult GetAsigCursoRol(int id) { AsigCursoRol asigCursoRol = db.AsigCursoRol.Find(id); if (asigCursoRol == null) { return NotFound(); } return Ok(asigCursoRol); } // PUT: api/AsigCursoRol/5 [ResponseType(typeof(void))] public IHttpActionResult PutAsigCursoRol(int id, AsigCursoRol asigCursoRol) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != asigCursoRol.IdAsignacion) { return BadRequest(); } db.Entry(asigCursoRol).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!AsigCursoRolExists(id)) { return NotFound(); } else { throw; } } return StatusCode(HttpStatusCode.NoContent); } // POST: api/AsigCursoRol [ResponseType(typeof(AsigCursoRol))] public IHttpActionResult PostAsigCursoRol(AsigCursoRol asigCursoRol) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.AsigCursoRol.Add(asigCursoRol); db.SaveChanges(); return CreatedAtRoute("DefaultApi", new { id = asigCursoRol.IdAsignacion }, asigCursoRol); } // DELETE: api/AsigCursoRol/5 [ResponseType(typeof(AsigCursoRol))] public IHttpActionResult DeleteAsigCursoRol(int id) { AsigCursoRol asigCursoRol = db.AsigCursoRol.Find(id); if (asigCursoRol == null) { return NotFound(); } db.AsigCursoRol.Remove(asigCursoRol); db.SaveChanges(); return Ok(asigCursoRol); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } private bool AsigCursoRolExists(int id) { return db.AsigCursoRol.Count(e => e.IdAsignacion == id) > 0; } } }<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Description; using WebApiCAR.Models; namespace WebApiCAR.Controllers { public class DetalleEvaluacionController : ApiController { private DbCoopeAlfaroRuizEntities db = new DbCoopeAlfaroRuizEntities(); // GET: api/DetalleEvaluacion public IQueryable<DetalleEvaluacion> GetDetalleEvaluacion() { return db.DetalleEvaluacion; } // GET: api/DetalleEvaluacion/5 [ResponseType(typeof(DetalleEvaluacion))] public IHttpActionResult GetDetalleEvaluacion(int id) { DetalleEvaluacion detalleEvaluacion = db.DetalleEvaluacion.Find(id); if (detalleEvaluacion == null) { return NotFound(); } return Ok(detalleEvaluacion); } // PUT: api/DetalleEvaluacion/5 [ResponseType(typeof(void))] public IHttpActionResult PutDetalleEvaluacion(int id, DetalleEvaluacion detalleEvaluacion) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != detalleEvaluacion.IdDetalle) { return BadRequest(); } db.Entry(detalleEvaluacion).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!DetalleEvaluacionExists(id)) { return NotFound(); } else { throw; } } return StatusCode(HttpStatusCode.NoContent); } // POST: api/DetalleEvaluacion [ResponseType(typeof(DetalleEvaluacion))] public IHttpActionResult PostDetalleEvaluacion(DetalleEvaluacion detalleEvaluacion) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.DetalleEvaluacion.Add(detalleEvaluacion); db.SaveChanges(); return CreatedAtRoute("DefaultApi", new { id = detalleEvaluacion.IdDetalle }, detalleEvaluacion); } // DELETE: api/DetalleEvaluacion/5 [ResponseType(typeof(DetalleEvaluacion))] public IHttpActionResult DeleteDetalleEvaluacion(int id) { DetalleEvaluacion detalleEvaluacion = db.DetalleEvaluacion.Find(id); if (detalleEvaluacion == null) { return NotFound(); } db.DetalleEvaluacion.Remove(detalleEvaluacion); db.SaveChanges(); return Ok(detalleEvaluacion); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } private bool DetalleEvaluacionExists(int id) { return db.DetalleEvaluacion.Count(e => e.IdDetalle == id) > 0; } } }<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Description; using WebApiCAR.Models; namespace WebApiCAR.Controllers { public class ModulosController : ApiController { private DbCoopeAlfaroRuizEntities db = new DbCoopeAlfaroRuizEntities(); // GET: api/Modulos public IQueryable<Modulos> GetModulos() { return db.Modulos; } // GET: api/Modulos/5 [ResponseType(typeof(Modulos))] public IHttpActionResult GetModulos(int id) { Modulos modulos = db.Modulos.Find(id); if (modulos == null) { return NotFound(); } return Ok(modulos); } // PUT: api/Modulos/5 [ResponseType(typeof(void))] public IHttpActionResult PutModulos(int id, Modulos modulos) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != modulos.IdModulo) { return BadRequest(); } db.Entry(modulos).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!ModulosExists(id)) { return NotFound(); } else { throw; } } return StatusCode(HttpStatusCode.NoContent); } // POST: api/Modulos [ResponseType(typeof(Modulos))] public IHttpActionResult PostModulos(Modulos modulos) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.Modulos.Add(modulos); db.SaveChanges(); return CreatedAtRoute("DefaultApi", new { id = modulos.IdModulo }, modulos); } // DELETE: api/Modulos/5 [ResponseType(typeof(Modulos))] public IHttpActionResult DeleteModulos(int id) { Modulos modulos = db.Modulos.Find(id); if (modulos == null) { return NotFound(); } db.Modulos.Remove(modulos); db.SaveChanges(); return Ok(modulos); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } private bool ModulosExists(int id) { return db.Modulos.Count(e => e.IdModulo == id) > 0; } } }
81a983a2add341d02c8848f8c0a42a2378c3f8cb
[ "C#" ]
8
C#
jimmy14cr/WebApiCAR
760ade15b04488a64d7f04b3cf9cc0335c492806
42b3933d6e652680c3b6b56666022285b615a627
refs/heads/master
<repo_name>zarq/galgje<file_sep>/galgje_gamemaster.py import re from galgje_utils import debug import random as random_ choice = random_.Random().choice del random_ debug("Woorden inlezen...") all_words = [] with open('dutch', 'r') as f: for line in f: word = line.strip().lower() all_words.append(word) def update_template(template, word, letter): res = '' for tc, wc in zip(template, word): if wc == letter: res += wc else: res += tc return res class GalgjeState(object): def __init__(self): self.word = None self.template = None class GalgjeError(Exception): pass def galgje(word=None): if word is None: word = choice(all_words) template = re.sub('[a-z]', '_', word) print("Galgjewoord: %r" % (template,)) state = GalgjeState() state.word = word state.template = template state.fouten = 0 return state, template def galgje_guess(state, letter): goede_letter = False geraden = False if len(letter) > 1: # woord raden if letter == state.word: print("Geraden! Het was %r" % (state.word,)) goede_letter = True geraden = True else: state.fouten += 1 if state.fouten > 5: print("Helaas. Het woord was %r" % (state.word,)) raise GalgjeError() return geraden, goede_letter, state.template template = state.template if letter in state.word: template = update_template(state.template, state.word, letter) state.template = template goede_letter = True else: state.fouten += 1 if state.fouten > 5: print("Helaas. Het woord was %r" % (state.word,)) raise GalgjeError() if template == state.word: print("Geraden! Het was %r" % (state.word,)) geraden = True return geraden, goede_letter, template <file_sep>/galgjeircclient.py import sys import socket import select import queue import os import time import imp import traceback from galgje_utils import debug CONNECTED, NICK_SENT, JOINING, JOINED = range(4) class IrcClient(object): HOST='irc.fruit.je' PORT=6667 NICK='ivobot' IDENT='ivobot' REALNAME='ivobot' CHANNEL = "#ivo" def __init__(self): self.send_queue = queue.Queue() self.readbuffer = bytearray() self.writebuffer = bytearray() self._module_timestamp = time.time() self._module = __import__('galgjeirccommands') self.module_filename = self._module.__file__ self.init_module_handler() def connect(self): self.s = socket.socket() self.s.connect((self.HOST, self.PORT)) self.s.setblocking(False) self.state = CONNECTED self.go() def sendstring(self, string): debug(string, end='') self.send_queue.put(string.encode('utf-8')) def parse_line(self, line, n=3): parts = [] while n > 0: if ' ' in line and n > 1: part, line = line.split(' ', 1) n -= 1 parts.append(part) else: parts.append(line) n -= 1 break if n > 0: parts += [None] * n return parts def dispatch_line(self, line): debug(line) if line.startswith('PING'): self.sendstring("PONG %s\r\n" % line[5:]) if self.state == CONNECTED: self.sendstring("NICK %s\r\n" % (self.NICK,)) self.sendstring("USER %s %s bla :%s\r\n" % (self.IDENT, self.HOST, self.REALNAME)) self.state = NICK_SENT elif self.state == NICK_SENT: if line.startswith(':'): server, code, args = self.parse_line(line) if code == '001': self.sendstring("JOIN %s\r\n" % (self.CHANNEL,)) self.state = JOINING elif self.state == JOINING: if line.startswith(':'): source, cmd, args = self.parse_line(line) if cmd == 'JOIN': assert args[1:] == self.CHANNEL self.state = JOINED elif self.state == JOINED: if line.startswith(':'): source, cmd, dest, args = self.parse_line(line, 4) self.module.handle(source, cmd, dest, args) if line.startswith('ERROR'): sys.exit(0) # if line[0] == 'PING': # sendstring("PONG %s\r\n" % (line[1],)) # if line[0].startswith(':'): # # sendstring("JOIN #galgje\r\n") def check_updated_module(self): statinfo = os.stat(self.module_filename) if statinfo.st_mtime > self._module_timestamp: debug("%s has changed, reloading" % (self.module_filename,)) try: imp.reload(self._module) except: traceback.print_exc() return self.init_module_handler() self._module_timestamp = statinfo.st_mtime def init_module_handler(self): self.module = self._module.Module() self.module.sendstring = self.sendstring def go(self): while True: if not self.send_queue.empty() or self.writebuffer: w = [self.s] else: w = [] r, w, e = select.select([self.s], w, [self.s], 1) if self.s in r: self.readbuffer += self.s.recv(1024) while True: idx = self.readbuffer.find(b'\n') if idx == -1: break line = self.readbuffer[:idx].decode('utf-8') if len(line) > 0 and line[-1] == '\r': line = line[:-1] # strip CR self.readbuffer = self.readbuffer[idx + 1:] self.dispatch_line(line) if self.s in w: if not self.send_queue.empty(): item = self.send_queue.get_nowait() if item: self.writebuffer += item if self.writebuffer: n = self.s.send(self.writebuffer) if n: self.writebuffer = self.writebuffer[n:] if self.s in e: return self.check_updated_module() client = IrcClient() client.connect() <file_sep>/galgjehelp.py from galgje import * template = input("Plak het template: ") succes, woord = gogogalgje(raadfn_terminal, template) if succes: print("Het woord is: %r" % (woord,)) print("Succes: %r; pogingen: %r" % (succes, pogingen)) <file_sep>/galgje_utils.py def debug(s, end='\n'): if type(s) != str and type(s) != bytes: s = repr(s) if type(s) == bytes: s = s.decode('utf-8') print(s, end=end) <file_sep>/autogalgje.py import sys from galgje import gogogalgje, pogingen from galgje_gamemaster import galgje as galgje_master from galgje_gamemaster import galgje_guess if len(sys.argv) > 1: word = sys.argv[1] else: word = None state, template = galgje_master(word) def raadfn(letter, template): geraden, goede_letter, template = galgje_guess(state, letter) return goede_letter, template try: gogogalgje(raadfn, template) finally: print("Pogingen: %r, %d fouten" % (pogingen, state.fouten)) <file_sep>/galgjeirccommands.py import traceback import re import imp import time from galgje_utils import debug import galgje class Recipient(object): def __init__(self, channel, nick): self.channel = channel self.nick = nick class Module(object): def __init__(self): self.quiet = False self.auto_galgje = False def parse_f00f(self, sender, s): assert(s.startswith(':')) s = s[1:] if s.startswith('Galgjewoord:'): # debug(s) pattern = b'^.*\xe2\x80\x98(?P<template>.*)\xe2\x80\x99( \((?P<letters>.*)\))?\.'.decode('utf-8') # debug(pattern) match = re.match(pattern, s) if match: # debug(match.group('template')) template = match.group('template') letters = match.group('letters') verboden = '' if letters: verboden = letters self.galgje_guess(sender, template, set(verboden)) elif s.startswith('Het woord was'): if self.auto_galgje: self.say_publicly(sender, "!galgje") def parse_invite(self, recipient, args): assert(args.startswith(':')) channel = args[1:] self.sendstring("JOIN %s\r\n" % (channel,)) def galgje_guess(self, sender, template, verboden=set()): # imp.reload(galgje) poging = galgje.galgje_reentrant(template, verboden) # debug(poging) self.respond_publicly(sender, "!raad %s" % (poging,)) def parse_command(self, sender, s): # debug("command: %r" % (s,)) if s.startswith(':`'): if ' ' in s: command, args = s[2:].split(' ', 1) else: command = s[2:] args = () debug("command = %r" % (command,)) self.dispatch_command(sender, command, args) def say_publicly(self, recipient, message): self.sendstring("PRIVMSG %s :%s\r\n" % (recipient.channel, message)) def respond_publicly(self, recipient, message): self.sendstring("PRIVMSG %s :%s: %s\r\n" % (recipient.channel, recipient.nick, message)) def dispatch_command(self, sender, command, args): methodname = 'handle_command_' + command if hasattr(self, methodname): getattr(self, methodname)(args) else: self.respond_publicly(sender, "No such command %r" % (command,)) def parse_recipient(self, source, dest): # debug(source) # debug(dest) assert(source.startswith(':')) source = source[1:] if '!' in source: source = source[:source.find('!')] recipient = Recipient(dest, source) return recipient def handle(self, source, cmd, dest, args): # debug("source=%r; cmd=%r; args=%r" % (source, cmd, args)) start = time.time() recipient = self.parse_recipient(source, dest) try: if cmd == 'PRIVMSG': if recipient.nick == 'zarq': # yay admin # debug("YAY ADMIN") self.parse_command(recipient, args) elif recipient.nick == 'f00f': self.parse_f00f(recipient, args) elif cmd == 'INVITE': if recipient.nick == 'zarq': self.parse_invite(recipient, args) except Exception as ex: traceback.print_exc() recipient = Recipient('#ivo', 'zarq') self.respond_publicly(recipient, "HALP %r" % (ex,)) debug("Handled in %.3fs" % (time.time() - start,)) def handle_command_stil(self): self.quiet = True def handle_command_auto(self, args): self.auto_galgje = not self.auto_galgje def handle_command_join(self, args): self.sendstring("JOIN %s\r\n" % (args,)) def handle_command_leave(self, args): self.sendstring("PART %s\r\n" % (args,)) def handle_command_quit(self, args): self.sendstring("QUIT :Terminating\r\n") <file_sep>/parseprofile.py import pstats p = pstats.Stats('profile.out') p.sort_stats('cumulative').print_stats() <file_sep>/galgje.py from collections import defaultdict import atexit import re from math import log as ln from galgje_utils import debug pogingen = [] cache = {} debug("Woorden inlezen...") all_words = set() with open('dutch', 'r') as f: for line in f: word = line.strip().lower() all_words.add(word) debug("Cache inlezen...") with open("cache", 'r') as f: for line in f: line = line.strip() letter = line[0] state = line[1:] cache[state] = letter debug("Cache2 inlezen...") cache2 = defaultdict(dict) with open("cache2", 'r') as f: for line in f: line = line.strip() letter,forbidden,template = line.split('|') cache2[template][forbidden] = letter def save_cache2(): with open('cache2', 'w') as f: for template in cache2: for forbidden in cache2[template]: letter = cache2[template][forbidden] f.write("%s|%s|%s\n" % (letter, forbidden, template)) def add_to_cache2(letter, forbidden, template): with open('cache2', 'a') as f: f.write("%s|%s|%s\n" % (letter, forbidden, template)) def create_re_from_template(template, gerade_letters): if not gerade_letters: dot = '[a-z]' else: overgebleven_letters = set('abcdefghijklmnopqrstuvwxyz') overgebleven_letters -= gerade_letters dot = '[' + ''.join(overgebleven_letters) + ']' expr = '^' + template.replace('_', dot) + '$' # debug("REGEX=%r" % (expr,)) return re.compile(expr) def predict_outcome(template, word, letter): result = '' for tc, wletter in zip(template, word): if wletter == letter: tc = wletter result += tc return result class CountingSet(): def __init__(self): self._data = defaultdict(lambda: 0) def add(self, value): self._data[value] += 1 def sorted_(self): def g(): for k, v in self._data: yield v, k return sorted(g()) def template_union(template, possibility): result = '' for tc, pc in zip(template, possibility): if tc == pc: result += tc else: result += '_' #debug("template_union(%r, %r) = %r" % (template, possibility, result)) return result def gogogalgje(raad, template): alphabet = set('abcdefghijklmnopqrstuvwxyz') words = all_words letters_die_erin_zitten = set() letters_die_er_niet_in_zitten = set() succes = False while True: # Itereren vanaf hier match = create_re_from_template(template, letters_die_erin_zitten) # debug("Rekenen...") letters = defaultdict(set) possible_outcomes_unique = defaultdict(set) possible_outcomes_all = defaultdict(list) possible_outcomes_astrid = defaultdict(lambda: defaultdict(lambda: 0)) new_words = set() for word in words: add = True for letter in letters_die_er_niet_in_zitten: if letter in word: add = False break for letter in letters_die_erin_zitten: if letter not in word: add = False break if add: if match.match(word): new_words.add(word) words = new_words # debug("Letters: %s" % ("".join(letters_die_erin_zitten),)) # debug("Woorden: (%d) %s" % (len(words), ",".join(list(words)[:20]),)) if len(words) == 1: print("Het woord is: %s" % (list(words)[0],)) resultaat, new_template = raad(list(words)[0], template) assert resultaat == True succes = True return succes, list(words)[0] if len(words) == 0: print("Ik weet het niet!") succes = False return succes, None if template in cache and cache[template] in alphabet: # debug("In cache") top_letter = cache[template] else: # debug("Not in cache, analyzing...") for word in words: for letter in alphabet: if letter in word: letters[letter].add(word) outcome = predict_outcome(template, word, letter) possible_outcomes_unique[letter].add(outcome) possible_outcomes_all[letter].append(outcome) possible_outcomes_astrid[letter][outcome] += 1 # options_letters = [] # total_letters = len(words) # for letter in letters: # count = len(letters[letter]) # # total_letters += count # options_letters.append((count, letter)) # options_letters = list(sorted(options_letters)) # target_letters = total_letters / 2 # debug("Possible outcomes (letters): %r" % (letters,)) # debug("%d mogelijke uitkomsten, doel is %d (letters)" % (total_letters, target_letters)) # debug("Options (letters): %r" % (",".join([repr((letter, count)) for count, letter in options_letters]),)) # optoptions_letters = list() # for optioncount, optionletter in options_letters: # optoptions_letters.append((abs(optioncount - target_letters), optionletter)) # optoptions_letters = list(sorted(optoptions_letters)) # debug("Optimale options (letters): %r" % (",".join([repr((letter, dist)) for dist, letter in optoptions_letters]),)) # options_all = [] # total_all = 0 # for letter in possible_outcomes_all: # count = len(possible_outcomes_all[letter]) # total_all += count # options_all.append((count, letter)) # options_all = list(sorted(options_all)) # target_all = total_all / 2 # debug("Possible outcomes (all): %r" % (possible_outcomes_all,)) # debug("%d mogelijke uitkomsten, doel is %d (all)" % (total_all, target_all)) # debug("Options (all): %r" % (",".join([repr((letter, count)) for count, letter in options_all]),)) # optoptions_all = list() # for optioncount, optionletter in options_all: # optoptions_all.append((abs(optioncount - target_all), optionletter)) # optoptions_all = list(sorted(optoptions_all)) # debug("Optimale options (all): %r" % (",".join([repr((letter, dist)) for dist, letter in optoptions_all]),)) options_astrid = [] total_astrid = len(words) for letter in possible_outcomes_astrid: p_sum = 0.0 for option in possible_outcomes_astrid[letter]: p_positie = float(possible_outcomes_astrid[letter][option]) / total_astrid # debug("letter=%r, optie=%r, n=%d, p=%.3f" % ( # letter, option, possible_outcomes_astrid[letter][option], p_positie)) p_sum += p_positie * ln(p_positie) p_nergens = 1.0 - (float(sum(possible_outcomes_astrid[letter].values()))) / total_astrid if p_nergens == 0.0: value = 0.0 else: value = (p_sum + p_nergens * ln(p_nergens)) / p_nergens options_astrid.append((value, letter)) options_astrid = list(sorted(options_astrid)) # debug("Possible outcomes (astrid): %r" % (possible_outcomes_astrid,)) # debug("%d mogelijke uitkomsten, doel is -inf (astrid)" % (total_astrid,)) # debug("Options (astrid): %r" % (",".join([repr((letter, count)) for count, letter in options_astrid]),)) optoptions_astrid = list() for optioncount, optionletter in options_astrid: optoptions_astrid.append((abs(optioncount), optionletter)) optoptions_astrid = list(sorted(optoptions_astrid, reverse=True)) debug("Optimale options (astrid): %r" % (",".join([repr((letter, dist)) for dist, letter in optoptions_astrid]),)) # options_unique = [] # total_unique = 0 # for letter in possible_outcomes_unique: # count = len(possible_outcomes_unique[letter]) # total_unique += count # options_unique.append((count, letter)) # options_unique = list(sorted(options_unique)) # target_unique = total_unique / 2 # debug("Possible outcomes (unique): %r" % (possible_outcomes_unique,)) # debug("%d mogelijke uitkomsten, doel is %d (unique)" % (total_unique, target_unique)) # debug("Options (unique): %r" % (",".join([repr((letter, count)) for count, letter in options_unique]),)) # optoptions_unique = list() # for optioncount, optionletter in options_unique: # optoptions_unique.append((abs(optioncount - target_unique), optionletter)) # optoptions_unique = list(sorted(optoptions_unique)) # debug("Optimale options (unique): %r" % (",".join([repr((letter, dist)) for dist, letter in optoptions_unique]),)) top_letter = optoptions_astrid[0][1] pogingen.append(top_letter) words_met_letter = len(letters[top_letter]) # debug("Beste letter: %s (%d van %d, %.2f%%)" % ( # top_letter,words_met_letter, len(words), # 100.0 * float(len(letters[top_letter])) / len(words))) resultaat, new_template = raad(top_letter, template) if resultaat == True: # letter zat erin letters_die_erin_zitten.add(top_letter) if template not in cache: cache[template] = top_letter else: letters_die_er_niet_in_zitten.add(top_letter) template = new_template alphabet.remove(top_letter) def extract_letters(template): alphabet = 'abcdefghijklmnopqrstuvwxyz' letters = set() for letter in template: if letter in alphabet: letters.add(letter) return letters def extract_letters_str(template): alphabet = 'abcdefghijklmnopqrstuvwxyz' letters = '' for letter in template: if letter in alphabet: letters += letter return letters def galgje_reentrant(template, letters_die_er_niet_in_zitten): forbidden = ''.join(sorted(letters_die_er_niet_in_zitten)) if forbidden in cache2[template]: return cache2[template][forbidden] # Itereren vanaf hier letters_die_erin_zitten = extract_letters(template) match = create_re_from_template(template, letters_die_erin_zitten) # debug("Rekenen...") letters = defaultdict(set) possible_outcomes_unique = defaultdict(set) possible_outcomes_all = defaultdict(list) possible_outcomes_astrid = defaultdict(lambda: defaultdict(lambda: 0)) new_words = set() for word in all_words: if match.match(word): add = True for letter in letters_die_er_niet_in_zitten: if letter in word: add = False break for letter in letters_die_erin_zitten: if letter not in word: add = False break if add: new_words.add(word) words = new_words # debug("Letters: %s" % ("".join(letters_die_erin_zitten),)) # debug("Woorden: (%d) %s" % (len(words), ",".join(list(words)[:20]),)) if len(words) == 1: print("Het woord is: %s" % (list(words)[0],)) return list(words)[0] if len(words) == 0: print("Ik weet het niet!") return None alphabet = set('abcdefghijklmnopqrstuvwxyz') for i in letters_die_erin_zitten: alphabet.remove(i) for i in letters_die_er_niet_in_zitten: alphabet.remove(i) for word in words: for letter in alphabet: if letter in word: letters[letter].add(word) outcome = predict_outcome(template, word, letter) possible_outcomes_unique[letter].add(outcome) possible_outcomes_all[letter].append(outcome) possible_outcomes_astrid[letter][outcome] += 1 # options_letters = [] # total_letters = len(words) # for letter in letters: # count = len(letters[letter]) # # total_letters += count # options_letters.append((count, letter)) # options_letters = list(sorted(options_letters)) # target_letters = total_letters / 2 # debug("Possible outcomes (letters): %r" % (letters,)) # debug("%d mogelijke uitkomsten, doel is %d (letters)" % (total_letters, target_letters)) # debug("Options (letters): %r" % (",".join([repr((letter, count)) for count, letter in options_letters]),)) # optoptions_letters = list() # for optioncount, optionletter in options_letters: # optoptions_letters.append((abs(optioncount - target_letters), optionletter)) # optoptions_letters = list(sorted(optoptions_letters)) # debug("Optimale options (letters): %r" % (",".join([repr((letter, dist)) for dist, letter in optoptions_letters]),)) # options_all = [] # total_all = 0 # for letter in possible_outcomes_all: # count = len(possible_outcomes_all[letter]) # total_all += count # options_all.append((count, letter)) # options_all = list(sorted(options_all)) # target_all = total_all / 2 # debug("Possible outcomes (all): %r" % (possible_outcomes_all,)) # debug("%d mogelijke uitkomsten, doel is %d (all)" % (total_all, target_all)) # debug("Options (all): %r" % (",".join([repr((letter, count)) for count, letter in options_all]),)) # optoptions_all = list() # for optioncount, optionletter in options_all: # optoptions_all.append((abs(optioncount - target_all), optionletter)) # optoptions_all = list(sorted(optoptions_all)) # debug("Optimale options (all): %r" % (",".join([repr((letter, dist)) for dist, letter in optoptions_all]),)) options_astrid = [] total_astrid = len(words) for letter in possible_outcomes_astrid: p_sum = 0.0 for option in possible_outcomes_astrid[letter]: p_positie = float(possible_outcomes_astrid[letter][option]) / total_astrid # debug("letter=%r, optie=%r, n=%d, p=%.3f" % ( # letter, option, possible_outcomes_astrid[letter][option], p_positie)) p_sum += p_positie * ln(p_positie) p_nergens = 1.0 - (float(sum(possible_outcomes_astrid[letter].values()))) / total_astrid if p_nergens == 0.0: value = 0.0 else: value = (p_sum + p_nergens * ln(p_nergens)) / p_nergens options_astrid.append((value, letter)) options_astrid = list(sorted(options_astrid)) # debug("Possible outcomes (astrid): %r" % (possible_outcomes_astrid,)) # debug("%d mogelijke uitkomsten, doel is -inf (astrid)" % (total_astrid,)) # debug("Options (astrid): %r" % (",".join([repr((letter, count)) for count, letter in options_astrid]),)) optoptions_astrid = list() for optioncount, optionletter in options_astrid: optoptions_astrid.append((abs(optioncount), optionletter)) optoptions_astrid = list(sorted(optoptions_astrid, reverse=True)) # debug("Optimale options (astrid): %r" % (",".join([repr((letter, dist)) for dist, letter in optoptions_astrid]),)) # options_unique = [] # total_unique = 0 # for letter in possible_outcomes_unique: # count = len(possible_outcomes_unique[letter]) # total_unique += count # options_unique.append((count, letter)) # options_unique = list(sorted(options_unique)) # target_unique = total_unique / 2 # debug("Possible outcomes (unique): %r" % (possible_outcomes_unique,)) # debug("%d mogelijke uitkomsten, doel is %d (unique)" % (total_unique, target_unique)) # debug("Options (unique): %r" % (",".join([repr((letter, count)) for count, letter in options_unique]),)) # optoptions_unique = list() # for optioncount, optionletter in options_unique: # optoptions_unique.append((abs(optioncount - target_unique), optionletter)) # optoptions_unique = list(sorted(optoptions_unique)) # debug("Optimale options (unique): %r" % (",".join([repr((letter, dist)) for dist, letter in optoptions_unique]),)) top_letter = optoptions_astrid[0][1] cache2[template][forbidden] = top_letter add_to_cache2(top_letter, forbidden, template) return top_letter def raadfn_terminal(letter, template): print("!raad %s" % (letter,)) while True: res = input("Zat er een %s in? (j/n) " % (letter,)) if res in 'nj': break if res == 'j': template = input("Plak het template: ") return True, template else: return False, template def save_cache(): debug("Cache schrijven...") with open('cache', 'w') as f: for template, letter in cache.items(): f.write("%s%s\n" % (letter, template)) atexit.register(save_cache) <file_sep>/turbogalgje.py import sys, time from galgje import gogogalgje, pogingen from galgje_gamemaster import galgje as galgje_master from galgje_gamemaster import galgje_guess start = time.time() aantal = 0 while True: state, template = galgje_master(None) pogingen.clear() def raadfn(letter, template): geraden, goede_letter, template = galgje_guess(state, letter) return goede_letter, template try: gogogalgje(raadfn, template) except: pass print("Pogingen: %r, %d fouten" % (pogingen, state.fouten)) aantal += 1 print("%d, %.1f/s" % (aantal, float(aantal)/(time.time()-start))) <file_sep>/seed_cache2.py from collections import defaultdict from galgje import create_re_from_template, extract_letters_str, predict_outcome from math import log as ln import time from galgje_utils import debug from galgje_gamemaster import galgje as galgje_master from galgje_gamemaster import galgje_guess from galgje_gamemaster import GalgjeError debug("Woorden inlezen...") all_words = set() all_words_by_word_length = defaultdict(set) with open('dutch', 'rU') as f: for line in f: word = line.strip().lower() all_words.add(word) all_words_by_word_length[len(word)].add(word) debug("Cache2 inlezen...") cache2 = defaultdict(dict) with open("cache2", 'rU') as f: for line in f: line = line.strip() letter,forbidden,template = line.split('|') cache2[template][forbidden] = letter cache_hits = [0] cache_misses = [0] guesses = [0] def add_to_cache2(letter, forbidden, template): with open('cache2', 'a') as f: f.write("%s|%s|%s\n" % (letter, forbidden, template)) def match_template(word, template, letters_die_erin_zitten, letters_die_er_niet_in_zitten): for tchar, wchar in zip(template, word): if tchar != wchar: return False elif tchar == '_': if wchar in letters_die_erin_zitten or wchar in letters_die_er_niet_in_zitten: return False return True def galgje_reentrant(template, letters_die_er_niet_in_zitten): guesses[0] += 1 forbidden = ''.join(sorted(letters_die_er_niet_in_zitten)) if forbidden in cache2[template]: cache_hits[0] += 1 return cache2[template][forbidden] cache_misses[0] += 1 # Itereren vanaf hier letters_die_erin_zitten = extract_letters_str(template) # match = create_re_from_template(template, letters_die_erin_zitten) # debug("Rekenen...") possible_outcomes_astrid = defaultdict(lambda: defaultdict(lambda: 0)) new_words = set() for word in all_words_by_word_length[len(template)]: if match_template(word, template, letters_die_erin_zitten, letters_die_er_niet_in_zitten): new_words.add(word) words = new_words # debug("Woorden: (%d) %s" % (len(words), ",".join(list(words)[:20]),)) if len(words) == 1: print("Het woord is: %s" % (list(words)[0],)) return list(words)[0] if len(words) == 0: print("Ik weet het niet!") return None alphabet = set('abcdefghijklmnopqrstuvwxyz') for i in letters_die_erin_zitten: alphabet.remove(i) for i in letters_die_er_niet_in_zitten: alphabet.remove(i) for word in words: for letter in alphabet: if letter in word: outcome = predict_outcome(template, word, letter) possible_outcomes_astrid[letter][outcome] += 1 options_astrid = [] total_astrid = len(words) for letter in possible_outcomes_astrid: p_sum = 0.0 for option in possible_outcomes_astrid[letter]: p_positie = float(possible_outcomes_astrid[letter][option]) / total_astrid # debug("letter=%r, optie=%r, n=%d, p=%.3f" % ( # letter, option, possible_outcomes_astrid[letter][option], p_positie)) p_sum += p_positie * ln(p_positie) p_nergens = 1.0 - (float(sum(possible_outcomes_astrid[letter].values()))) / total_astrid if p_nergens == 0.0: value = 0.0 else: value = (p_sum + p_nergens * ln(p_nergens)) / p_nergens options_astrid.append((value, letter)) options_astrid = list(sorted(options_astrid)) top_letter = options_astrid[0][1] cache2[template][forbidden] = top_letter add_to_cache2(top_letter, forbidden, template) return top_letter failed_words = set() start = time.time() done_count = 0 for word in all_words: state, template = galgje_master(word) letters_die_er_niet_in_zitten = set() while True: try: letter = galgje_reentrant(template, letters_die_er_niet_in_zitten) if letter == None: break geraden, goede_letter, template = galgje_guess(state, letter) if not goede_letter: letters_die_er_niet_in_zitten.add(letter) if geraden: break except GalgjeError: failed_words.add(word) with open("nietgeraden", "a") as f: f.write(word + '\n') break debug("guesses: %.1f/s, hits=%.1f%%" % (guesses[0]/(time.time() - start), float(100.0 * cache_hits[0]) / (cache_hits[0] + cache_misses[0]))) done_count += 1 done = float(done_count) / len(all_words) debug("%.3f%% of %d words" % (done * 100.0, len(all_words))) td = time.time() - start remaining = float(len(all_words) - done_count) / len(all_words) if done > 0: debug("ETA: %f seconds" % (td / done * remaining)) debug("Niet-gerade woorden: %.3f%%" % (float(len(failed_words)) * 100.0 / done_count,)) def save_cache2(): with open('cache2', 'w') as f: for template in cache2: for forbidden in cache2[template]: letter = cache2[template][forbidden] f.write("%s|%s|%s\n" % (letter, forbidden, template)) import atexit atexit.register(save_cache2) <file_sep>/galgjetree.py import sys, re from collections import defaultdict counts = defaultdict(lambda: 0) alphabet = set('abcdefghijklmnopqrstuvwxyz') words = set() aantal_letters = 7 print("Inlezen...") count = 0 with open('dutch', 'r') as f: for line in f: word = line.strip().lower() if len(word) == aantal_letters: if re.match(r'^[a-z]*$', word): words.add(word) count += 1 if count >= 100: break def add_letter(pattern, word, letter): new_pattern = '' for pos in range(len(word)): if word[pos] == letter: new_pattern += letter else: new_pattern += pattern[pos] return new_pattern print("digraph G {") for word in words: start = '_' * len(word) pattern = '' print("#word: %r" % (word,)) def iterate(pattern, word, remaining_letters): for letter in remaining_letters: if letter in word: new_pattern = add_letter(pattern, word, letter) print("%s -> %s [label=%s];" % (pattern, new_pattern, letter)) if new_pattern == word: return iterate(new_pattern, word, remaining_letters - set(letter)) iterate(start, word, alphabet) print("}") sys.exit(0) letters_die_erin_zitten = set() letters_die_er_niet_in_zitten = set() while True: # Itereren vanaf hier print("Rekenen...") letters = defaultdict(set) new_words = set() for word in words: add = True for letter in letters_die_er_niet_in_zitten: if letter in word: add = False break for letter in letters_die_erin_zitten: if letter not in word: add = False break if add: new_words.add(word) words = new_words for word in words: for letter in alphabet: if letter in word: letters[letter].add(word) def countfn(letter): return len(letters[letter]) gesorteerde_letters = list(sorted(letters, key=countfn, reverse=True)) print("Letters: %s" % ("".join(letters_die_erin_zitten),)) print("Overgebleven letters: %s" % ("".join(gesorteerde_letters),)) print("Woorden: (%d) %s" % (len(words), ",".join(list(words)[:20]),)) top_letter = gesorteerde_letters[0] print("Voorkomendste letter: %s (%d van %d, %.2f%%)" % ( top_letter, len(letters[top_letter]), len(words), 100.0 * float(len(letters[top_letter])) / len(words))) print("!raad %s" % (top_letter,)) while True: res = input("Zat er een %s in? (j/n) " % (top_letter,)) if res in 'nj': break if res == 'j': # letter zat erin letters_die_erin_zitten.add(top_letter) else: letters_die_er_niet_in_zitten.add(top_letter) alphabet.remove(top_letter)
b4c9f94c3887cd1a34e80f039b18cbcdfd868ae4
[ "Python" ]
11
Python
zarq/galgje
5b616c07fe333937e5ee8784b51f02942fcb83b3
65e4d6df2016115f6f15f679b9b2e8e9d8d85e10
refs/heads/master
<file_sep>'use strict'; var gulp = require('gulp'), mocha = require('gulp-spawn-mocha'); gulp.task('test', function () { return gulp.src(['test/*.spec.js'], { read: false }) .pipe(mocha({ r: 'test/helpers/setup.js', istanbul: true })); }); gulp.task('default', ['test'], function () { }); gulp.task('watch', ['test'], function () { gulp.watch(['test/**/*.spec.js', 'lib/**/*.js'], ['test']); }); <file_sep>'use strict'; describe("the text-to-image generator", function () { var imageGenerator, Promise = require('bluebird'), glob = require('glob'), fs = require('fs'), path = require('path'), sizeOf = require('image-size'), readimage = require('readimage'), extractColors = require('./helpers/extractColors'); beforeEach(function () { imageGenerator = require('../lib/text-to-image'); }); afterEach(function () { // remove all pngs created by the lib in debug mode var pngs = glob.sync(path.join(process.cwd(), '*.png')); pngs.forEach(function (item, index, array) { fs.unlinkSync(item); }); delete process.env.DEBUG; }); it("should expose a generate function", function () { imageGenerator.should.respondTo('generate'); }); it("should return a promise", function () { expect(imageGenerator.generate('Hello world')).to.respondTo('then'); }); it("should generate an image data url", function () { return imageGenerator.generate('Hello world').should.eventually.match(/^data:image\/png;base64/); }); it("should create a png file in debug mode", function () { return imageGenerator.generate('Hello world', { debug: true }).then(function () { expect(glob.sync(path.join(process.cwd(), '*.png'))).to.have.lengthOf(1); }); }); it("should not create a file if not in debug mode", function () { return imageGenerator.generate('Hello world').then(function () { expect(glob.sync(path.join(process.cwd(), '*.png'))).to.have.lengthOf(0); }); }); it("should generate equal width but longer png when there's plenty of text", function () { return Promise.all([ imageGenerator.generate('Hello world', { debug: true }), imageGenerator.generate('Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut dolor eros, lobortis ac orci a, molestie sagittis libero.', { debug: true }) ]).then(function () { var images = glob.sync(path.join(process.cwd(), '*.png')); // expect(images).to.have.lengthOf(2); var dimensions1 = sizeOf(images[0]); var dimensions2 = sizeOf(images[1]); expect(dimensions1.height).to.be.above(0); expect(dimensions1.height).to.be.below(dimensions2.height); expect(dimensions1.width).to.equal(dimensions2.width); }); }); it("should create a new lines when a \\n occurrs", function () { return Promise.all([ imageGenerator.generate('Hello world', { debug: true }), imageGenerator.generate('Hello world\nhello again', { debug: true }) ]).then(function () { var images = glob.sync(path.join(process.cwd(), '*.png')); // expect(images).to.have.lengthOf(2); var dimensions1 = sizeOf(images[0]); var dimensions2 = sizeOf(images[1]); expect(dimensions1.height).to.be.above(0); expect(dimensions1.height).to.be.below(dimensions2.height); expect(dimensions1.width).to.equal(dimensions2.width); }); }); it("should create a new lines when a multiple \\n occurrs", function () { return Promise.all([ imageGenerator.generate('Hello world\nhello again', { debug: true }), imageGenerator.generate('Hello world\n\n\nhello again', { debug: true }) ]).then(function () { var images = glob.sync(path.join(process.cwd(), '*.png')); // expect(images).to.have.lengthOf(2); var dimensions1 = sizeOf(images[0]); var dimensions2 = sizeOf(images[1]); expect(dimensions1.height).to.be.above(0); expect(dimensions1.height).to.be.below(dimensions2.height); expect(dimensions1.width).to.equal(dimensions2.width); }); }); it("should default to a 400 px wide image", function () { return Promise.all([ imageGenerator.generate('Lorem ipsum dolor sit amet.', { debug: true }) ]).then(function () { var images = glob.sync(path.join(process.cwd(), '*.png')); var dimensions = sizeOf(images[0]); expect(dimensions.width).to.equal(400); }); }); it("should be configurable to use another image width", function () { return Promise.all([ imageGenerator.generate('Lorem ipsum dolor sit amet.', { debug: true, maxWidth: 500 }) ]).then(function () { var images = glob.sync(path.join(process.cwd(), '*.png')); var dimensions = sizeOf(images[0]); expect(dimensions.width).to.equal(500); }); }); it("should default to a white background no transparency", function () { return Promise.all([ imageGenerator.generate('Lorem ipsum dolor sit amet.', { debug: true }) ]).then(function () { var images = glob.sync(path.join(process.cwd(), '*.png')); var imageData = fs.readFileSync(images[0]); return new Promise(function (resolve, reject) { readimage(imageData, function (err, image) { if (err) { reject(err); } else { resolve(image); } }); }); }).then(function (image) { expect(image.frames.length).to.equal(1); expect(image.frames[0].data[0]).to.equals(0xff); expect(image.frames[0].data[1]).to.equals(0xff); expect(image.frames[0].data[2]).to.equals(0xff); expect(image.frames[0].data[3]).to.equals(0xff); }); }); it("should use the background color specified with no transparency", function () { return Promise.all([ imageGenerator.generate('Lorem ipsum dolor sit amet.', { debug: true, bgColor: '#001122' }) ]).then(function () { var images = glob.sync(path.join(process.cwd(), '*.png')); var imageData = fs.readFileSync(images[0]); return new Promise(function (resolve, reject) { readimage(imageData, function (err, image) { if (err) { reject(err); } else { resolve(image); } }); }); }).then(function (image) { expect(image.frames.length).to.equal(1); expect(image.frames[0].data[0]).to.equals(0x00); expect(image.frames[0].data[1]).to.equals(0x11); expect(image.frames[0].data[2]).to.equals(0x22); expect(image.frames[0].data[3]).to.equals(0xff); }); }); it("should default to a black text color", function () { var WIDTH = 720; var HEIGHT = 220; return Promise.all([ imageGenerator.generate('Lorem ipsum dolor sit amet.', { debug: true, maxWidth: WIDTH, fontSize: 100, lineHeight: 100 }) ]).then(function () { var images = glob.sync(path.join(process.cwd(), '*.png')); var dimensions = sizeOf(images[0]); expect(dimensions.width).to.equals(WIDTH); expect(dimensions.height).to.equals(HEIGHT); var imageData = fs.readFileSync(images[0]); return new Promise(function (resolve, reject) { readimage(imageData, function (err, image) { if (err) { reject(err); } else { resolve(image); } }); }); }).then(function (image) { var map = extractColors(image); // GIMP reports 256 colors on this image expect(Object.keys(map).length).to.be.within(2, 256); expect(map['#000000']).to.be.above(10); expect(map['#ffffff']).to.be.above(100); }); }); it("should use the text color specified", function () { var WIDTH = 720; var HEIGHT = 220; return Promise.all([ imageGenerator.generate('Lorem ipsum dolor sit amet.', { debug: true, maxWidth: WIDTH, fontSize: 100, lineHeight: 100, textColor: "#112233" }) ]).then(function () { var images = glob.sync(path.join(process.cwd(), '*.png')); var dimensions = sizeOf(images[0]); expect(dimensions.width).to.equals(WIDTH); expect(dimensions.height).to.equals(HEIGHT); var imageData = fs.readFileSync(images[0]); return new Promise(function (resolve, reject) { readimage(imageData, function (err, image) { if (err) { reject(err); } else { resolve(image); } }); }); }).then(function (image) { var map = extractColors(image); // GIMP reports 256 colors on this image expect(Object.keys(map).length).to.be.within(2, 256); expect(map['#112233']).to.be.above(10); expect(map['#ffffff']).to.be.above(100); }); }); }); <file_sep>'use strict'; var chai = require('chai'), chaiAsPromised = require('chai-as-promised'), chaiThings = require('chai-things'), sinonChai = require("sinon-chai"); global.sinon = require('sinon'); global.expect = chai.expect; global.should = chai.should(); global.assert = chai.assert; chai.use(chaiAsPromised); chai.use(chaiThings); chai.use(sinonChai);
23d674e18a60e724f23ccca6514e7efd372ffcfc
[ "JavaScript" ]
3
JavaScript
izigibran/text-to-image
e54d50bc9cd32d852306eb522cb7b5294a0a78c1
f7a9d954ed55849f99a19570c7b24d84f05394b4
refs/heads/master
<repo_name>wscarval/OldHunters<file_sep>/guild_watcher.py import logging import re import urllib.parse import requests import pickle import json import time log = logging.getLogger(__name__) log.setLevel(logging.DEBUG) consoleHandler = logging.StreamHandler() consoleHandler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s: %(message)s')) consoleHandler.setLevel(logging.DEBUG) log.addHandler(consoleHandler) cfg = {} try: with open('config.json') as json_data: cfg = json.load(json_data) except FileNotFoundError: log.error("Missing config.json file. Check the example file.") exit() except ValueError: log.error("Malformed config.json file.") exit() def save_data(file, data): with open(file, "wb") as f: pickle.dump(data, f, protocol=pickle.HIGHEST_PROTOCOL) def load_data(file): try: with open(file, "rb") as f: return pickle.load(f) except ValueError: return None except FileNotFoundError: return None def get_character(name, tries=5): """Returns a dictionary with a player's info The dictionary contains the following keys: name, deleted, level, vocation, world, residence, married, gender, guild, last,login, chars*. *chars is list that contains other characters in the same account (if not hidden). Each list element is dictionary with the keys: name, world. May return ERROR_DOESNTEXIST or ERROR_NETWORK accordingly.""" url_character = "https://secure.tibia.com/community/?subtopic=characters&name=" try: url = url_character + urllib.parse.quote(name.encode('iso-8859-1')) except UnicodeEncodeError: return None char = dict() # Fetch website try: r = requests.get(url=url) content = r.text except requests.RequestException: if tries == 0: return {"error": "Network"} else: tries -= 1 return get_character(name, tries) # Trimming content to reduce load try: startIndex = content.index('<div class="BoxContent"') endIndex = content.index("<B>Search Character</B>") content = content[startIndex:endIndex] except ValueError: # Website fetch was incomplete, due to a network error if tries == 0: return None else: tries -= 1 time.sleep(2) return get_character(name, tries) # Check if player exists if "Name:</td><td>" not in content: return None # Name m = re.search(r'Name:</td><td>([^<,]+)', content) if m: char['name'] = m.group(1).strip() # Vocation m = re.search(r'Vocation:</td><td>([^<]+)', content) if m: char['vocation'] = m.group(1) # World m = re.search(r'World:</td><td>([^<]+)', content) if m: char['world'] = m.group(1) return char def get_guild_info(name, tries=5): try: r = requests.get("https://secure.tibia.com/community/", params={"subtopic":"guilds","page":"view","GuildName":name}) content = r.text except requests.RequestException: if tries == 0: return {"error": "Network"} else: tries -= 1 return get_guild_info(name, tries) try: start_index = content.index('<div class="BoxContent"') end_index = content.index('<div id="ThemeboxesColumn" >') content = content[start_index:end_index] except ValueError: # Website fetch was incomplete, due to a network error return {"error": "Network"} if '<div class="Text" >Error</div>' in content: return {"error": "NotFound"} guild = {} # Logo URL m = re.search(r'<IMG SRC=\"([^\"]+)\" W', content) if m: guild['logo_url'] = m.group(1) # Regex pattern to fetch members regex_members = r'<TR BGCOLOR=#[\dABCDEF]+><TD>(.+?)</TD>\s</td><TD><A HREF="https://secure.tibia.com/community/\?subtopic=characters&name=(.+?)">.+?</A> *\(*(.*?)\)*</TD>\s<TD>(.+?)</TD>\s<TD>(.+?)</TD>\s<TD>(.+?)</TD>' pattern = re.compile(regex_members, re.MULTILINE + re.S) m = re.findall(pattern, content) guild['members'] = [] # Check if list is empty if m: # Building dictionary list from members last_rank = "" guild["ranks"] = [] for (rank, name, title, vocation, level, joined) in m: rank = last_rank if (rank == '&#160;') else rank if rank not in guild["ranks"]: guild["ranks"].append(rank) last_rank = rank name = requests.utils.unquote(name).replace("+", " ") joined = joined.replace('&#160;', '-') guild['members'].append({'rank': rank, 'name': name, 'title': title, 'vocation': vocation, 'level': level, 'joined': joined}) return guild vocation_emojis = { "Druid": "\U00002744", "Elder Druid": "\U00002744", "Knight": "\U0001F6E1", "Elite Knight": "\U0001F6E1", "Sorcerer": "\U0001F525", "Master Sorcerer": "\U0001F525", "Paladin": "\U0001F3F9", "Royal Paladin": "\U0001F3F9", } vocation_abbreviations = { "Druid": "D", "Elder Druid": "ED", "Knight": "K", "Elite Knight": "EK", "Sorcerer": "S", "Master Sorcerer": "MS", "Paladin": "P", "Royal Paladin": "RP", "None": "N", } def announce_changes(guild_config, name, changes, joined, total): new_member_format = "[{name}]({url}) - Level **{level}** **{vocation}** {emoji}" member_format = "[{name}]({url}) - Level **{level}** **{vocation}** {emoji} - Rank: **{rank}** - " \ "Joined: **{joined}**" name_changed_format = "{former_name} \U00002192 [{name}]({url}) - Level **{level}** **{vocation}** {emoji} - " \ "Rank: **{rank}**" title_changed_format = "[{name}]({url}) - {old_title} \U00002192 {title} - Level **{level}** **{vocation}** {emoji} - " \ "Rank: **{rank}**" body = { "username": guild["name"] if guild_config.get("override_name", False) else cfg.get("name"), "avatar_url": guild_config.get("avatar_url", cfg.get("avatar_url")), "embeds": [], } joined_str = "" removed = "" name_changed = "" deleted = "" promoted = "" demoted = "" title_changed = "" for m in (changes+joined): m["url"] = "https://secure.tibia.com/community/?subtopic=characters&name=" + requests.utils.quote(m["name"]) m["emoji"] = vocation_emojis.get(m["vocation"], "") m["vocation"] = vocation_abbreviations.get(m["vocation"], "") change_type = m.get("type", "") if change_type == "removed": removed += member_format.format(**m) + "\n" elif change_type == "promotion": promoted += member_format.format(**m) + "\n" elif change_type == "demotion": demoted += member_format.format(**m) + "\n" elif change_type == "namechange": name_changed += name_changed_format.format(**m) + "\n" elif change_type == "titlechange": if m["old_title"] == "": m["old_title"] = "None" if m["title"] == "": m["title"] = "None" title_changed += title_changed_format.format(**m) + "\n" elif change_type == "deleted": deleted += member_format.format(**m) + "\n" else: joined_str += new_member_format.format(**m) + "\n" if joined_str or deleted or removed: body["content"] = "The guild now has **{0:,}** members.".format(total) if joined_str: title = "New member" if not guild_config.get("override_name", False): title += " in {0}".format(name) if len(cfg["guilds"]) > 1 else "" new = {"color": 361051, "title": title, "description": joined_str} body["embeds"].append(new) if removed: title = "Member left or kicked" if not guild_config.get("override_name", False): title += " in {0}".format(name) if len(cfg["guilds"]) > 1 else "" new = {"color": 16711680, "title": title, "description": removed} body["embeds"].append(new) if promoted: title = "Member promoted" if not guild_config.get("override_name", False): title += " in {0}".format(name) if len(cfg["guilds"]) > 1 else "" new = {"color": 16776960, "title": title, "description": promoted} body["embeds"].append(new) if demoted: title = "Member demoted" if not guild_config.get("override_name", False): title += " in {0}".format(name) if len(cfg["guilds"]) > 1 else "" new = {"color": 16753920, "title": title, "description": demoted} body["embeds"].append(new) if deleted: title = "Member deleted" if not guild_config.get("override_name", False): title += " in {0}".format(name) if len(cfg["guilds"]) > 1 else "" new = {"color": 0, "title": title, "description": deleted} body["embeds"].append(new) if name_changed: title = "Member changed name" if not guild_config.get("override_name", False): title += " in {0}".format(name) if len(cfg["guilds"]) > 1 else "" new = {"color": 65535, "title": title, "description": name_changed} body["embeds"].append(new) if title_changed: title = "Title changed" if not guild_config.get("override_name", False): title += " in {0}".format(name) if len(cfg["guilds"]) > 1 else "" new = {"color": 12915437, "title": title, "description": title_changed} body["embeds"].append(new) requests.post(guild.get("webhook_url", guild_config.get("webhook_url", cfg.get("webhook_url"))), data=json.dumps(body), headers={"Content-Type": "application/json"}) if __name__ == "__main__": while True: # Iterate each guild for guild in cfg["guilds"]: if guild.get("webhook_url", cfg.get("webhook_url")) is None: log.error("Missing Webhook URL in config.json") exit() name = guild.get("name", None) if name is None: log.error("Guild missing name.") time.sleep(5) continue guild_file = name+".data" guild_data = load_data(guild_file) if guild_data is None: log.info(name + " - No previous data found. Saving current data.") guild_data = get_guild_info(name) error = guild_data.get("error") if error is not None: log.error(name +" - Error: " + error) continue save_data(guild_file, guild_data) time.sleep(5) continue log.info(name + " - Scanning guild...") new_guild_data = get_guild_info(name) error = new_guild_data.get("error") if error is not None: log.error(name + " - Error: "+error) continue save_data(guild_file, new_guild_data) changes = [] # Looping previously saved members total_members = len(new_guild_data["members"]) for member in guild_data["members"]: found = False # Looping current members for _member in new_guild_data["members"]: if member["name"] == _member["name"]: # Member still in guild, we remove it from list for faster iterating new_guild_data["members"].remove(_member) found = True # Rank changed if member["rank"] != _member["rank"]: try: if new_guild_data["ranks"].index(member["rank"]) < \ new_guild_data["ranks"].index(_member["rank"]): # Demoted log.info("Member demoted: " + _member["name"]) _member["type"] = "demotion" changes.append(_member) else: # Promoted log.info("Member promoted: " + _member["name"]) _member["type"] = "promotion" changes.append(_member) except ValueError: # Todo: Handle this pass # Title changed if member["title"] != _member["title"]: _member["type"] = "titlechange" _member["old_title"] = member["title"] log.info("Member title changed: {name} - {title}".format(**member)) changes.append(_member) break if not found: # We check if it was a namechange or character deleted log.info("Checking character {name}".format(**member)) char = get_character(member["name"]) # Character was deleted (or maybe namelocked) if char is None: member["type"] = "deleted" changes.append(member) continue # Character has a new name and matches someone in guild, meaning it got a name change _found = False for _member in new_guild_data["members"]: if char["name"] == _member["name"]: _member["former_name"] = member["name"] _member["type"] = "namechange" changes.append(_member) new_guild_data["members"].remove(_member) log.info("{former_name} changed name to {name}".format(**_member)) _found = True break if _found: continue log.info("Member no longer in guild: " + member["name"]) member["type"] = "removed" changes.append(member) joined = new_guild_data["members"][:] if len(joined) > 0: log.info("New members found: " + ",".join(m["name"] for m in joined)) if guild["override_image"]: guild["avatar_url"] = new_guild_data["logo_url"] announce_changes(guild, name, changes, joined, total_members) log.info(name + " - Scanning done") time.sleep(2) time.sleep(5*60) <file_sep>/README.md # GuildWatcher [![Build Status](https://travis-ci.org/Galarzaa90/GuildWatcher.svg?branch=master)](https://travis-ci.org/Galarzaa90/GuildWatcher) A discord webhook that posts guild changes (member joins, members leaves, member promoted) in a Discord channel. ## Requirements: * Python 3.2 or higher with the following module: * Requests ## Configuring Webhooks 1. On the desired channel, go to its settings and click on the **Webhooks** section. 1. Click on **Create Webhook**. 1. Change the bot's name and avatar to whatever you prefer. * You can also edit config.json to override the bot's username and avatar 1. Rename **config-example.json** to **config.json** and edit it. * "*name*" and "*avatar_url*" are optional parameters, they can be left blank or removed. If used, those values will be used instead of the ones set in the webhook configuration screen in discord. * Add as many guilds as you like. If "*override_name*" or "*override_image*" is used, the message will show the guild's name and/or picture instead. 1. Run the script. ## Current Features * Announces when a member joins * Announces when a member leaves or is kicked * Announce when a member is promoted or demoted * Announce when a member changes name * Announce when a member's title is changed * Multiple guilds support * Webhook URL configurable per guild ## Known Issues * Renaming a rank would trigger all rank members getting announced as leaving and joining back. ## Planned features * Configurable scan times * Check invites ## Example ![image](https://user-images.githubusercontent.com/12865379/29383497-7df48300-8285-11e7-83c3-f774ad3a43a8.png)
44a66f5ee2b251fe975338a27dde93543e9f2cd7
[ "Markdown", "Python" ]
2
Python
wscarval/OldHunters
b9c458527365257ff836daeb75da63adec7a5641
b315b8bb5a8628e9f08f338677882e073c2b277c
refs/heads/master
<file_sep>#!/usr/bin/python3 #Problem 1 - Multiples of 3 and 5 #If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. #Find the sum of all the multiples of 3 or 5 below 1000. totalsum=0 for currentnum in range(0,1000): if(currentnum%5==0 or currentnum%3==0): totalsum+=currentnum print("Counting: "+str(currentnum)+" Total is: "+str(totalsum)) print (totalsum) <file_sep>def checkfac(num): for j in range(11,20): if(num%j!=0): return False return True for i in range(9999999,99999999): if(checkfac(i)): print(str(i)) break; else: print(str(i)+" Not applicable ") <file_sep>#!/usr/bin/python3 #Problem 3 - Largest prime factor #The prime factors of 13195 are 5, 7, 13 and 29. #What is the largest prime factor of the number 600851475143 ? def checkPrime(num): for i in range(2,num): if(num%i==0): return False return True def longdivide(num): for i in range(2,num): if(num%i==0): if(checkPrime(num)): return i; targetnum=600851475143 rentnum=targetnum print("Starting- targetnum: "+str(targetnum)+" limit: "+str(limit)) while currentnum > limit : longdivide(currentnum) # print("Checking:"+str(currentnum)); # if(targetnum%currentnum==0): #if(checkPrime(currentnum)): # print (str(currentnum)) currentnum=currentnum/currentdivisor <file_sep> def factorise(num): for i in range(100, 999): if(num%i==0): print "================================" print "Factor found:"+str(i) divval=num/i if(divval>99 and divval<1000): print(str(num)+"="+str(divval))+"X"+str(i) return True return False for i in range(999999,99999, -1): if(str(i)==str(i)[::-1]): print(str(i)) if(factorise(i)): break; <file_sep>#!/usr/bin/python3 #Problem 2 - Even Fibonacci numbers #Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: #1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... #By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. currentnum=1 prevnum=0 fibsum=0 limitval=4000000 while currentnum<limitval: nextnum=currentnum+prevnum prevnum=currentnum currentnum=nextnum if(currentnum%2==0 and currentnum<limitval): fibsum+=currentnum print(str(currentnum)) print ("Sum: "+str(fibsum)) <file_sep>#The sum of the squares of the first ten natural numbers is, 12 + 22 + ... + 102 = 385 #The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)2 = 552 = 3025 #Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640. #Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. totsum=0 sqsum=0 for i in range(1,101): totsum+=i; sqsum+=(i*i); print(str(i)+" ^2+") totsumsq=totsum*totsum diff=totsumsq-sqsum print("Total Sum: "+str(totsum)+" Sum of squares: "+str(sqsum)+" Difference: "+str(diff))
50f022f2a4bee8f4c9c34e0b4707c342635c1c71
[ "Python" ]
6
Python
thepegasus/projecteuler
546e4f7d209910ea3fb4ded526e9e90e100aa2c7
cae01c673eab2f689221f2041607f7fad96bcf7e
refs/heads/master
<repo_name>bartlett705/tango-sierra<file_sep>/todo.txt [todo] I didn't end up having time to implement all of the bonus features, but I wanted to include some thoughts on how I would do it: - Game Search - Since we already have all the game info available, I would add a text input box at the top of the page, with its value bound to a string state property called 'searchTerm' via a new action creator / reducer case triggered by the text input's onChange event handler. Finally, I would add an Array.filter call before the gameData.map call in GameList.tsx that would only pass through game's for which gameData.Name.includes(SearchTerm) === true. This should implement real-time game filtering by text. - Periodic Updates - perhaps slightly better than wrapping our call to fetchGames in GameList in a setInterval call would be to save the timestamp from the initial fetch in a new piece of state, and compare that timestamp to the current time whenever a game is clicked to get details. If more than a few minutes have elapsed since the initial fetch, we would dispatch fetchGames again. This controller logic could happen one of two ways - the check could take place and we could dispatch the appropriate action(s) from a clickHandler function in our GameList component, or we could add a thunk that is dispatched from the UI at the same point setDetailIndex is now, which would have the ability to perform the conditional check and dispatch additional action(s) as needed. <file_sep>/source/components/games/GameListContainer.ts import * as React from 'react'; import { bindActionCreators, Dispatch } from 'redux'; import { connect } from 'react-redux'; import { GameList, GameListProps, ConnectedProps, ConnectedDispatch } from './GameList'; import { GlobalState } from '../../state/GlobalState'; import { fetchGames,setDetailIndex } from '../../actions/games'; function mapStateToProps(state: GlobalState, props: GameListProps): ConnectedProps { return { games: state.games.games, isFetching: state.games.isFetching, isError: state.games.isError, detailIndex: state.games.detailIndex, progress: state.games.progress, }; }; function mapDispatchToProps(dispatch: Dispatch<any>): ConnectedDispatch { return bindActionCreators({ fetchGames, setDetailIndex, }, dispatch); }; // tslint:disable-next-line:variable-name export const GameListContainer = connect(mapStateToProps, mapDispatchToProps)(GameList) as React.ComponentClass<GameListProps>; <file_sep>/source/models/Config.ts import { template } from "lodash"; export class Config { gamesDataURL = "https://clientupdate-v6.cursecdn.com/Feed/games/v10/games.json"; gameIconURLTemplate = template("https://clientupdate-v6.cursecdn.com/GameAssets/<%= gameID %>/Icon64.png"); } <file_sep>/source/models/Game.ts export interface Game { Name: string; SupportsAddons: Boolean; SupportsVoice: Boolean; Order: number; Slug: string; GameFiles: Array<GameFile>; CategorySections: Array<Category>; ID: number; } interface GameFile { FileName: string; } interface Category { Name: string; } <file_sep>/source/state/GamesState.ts import { Game } from "../models/Game"; export interface GamesState { games: Game[]; isFetching: boolean; isError: boolean; detailIndex: number; progress: number; } <file_sep>/source/actions/games.ts import { GlobalStateGetter } from "../state/GlobalState"; import { Game } from "../models/Game"; import { config } from '../globals'; // Update download progress export type UPDATE_PROGRESS = 'UPDATE_PROGRESS'; export const UPDATE_PROGRESS: UPDATE_PROGRESS = 'UPDATE_PROGRESS'; export type UpdateProgress = { type: UPDATE_PROGRESS; progress: Number; }; export function updateProgress(progress: Number): UpdateProgress { return { type: UPDATE_PROGRESS, progress }; } // Set index of game to view details export type SET_DETAIL_INDEX = 'SET_DETAIL_INDEX'; export const SET_DETAIL_INDEX: SET_DETAIL_INDEX = 'SET_DETAIL_INDEX'; export type SetDetailIndex = { type: SET_DETAIL_INDEX; detailIndex: Number; }; export function setDetailIndex(detailIndex: Number): SetDetailIndex { return { type: SET_DETAIL_INDEX, detailIndex }; } // Fetch Games Started export type FETCH_GAMES_STARTED = 'FETCH_GAMES_STARTED'; export const FETCH_GAMES_STARTED: FETCH_GAMES_STARTED = 'FETCH_GAMES_STARTED'; export type FetchGamesStarted = { type: FETCH_GAMES_STARTED; }; export function fetchGamesStarted(): FetchGamesStarted { return { type: FETCH_GAMES_STARTED }; } // Fetch Games Succeeded export type FETCH_GAMES_SUCCEEDED = 'FETCH_GAMES_SUCCEEDED'; export const FETCH_GAMES_SUCCEEDED: FETCH_GAMES_SUCCEEDED = 'FETCH_GAMES_SUCCEEDED'; export type FetchGamesSucceeded = { type: FETCH_GAMES_SUCCEEDED; games: Game[]; }; export function fetchGamesSucceeded(games: Game[]): FetchGamesSucceeded { return { type: FETCH_GAMES_SUCCEEDED, games }; } // Fetch Games Failed export type FETCH_GAMES_FAILED = 'FETCH_GAMES_FAILED'; export const FETCH_GAMES_FAILED: FETCH_GAMES_FAILED = 'FETCH_GAMES_FAILED'; export type FetchGamesFailed = { type: FETCH_GAMES_FAILED; }; export function fetchGamesFailed(): FetchGamesFailed { return { type: FETCH_GAMES_FAILED }; } // Fetch Games Thunk export function fetchGames() { return (dispatch: Redux.Dispatch<any>, getState: GlobalStateGetter) => { dispatch(fetchGamesStarted()); const xhr = new XMLHttpRequest(); xhr.onload = function(e) { dispatch(fetchGamesSucceeded(JSON.parse(xhr.responseText).data)); }; xhr.addEventListener("error", (e) => { console.log('error!', e.error); dispatch(fetchGamesFailed()); }); xhr.addEventListener('progress', (e) => { dispatch(updateProgress(parseInt((e.loaded / 3003).toString().slice(0, 2)))); }); xhr.open("GET", config.gamesDataURL); xhr.send(); // fetch(config.gamesDataURL) // .then((response) => response.json()) // .then((data: any) => { // dispatch(fetchGamesSucceeded(data.data)); // }) // .catch((err:Error)=> { // console.log('Error! ', err); // }); }; } <file_sep>/source/__tests__/state.test.ts // These tests exercise redux code; namely action creators, reducers, and // createStore in globals. import { store, initGlobals } from '../globals'; import { initialStateFixture, gamesDataFixture } from './fixtures'; import { fetchGamesStarted, fetchGamesFailed, fetchGamesSucceeded, updateProgress, setDetailIndex } from '../actions/games'; import { GamesState } from '../state/GamesState'; let fetchingStateFixture: GamesState; let progressStateFixture: GamesState; let fetchFailedStateFixture: GamesState; describe('globals tests', () => { it('initGlobals() runs gracefully', () => { initGlobals(); }); it('createStore() returns a store object with initial values', () => { expect(store.getState().games).toEqual(initialStateFixture); }); }); describe('actions/games synchronous actions & gamesReducer tests', () => { it('fetchGamesStarted() properly modifies state.games.isFetching', () => { store.dispatch(fetchGamesStarted()); fetchingStateFixture = Object.assign({}, initialStateFixture, { isFetching: true }); expect(store.getState().games).toEqual(fetchingStateFixture); }); it('updateProgress() properly modifies state.games.progress', () => { store.dispatch(updateProgress(50)); progressStateFixture = Object.assign({}, fetchingStateFixture, { progress: 50 }); expect(store.getState().games).toEqual(progressStateFixture); }); it('FetchGamesFailed() properly modifies state.games.isError and state.games.isFetching', () => { store.dispatch(fetchGamesFailed()); fetchFailedStateFixture = Object.assign({}, progressStateFixture, { isFetching: false, isError: true }); expect(store.getState().games).toEqual(fetchFailedStateFixture); }); it('FetchGamesSucceeded() properly modifies state.games.isFetching, state.games.isError, and state.games.games', () => { // from here on we're comparing properties individually rather than the entire state, // because the expected / actual log for a failure of a whole-state test is // so long as to render the test output useless. store.dispatch(fetchGamesSucceeded(gamesDataFixture)); expect(store.getState().games.isFetching).toEqual(false); expect(store.getState().games.isError).toEqual(false); expect(store.getState().games.games.length).toEqual(198); }); it('Games are sorted by Game.Order', () => { const currentState = store.getState().games; expect(currentState.games[0].Order <= currentState.games[1].Order).toEqual(true); expect(currentState.games[1].Order <= currentState.games[5].Order).toEqual(true); expect(currentState.games[7].Order <= currentState.games[9].Order).toEqual(true); expect(currentState.games[10].Order <= currentState.games[100].Order).toEqual(true); }); it('setDetailIndex() properly modifies state.games.detailIndex', () => { store.dispatch(setDetailIndex(1)); expect(store.getState().games.detailIndex).toEqual(1); }); }); <file_sep>/source/__tests__/fixtures/gamesDataFixture.ts export const gamesData = [ { "ID": 1, "Name": "World of Warcraft", "Slug": "wow", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 33, "GameId": 1, "Name": "Icon16" }, { "Id": 34, "GameId": 1, "Name": "Icon24" }, { "Id": 35, "GameId": 1, "Name": "Icon32" }, { "Id": 36, "GameId": 1, "Name": "Logo" } ], "GameFiles": [ { "Id": 1, "GameId": 1, "IsRequired": false, "FileName": "WoW.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 2, "GameId": 1, "IsRequired": false, "FileName": "WoW-64.exe", "FileType": 2, "PlatformType": 3 }, { "Id": 3, "GameId": 1, "IsRequired": false, "FileName": "World of Warcraft Launcher.exe", "FileType": 3, "PlatformType": 4 }, { "Id": 4, "GameId": 1, "IsRequired": false, "FileName": "world.MPQ.lock", "FileType": 4, "PlatformType": 1 }, { "Id": 151, "GameId": 1, "IsRequired": false, "FileName": "World of Warcraft.app", "FileType": 2, "PlatformType": 5 }, { "Id": 187, "GameId": 1, "IsRequired": false, "FileName": "WowB.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 188, "GameId": 1, "IsRequired": false, "FileName": "WowB-64.exe", "FileType": 2, "PlatformType": 3 }, { "Id": 189, "GameId": 1, "IsRequired": false, "FileName": "World of Warcraft Beta Launcher.exe", "FileType": 3, "PlatformType": 4 }, { "Id": 190, "GameId": 1, "IsRequired": false, "FileName": "WowT.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 191, "GameId": 1, "IsRequired": false, "FileName": "WoWT-64.exe", "FileType": 2, "PlatformType": 3 }, { "Id": 192, "GameId": 1, "IsRequired": false, "FileName": "World of Warcraft Public Test Launcher.exe", "FileType": 3, "PlatformType": 4 }, { "Id": 195, "GameId": 1, "IsRequired": false, "FileName": "World of Warcraft Beta.app", "FileType": 2, "PlatformType": 5 }, { "Id": 196, "GameId": 1, "IsRequired": false, "FileName": "World of Warcraft Public Test.app", "FileType": 2, "PlatformType": 5 } ], "GameDetectionHints": [ { "ID": 2, "HintType": 1, "HintPath": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Blizzard Entertainment\\World of Warcraft", "HintKey": "InstallPath", "HintOptions": 0 }, { "ID": 3, "HintType": 1, "HintPath": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Blizzard Entertainment\\World of Warcraft", "HintKey": "InstallPath", "HintOptions": 0 }, { "ID": 4, "HintType": 1, "HintPath": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\VirtualStore\\MACHINE\\SOFTWARE\\Blizzard Entertainment\\World of Warcraft", "HintKey": "InstallPath", "HintOptions": 0 }, { "ID": 5, "HintType": 2, "HintPath": "%PROGRAMFILES(x86)%\\World of Warcraft", "HintKey": "", "HintOptions": 0 }, { "ID": 6, "HintType": 2, "HintPath": "%PROGRAMFILES%\\World of Warcraft", "HintKey": "", "HintOptions": 0 }, { "ID": 7, "HintType": 2, "HintPath": "%Public%\\Games\\World of Warcraft", "HintKey": "", "HintOptions": 0 }, { "ID": 1014, "HintType": 2, "HintPath": "/Applications/World of Warcraft", "HintKey": "", "HintOptions": 0 }, { "ID": 1026, "HintType": 1, "HintPath": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Blizzard Entertainment\\World of Warcraft\\PTR", "HintKey": "InstallPath", "HintOptions": 0 }, { "ID": 1027, "HintType": 1, "HintPath": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Blizzard Entertainment\\World of Warcraft\\PTR", "HintKey": "InstallPath", "HintOptions": 0 }, { "ID": 1028, "HintType": 1, "HintPath": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\VirtualStore\\MACHINE\\SOFTWARE\\Blizzard Entertainment\\World of Warcraft\\PTR", "HintKey": "InstallPath", "HintOptions": 0 }, { "ID": 1034, "HintType": 2, "HintPath": "%PROGRAMFILES(x86)%\\World of Warcraft Beta", "HintKey": "", "HintOptions": 0 }, { "ID": 1035, "HintType": 2, "HintPath": "%PROGRAMFILES%\\World of Warcraft Beta", "HintKey": "", "HintOptions": 0 } ], "FileParsingRules": [ { "CommentStripPattern": "(?s)<!--.*?-->", "FileExtension": ".xml", "InclusionPattern": "(?i)<(?:Include|Script)\\s+file=[\"\"']((?:(?<!\\.\\.).)+)[\"\"']\\s*/>" }, { "CommentStripPattern": "(?m)\\s*#.*$", "FileExtension": ".toc", "InclusionPattern": "(?mi)^\\s*((?:(?<!\\.\\.).)+\\.(?:xml|lua))\\s*$" } ], "CategorySections": [ { "ID": 1, "GameID": 1, "Name": "Addons", "PackageType": 1, "Path": "interface\\addons", "InitialInclusionPattern": "(?i)^([^/]+)[\\\\/]\\1\\.toc$", "ExtraIncludePattern": "(?i)^[^/\\\\]+[/\\\\]Bindings\\.xml$" } ], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": true, "SupportsVoice": false, "Order": 12, "SupportsNotifications": true, "BundleAssets": true }, { "ID": 11, "Name": "Dungeons & Dragons Online", "Slug": "DDO", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 11, "Name": "Cover" }, { "Id": 33, "GameId": 11, "Name": "Icon16" }, { "Id": 34, "GameId": 11, "Name": "Icon24" }, { "Id": 35, "GameId": 11, "Name": "Icon32" }, { "Id": 36, "GameId": 11, "Name": "Logo" }, { "Id": 37, "GameId": 11, "Name": "CoverLogo" }, { "Id": 38, "GameId": 11, "Name": "Background" } ], "GameFiles": [], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": false, "BundleAssets": false }, { "ID": 12, "Name": "EVE Online", "Slug": "eve", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 12, "Name": "Cover" }, { "Id": 33, "GameId": 12, "Name": "Icon16" }, { "Id": 34, "GameId": 12, "Name": "Icon24" }, { "Id": 35, "GameId": 12, "Name": "Icon32" }, { "Id": 36, "GameId": 12, "Name": "Logo" }, { "Id": 37, "GameId": 12, "Name": "CoverLogo" }, { "Id": 38, "GameId": 12, "Name": "Background" } ], "GameFiles": [ { "Id": 150, "GameId": 12, "IsRequired": true, "FileName": "exefile.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 13, "Name": "EverQuest", "Slug": "eq", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 13, "Name": "Cover" }, { "Id": 33, "GameId": 13, "Name": "Icon16" }, { "Id": 34, "GameId": 13, "Name": "Icon24" }, { "Id": 35, "GameId": 13, "Name": "Icon32" }, { "Id": 36, "GameId": 13, "Name": "Logo" }, { "Id": 37, "GameId": 13, "Name": "CoverLogo" }, { "Id": 38, "GameId": 13, "Name": "Background" } ], "GameFiles": [ { "Id": 149, "GameId": 13, "IsRequired": true, "FileName": "eqgame.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 33, "Name": "<NAME>", "Slug": "lotro", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 33, "Name": "Cover" }, { "Id": 33, "GameId": 33, "Name": "Icon16" }, { "Id": 34, "GameId": 33, "Name": "Icon24" }, { "Id": 35, "GameId": 33, "Name": "Icon32" }, { "Id": 36, "GameId": 33, "Name": "Logo" }, { "Id": 37, "GameId": 33, "Name": "CoverLogo" }, { "Id": 38, "GameId": 33, "Name": "Background" } ], "GameFiles": [ { "Id": 108, "GameId": 33, "IsRequired": true, "FileName": "lotroclient.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 36, "Name": "Star Trek Online", "Slug": "startreakonline", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 36, "Name": "Cover" }, { "Id": 33, "GameId": 36, "Name": "Icon16" }, { "Id": 34, "GameId": 36, "Name": "Icon24" }, { "Id": 35, "GameId": 36, "Name": "Icon32" }, { "Id": 36, "GameId": 36, "Name": "Logo" }, { "Id": 37, "GameId": 36, "Name": "CoverLogo" }, { "Id": 38, "GameId": 36, "Name": "Background" } ], "GameFiles": [ { "Id": 85, "GameId": 36, "IsRequired": true, "FileName": "Star Trek Online.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 64, "Name": "The Secret World", "Slug": "tsw", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 64, "Name": "Cover" }, { "Id": 33, "GameId": 64, "Name": "Icon16" }, { "Id": 34, "GameId": 64, "Name": "Icon24" }, { "Id": 35, "GameId": 64, "Name": "Icon32" }, { "Id": 36, "GameId": 64, "Name": "Logo" }, { "Id": 37, "GameId": 64, "Name": "CoverLogo" }, { "Id": 38, "GameId": 64, "Name": "Background" } ], "GameFiles": [ { "Id": 260, "GameId": 64, "IsRequired": true, "FileName": "thesecretworld.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 263, "GameId": 64, "IsRequired": false, "FileName": "ClientPatcher.exe", "FileType": 3, "PlatformType": 4 } ], "GameDetectionHints": [ { "ID": 1020, "HintType": 1, "HintPath": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Funcom\\The Secret World", "HintKey": "LastInstalledClient", "HintOptions": 0 }, { "ID": 1021, "HintType": 1, "HintPath": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Funcom\\The Secret World", "HintKey": "LastInstalledClient", "HintOptions": 0 }, { "ID": 1022, "HintType": 2, "HintPath": "%PROGRAMFILES(x86)%\\The Secret World", "HintKey": "", "HintOptions": 0 }, { "ID": 1023, "HintType": 2, "HintPath": "%PROGRAMFILES%\\The Secret World", "HintKey": "", "HintOptions": 0 } ], "FileParsingRules": [], "CategorySections": [ { "ID": 14, "GameID": 64, "Name": "Mods", "PackageType": 4, "Path": "Data\\Gui\\Customized", "InitialInclusionPattern": "([^\\/\\\\]+\\.ctoc)$", "ExtraIncludePattern": "([^\\/\\\\]+\\.ctoc)$" } ], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": true, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 65, "Name": "<NAME>", "Slug": "sc2", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 65, "Name": "Cover" }, { "Id": 33, "GameId": 65, "Name": "Icon16" }, { "Id": 34, "GameId": 65, "Name": "Icon24" }, { "Id": 35, "GameId": 65, "Name": "Icon32" }, { "Id": 36, "GameId": 65, "Name": "Logo" }, { "Id": 37, "GameId": 65, "Name": "CoverLogo" }, { "Id": 38, "GameId": 65, "Name": "Background" } ], "GameFiles": [ { "Id": 38, "GameId": 65, "IsRequired": false, "FileName": "StarCraft II.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 39, "GameId": 65, "IsRequired": false, "FileName": "SC2.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 70, "Name": "9Dragons", "Slug": "9Dragons", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 70, "Name": "Cover" }, { "Id": 33, "GameId": 70, "Name": "Icon16" }, { "Id": 34, "GameId": 70, "Name": "Icon24" }, { "Id": 35, "GameId": 70, "Name": "Icon32" }, { "Id": 36, "GameId": 70, "Name": "Logo" }, { "Id": 37, "GameId": 70, "Name": "CoverLogo" }, { "Id": 38, "GameId": 70, "Name": "Background" } ], "GameFiles": [], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": false, "BundleAssets": false }, { "ID": 122, "Name": "<NAME>", "Slug": "KO", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 122, "Name": "Cover" }, { "Id": 33, "GameId": 122, "Name": "Icon16" }, { "Id": 34, "GameId": 122, "Name": "Icon24" }, { "Id": 35, "GameId": 122, "Name": "Icon32" }, { "Id": 36, "GameId": 122, "Name": "Logo" }, { "Id": 37, "GameId": 122, "Name": "CoverLogo" }, { "Id": 38, "GameId": 122, "Name": "Background" } ], "GameFiles": [ { "Id": 218, "GameId": 122, "IsRequired": true, "FileName": "KnightOnLine.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 335, "Name": "Runes of Magic", "Slug": "RoM", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 335, "Name": "Cover" }, { "Id": 33, "GameId": 335, "Name": "Icon16" }, { "Id": 34, "GameId": 335, "Name": "Icon24" }, { "Id": 35, "GameId": 335, "Name": "Icon32" }, { "Id": 36, "GameId": 335, "Name": "Logo" }, { "Id": 37, "GameId": 335, "Name": "CoverLogo" }, { "Id": 38, "GameId": 335, "Name": "Background" } ], "GameFiles": [ { "Id": 257, "GameId": 335, "IsRequired": false, "FileName": "client.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 264, "GameId": 335, "IsRequired": true, "FileName": "Runes of Magic.exe", "FileType": 3, "PlatformType": 4 } ], "GameDetectionHints": [ { "ID": 1015, "HintType": 1, "HintPath": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Frogster Interactive Pictures\\Runes of Magic", "HintKey": "RootDir", "HintOptions": 0 }, { "ID": 1016, "HintType": 2, "HintPath": "%PROGRAMFILES(x86)%\\Runes of Magic", "HintKey": "", "HintOptions": 0 }, { "ID": 1017, "HintType": 2, "HintPath": "%PROGRAMFILES%\\Runes of Magic", "HintKey": "", "HintOptions": 0 }, { "ID": 1036, "HintType": 1, "HintPath": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Runes of Magic", "HintKey": "InstallDir", "HintOptions": 0 }, { "ID": 1037, "HintType": 2, "HintPath": "%PROGRAMFILES(x86)%\\GameforgeLive\\Games\\USA_eng\\Runes Of Magic", "HintKey": "", "HintOptions": 0 }, { "ID": 1038, "HintType": 2, "HintPath": "%PROGRAMFILES%\\GameforgeLive\\Games\\USA_eng\\Runes Of Magic", "HintKey": "", "HintOptions": 0 } ], "FileParsingRules": [], "CategorySections": [ { "ID": 1, "GameID": 335, "Name": "Addons", "PackageType": 1, "Path": "interface\\addons", "InitialInclusionPattern": ".", "ExtraIncludePattern": null } ], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": true, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 339, "Name": "Star Wars: The Old Republic", "Slug": "swtor", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 339, "Name": "Cover" }, { "Id": 33, "GameId": 339, "Name": "Icon16" }, { "Id": 34, "GameId": 339, "Name": "Icon24" }, { "Id": 35, "GameId": 339, "Name": "Icon32" }, { "Id": 36, "GameId": 339, "Name": "Logo" }, { "Id": 37, "GameId": 339, "Name": "CoverLogo" }, { "Id": 38, "GameId": 339, "Name": "Background" } ], "GameFiles": [ { "Id": 65, "GameId": 339, "IsRequired": true, "FileName": "launcher.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 66, "GameId": 339, "IsRequired": true, "FileName": "brwc_swtor.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 341, "Name": "League of Legends", "Slug": "lol", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 33, "GameId": 341, "Name": "Icon16" }, { "Id": 34, "GameId": 341, "Name": "Icon24" }, { "Id": 35, "GameId": 341, "Name": "Icon32" } ], "GameFiles": [ { "Id": 8, "GameId": 341, "IsRequired": true, "FileName": "lol.launcher.exe", "FileType": 3, "PlatformType": 4 }, { "Id": 156, "GameId": 341, "IsRequired": false, "FileName": "LoLLauncher.app", "FileType": 3, "PlatformType": 5 }, { "Id": 157, "GameId": 341, "IsRequired": false, "FileName": "LeagueofLegends.app", "FileType": 2, "PlatformType": 5 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": true, "Order": 1, "SupportsNotifications": true, "BundleAssets": true }, { "ID": 391, "Name": "Final Fantasy XIV", "Slug": "ffxiv", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 391, "Name": "Cover" }, { "Id": 33, "GameId": 391, "Name": "Icon16" }, { "Id": 34, "GameId": 391, "Name": "Icon24" }, { "Id": 35, "GameId": 391, "Name": "Icon32" }, { "Id": 36, "GameId": 391, "Name": "Logo" }, { "Id": 37, "GameId": 391, "Name": "CoverLogo" }, { "Id": 38, "GameId": 391, "Name": "Background" } ], "GameFiles": [ { "Id": 184, "GameId": 391, "IsRequired": false, "FileName": "ffxiv.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 258, "GameId": 391, "IsRequired": false, "FileName": "ffxiv_dx11.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 412, "Name": "Guild Wars 2", "Slug": "gw2", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 412, "Name": "Cover" }, { "Id": 33, "GameId": 412, "Name": "Icon16" }, { "Id": 34, "GameId": 412, "Name": "Icon24" }, { "Id": 35, "GameId": 412, "Name": "Icon32" }, { "Id": 36, "GameId": 412, "Name": "Logo" }, { "Id": 37, "GameId": 412, "Name": "CoverLogo" }, { "Id": 38, "GameId": 412, "Name": "Background" } ], "GameFiles": [ { "Id": 23, "GameId": 412, "IsRequired": false, "FileName": "gw2.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 225, "GameId": 412, "IsRequired": false, "FileName": "Gw2-64.exe", "FileType": 2, "PlatformType": 3 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 414, "Name": "<NAME>", "Slug": "diablo-3", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 33, "GameId": 414, "Name": "Icon16" }, { "Id": 34, "GameId": 414, "Name": "Icon24" }, { "Id": 35, "GameId": 414, "Name": "Icon32" } ], "GameFiles": [ { "Id": 153, "GameId": 414, "IsRequired": true, "FileName": "Diablo III.app", "FileType": 2, "PlatformType": 5 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 12, "SupportsNotifications": true, "BundleAssets": true }, { "ID": 418, "Name": "<NAME>", "Slug": "APB", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 418, "Name": "Cover" }, { "Id": 33, "GameId": 418, "Name": "Icon16" }, { "Id": 34, "GameId": 418, "Name": "Icon24" }, { "Id": 35, "GameId": 418, "Name": "Icon32" }, { "Id": 36, "GameId": 418, "Name": "Logo" }, { "Id": 37, "GameId": 418, "Name": "CoverLogo" }, { "Id": 38, "GameId": 418, "Name": "Background" } ], "GameFiles": [ { "Id": 89, "GameId": 418, "IsRequired": true, "FileName": "APB.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 423, "Name": "World of Tanks", "Slug": "wot", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 423, "Name": "Cover" }, { "Id": 33, "GameId": 423, "Name": "Icon16" }, { "Id": 34, "GameId": 423, "Name": "Icon24" }, { "Id": 35, "GameId": 423, "Name": "Icon32" }, { "Id": 36, "GameId": 423, "Name": "Logo" }, { "Id": 37, "GameId": 423, "Name": "CoverLogo" }, { "Id": 38, "GameId": 423, "Name": "Background" } ], "GameFiles": [ { "Id": 18, "GameId": 423, "IsRequired": false, "FileName": "WorldOfTanks.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 265, "GameId": 423, "IsRequired": false, "FileName": "WOTLauncher.exe", "FileType": 3, "PlatformType": 4 } ], "GameDetectionHints": [ { "ID": 1024, "HintType": 2, "HintPath": "%PROGRAMFILES%\\World_of_Tanks", "HintKey": "", "HintOptions": 0 }, { "ID": 1025, "HintType": 2, "HintPath": "C:\\Games\\World_of_Tanks", "HintKey": "", "HintOptions": 0 } ], "FileParsingRules": [], "CategorySections": [ { "ID": 8, "GameID": 423, "Name": "Mods", "PackageType": 4, "Path": "res_mods\\0.9.16.0.0", "InitialInclusionPattern": ".", "ExtraIncludePattern": null }, { "ID": 9, "GameID": 423, "Name": "Skins", "PackageType": 4, "Path": "res_mods\\0.9.16.0.0", "InitialInclusionPattern": ".", "ExtraIncludePattern": null } ], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": true, "SupportsVoice": false, "Order": 10, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 424, "Name": "Rift", "Slug": "rift", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 424, "Name": "Cover" }, { "Id": 33, "GameId": 424, "Name": "Icon16" }, { "Id": 34, "GameId": 424, "Name": "Icon24" }, { "Id": 35, "GameId": 424, "Name": "Icon32" }, { "Id": 36, "GameId": 424, "Name": "Logo" }, { "Id": 37, "GameId": 424, "Name": "CoverLogo" }, { "Id": 38, "GameId": 424, "Name": "Background" } ], "GameFiles": [ { "Id": 256, "GameId": 424, "IsRequired": false, "FileName": "rift.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 259, "GameId": 424, "IsRequired": false, "FileName": "rift_x64.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 266, "GameId": 424, "IsRequired": false, "FileName": "riftpatchlive.exe", "FileType": 3, "PlatformType": 4 } ], "GameDetectionHints": [ { "ID": 1018, "HintType": 2, "HintPath": "%PROGRAMFILES(x86)%\\Rift Game", "HintKey": "", "HintOptions": 0 }, { "ID": 1019, "HintType": 2, "HintPath": "%PROGRAMFILES%\\Rift Game", "HintKey": "", "HintOptions": 0 }, { "ID": 1039, "HintType": 2, "HintPath": "%PROGRAMFILES(x86)%\\Glyph\\Games\\RIFT\\Live", "HintKey": "", "HintOptions": 0 }, { "ID": 1040, "HintType": 2, "HintPath": "%PROGRAMFILES%\\Glyph\\Games\\RIFT\\Live", "HintKey": "", "HintOptions": 0 }, { "ID": 1041, "HintType": 1, "HintPath": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Glyph RIFT", "HintKey": "Installlocation", "HintOptions": 0 } ], "FileParsingRules": [ { "CommentStripPattern": "(?m)\\s*#.*$", "FileExtension": ".toc", "InclusionPattern": "['\"](.*\\.lua)['\"]" } ], "CategorySections": [ { "ID": 1, "GameID": 424, "Name": "Addons", "PackageType": 1, "Path": "%PERSONAL%\\RIFT\\Interface\\AddOns", "InitialInclusionPattern": "(?i)^([^/]+)[\\\\/]RiftAddon\\.toc$", "ExtraIncludePattern": null } ], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": true, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 431, "Name": "Terraria", "Slug": "terraria", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 431, "Name": "Cover" }, { "Id": 33, "GameId": 431, "Name": "Icon16" }, { "Id": 34, "GameId": 431, "Name": "Icon24" }, { "Id": 35, "GameId": 431, "Name": "Icon32" }, { "Id": 36, "GameId": 431, "Name": "Logo" }, { "Id": 37, "GameId": 431, "Name": "CoverLogo" }, { "Id": 38, "GameId": 431, "Name": "Background" } ], "GameFiles": [ { "Id": 47, "GameId": 431, "IsRequired": true, "FileName": "Terraria.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 432, "Name": "Minecraft", "Slug": "mc", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 432, "Name": "Cover" }, { "Id": 33, "GameId": 432, "Name": "Icon16" }, { "Id": 34, "GameId": 432, "Name": "Icon24" }, { "Id": 35, "GameId": 432, "Name": "Icon32" }, { "Id": 36, "GameId": 432, "Name": "Logo" }, { "Id": 37, "GameId": 432, "Name": "CoverLogo" }, { "Id": 38, "GameId": 432, "Name": "Background" } ], "GameFiles": [ { "Id": 40, "GameId": 432, "IsRequired": true, "FileName": "instance.json", "FileType": 3, "PlatformType": 4 } ], "GameDetectionHints": [ { "ID": 1012, "HintType": 2, "HintPath": "%Public%\\Games\\Minecraft", "HintKey": "", "HintOptions": 0 } ], "FileParsingRules": [], "CategorySections": [ { "ID": 6, "GameID": 432, "Name": "Mods", "PackageType": 6, "Path": "mods", "InitialInclusionPattern": ".", "ExtraIncludePattern": null }, { "ID": 12, "GameID": 432, "Name": "Texture Packs", "PackageType": 3, "Path": "resourcepacks", "InitialInclusionPattern": "([^\\/\\\\]+\\.zip)$", "ExtraIncludePattern": "([^\\/\\\\]+\\.zip)$" }, { "ID": 17, "GameID": 432, "Name": "Worlds", "PackageType": 1, "Path": "saves", "InitialInclusionPattern": ".", "ExtraIncludePattern": null }, { "ID": 4471, "GameID": 432, "Name": "Modpacks", "PackageType": 5, "Path": "downloads", "InitialInclusionPattern": ".", "ExtraIncludePattern": null } ], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": true, "SupportsVoice": true, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 438, "Name": "Tropico 4", "Slug": "tropico4", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 438, "Name": "Cover" }, { "Id": 33, "GameId": 438, "Name": "Icon16" }, { "Id": 34, "GameId": 438, "Name": "Icon24" }, { "Id": 35, "GameId": 438, "Name": "Icon32" }, { "Id": 36, "GameId": 438, "Name": "Logo" }, { "Id": 37, "GameId": 438, "Name": "CoverLogo" }, { "Id": 38, "GameId": 438, "Name": "Background" } ], "GameFiles": [ { "Id": 123, "GameId": 438, "IsRequired": true, "FileName": "Tropico4.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 441, "Name": "Dragon Nest", "Slug": "dragon-nest", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 441, "Name": "Cover" }, { "Id": 33, "GameId": 441, "Name": "Icon16" }, { "Id": 34, "GameId": 441, "Name": "Icon24" }, { "Id": 35, "GameId": 441, "Name": "Icon32" }, { "Id": 36, "GameId": 441, "Name": "Logo" }, { "Id": 37, "GameId": 441, "Name": "CoverLogo" }, { "Id": 38, "GameId": 441, "Name": "Background" } ], "GameFiles": [ { "Id": 67, "GameId": 441, "IsRequired": true, "FileName": "DragonNest.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 447, "Name": "Fallout: New Vegas", "Slug": "falloutnv", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 447, "Name": "Cover" }, { "Id": 33, "GameId": 447, "Name": "Icon16" }, { "Id": 34, "GameId": 447, "Name": "Icon24" }, { "Id": 35, "GameId": 447, "Name": "Icon32" }, { "Id": 36, "GameId": 447, "Name": "Logo" }, { "Id": 37, "GameId": 447, "Name": "CoverLogo" }, { "Id": 38, "GameId": 447, "Name": "Background" } ], "GameFiles": [ { "Id": 78, "GameId": 447, "IsRequired": true, "FileName": "FalloutNV.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 448, "Name": "<NAME>", "Slug": "jc2", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 448, "Name": "Cover" }, { "Id": 33, "GameId": 448, "Name": "Icon16" }, { "Id": 34, "GameId": 448, "Name": "Icon24" }, { "Id": 35, "GameId": 448, "Name": "Icon32" }, { "Id": 36, "GameId": 448, "Name": "Logo" }, { "Id": 37, "GameId": 448, "Name": "CoverLogo" }, { "Id": 38, "GameId": 448, "Name": "Background" } ], "GameFiles": [ { "Id": 106, "GameId": 448, "IsRequired": true, "FileName": "JustCause2.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 449, "Name": "Skyrim", "Slug": "skyrim", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 449, "Name": "Cover" }, { "Id": 33, "GameId": 449, "Name": "Icon16" }, { "Id": 34, "GameId": 449, "Name": "Icon24" }, { "Id": 35, "GameId": 449, "Name": "Icon32" }, { "Id": 36, "GameId": 449, "Name": "Logo" }, { "Id": 37, "GameId": 449, "Name": "CoverLogo" }, { "Id": 38, "GameId": 449, "Name": "Background" } ], "GameFiles": [ { "Id": 25, "GameId": 449, "IsRequired": false, "FileName": "TESV.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 224, "GameId": 449, "IsRequired": false, "FileName": "SkyrimSE.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 452, "Name": "Borderlands 2", "Slug": "bl2", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 452, "Name": "Cover" }, { "Id": 33, "GameId": 452, "Name": "Icon16" }, { "Id": 34, "GameId": 452, "Name": "Icon24" }, { "Id": 35, "GameId": 452, "Name": "Icon32" }, { "Id": 36, "GameId": 452, "Name": "Logo" }, { "Id": 37, "GameId": 452, "Name": "CoverLogo" }, { "Id": 38, "GameId": 452, "Name": "Background" } ], "GameFiles": [ { "Id": 60, "GameId": 452, "IsRequired": true, "FileName": "Borderlands2.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 454, "Name": "WildStar", "Slug": "ws", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 454, "Name": "Cover" }, { "Id": 33, "GameId": 454, "Name": "Icon16" }, { "Id": 34, "GameId": 454, "Name": "Icon24" }, { "Id": 35, "GameId": 454, "Name": "Icon32" }, { "Id": 36, "GameId": 454, "Name": "Logo" }, { "Id": 37, "GameId": 454, "Name": "CoverLogo" }, { "Id": 38, "GameId": 454, "Name": "Background" } ], "GameFiles": [ { "Id": 27, "GameId": 454, "IsRequired": false, "FileName": "WildStar64.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 28, "GameId": 454, "IsRequired": false, "FileName": "WildStar32.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 262, "GameId": 454, "IsRequired": true, "FileName": "Wildstar.exe", "FileType": 3, "PlatformType": 4 } ], "GameDetectionHints": [ { "ID": 1029, "HintType": 1, "HintPath": "HKEY_CURRENT_USER\\Software\\NCSoft\\WildStar", "HintKey": "LastRun", "HintOptions": 0 }, { "ID": 1032, "HintType": 2, "HintPath": "%PROGRAMFILES%\\NCSOFT\\WildStar", "HintKey": "", "HintOptions": 0 }, { "ID": 1033, "HintType": 2, "HintPath": "%PROGRAMFILES(x86)%\\NCSOFT\\WildStar", "HintKey": "", "HintOptions": 0 } ], "FileParsingRules": [ { "CommentStripPattern": "(?s)<!--.*?-->", "FileExtension": ".xml", "InclusionPattern": "(?i)<(?:Form|Script)(?:[^>]*\\s)Name\\s*=\\s*[\"\"']([^\"\"']+)[\"\"'][^>]*/>" } ], "CategorySections": [ { "ID": 18, "GameID": 454, "Name": "Addons", "PackageType": 1, "Path": "%APPDATA%\\NCSoft\\Wildstar\\addons", "InitialInclusionPattern": "(?i)^[^/\\\\]+[/\\\\]toc\\.xml$", "ExtraIncludePattern": null } ], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": true, "SupportsVoice": false, "Order": 10, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 455, "Name": "The Elder Scrolls Online", "Slug": "teso", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 455, "Name": "Cover" }, { "Id": 33, "GameId": 455, "Name": "Icon16" }, { "Id": 34, "GameId": 455, "Name": "Icon24" }, { "Id": 35, "GameId": 455, "Name": "Icon32" }, { "Id": 36, "GameId": 455, "Name": "Logo" }, { "Id": 37, "GameId": 455, "Name": "CoverLogo" }, { "Id": 38, "GameId": 455, "Name": "Background" } ], "GameFiles": [ { "Id": 131, "GameId": 455, "IsRequired": false, "FileName": "eso.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 186, "GameId": 455, "IsRequired": false, "FileName": "eso64.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 261, "GameId": 455, "IsRequired": true, "FileName": "Launcher\\Bethesda.net_Launcher.exe", "FileType": 3, "PlatformType": 4 } ], "GameDetectionHints": [ { "ID": 1030, "HintType": 1, "HintPath": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Zenimax_Online\\Launcher", "HintKey": "InstallPath", "HintOptions": 0 }, { "ID": 1031, "HintType": 1, "HintPath": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Zenimax_Online\\Launcher", "HintKey": "InstallPath", "HintOptions": 0 } ], "FileParsingRules": [], "CategorySections": [ { "ID": 19, "GameID": 455, "Name": "Addons", "PackageType": 1, "Path": "%MYDOCUMENTS%\\Elder Scrolls Online\\live\\AddOns", "InitialInclusionPattern": ".", "ExtraIncludePattern": null } ], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": true, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 456, "Name": "Firefall", "Slug": "firefall", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 456, "Name": "Cover" }, { "Id": 33, "GameId": 456, "Name": "Icon16" }, { "Id": 34, "GameId": 456, "Name": "Icon24" }, { "Id": 35, "GameId": 456, "Name": "Icon32" }, { "Id": 36, "GameId": 456, "Name": "Logo" }, { "Id": 37, "GameId": 456, "Name": "CoverLogo" }, { "Id": 38, "GameId": 456, "Name": "Background" } ], "GameFiles": [ { "Id": 12, "GameId": 456, "IsRequired": true, "FileName": "Launcher.exe", "FileType": 3, "PlatformType": 4 }, { "Id": 13, "GameId": 456, "IsRequired": true, "FileName": "FirefallClient.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 125, "GameId": 456, "IsRequired": true, "FileName": "FirefallClient.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 457, "Name": "Strife", "Slug": "strife", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 33, "GameId": 457, "Name": "Icon16" }, { "Id": 34, "GameId": 457, "Name": "Icon24" }, { "Id": 35, "GameId": 457, "Name": "Icon32" }, { "Id": 36, "GameId": 457, "Name": "Logo" } ], "GameFiles": [], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": true, "Order": 3, "SupportsNotifications": true, "BundleAssets": true }, { "ID": 458, "Name": "SMITE", "Slug": "smite", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 33, "GameId": 458, "Name": "Icon16" }, { "Id": 34, "GameId": 458, "Name": "Icon24" }, { "Id": 35, "GameId": 458, "Name": "Icon32" } ], "GameFiles": [], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": true, "Order": 2, "SupportsNotifications": true, "BundleAssets": true }, { "ID": 459, "Name": "Hearthstone", "Slug": "hearthstone", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 459, "Name": "Cover" }, { "Id": 33, "GameId": 459, "Name": "Icon16" }, { "Id": 34, "GameId": 459, "Name": "Icon24" }, { "Id": 35, "GameId": 459, "Name": "Icon32" }, { "Id": 36, "GameId": 459, "Name": "Logo" }, { "Id": 37, "GameId": 459, "Name": "CoverLogo" }, { "Id": 38, "GameId": 459, "Name": "Background" } ], "GameFiles": [ { "Id": 14, "GameId": 459, "IsRequired": true, "FileName": "Hearthstone.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 15, "GameId": 459, "IsRequired": false, "FileName": "battle.net.dll", "FileType": 1, "PlatformType": 4 }, { "Id": 154, "GameId": 459, "IsRequired": true, "FileName": "Hearthstone.app", "FileType": 2, "PlatformType": 5 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 10, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 460, "Name": "ArcheAge", "Slug": "archeage", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 460, "Name": "Cover" }, { "Id": 33, "GameId": 460, "Name": "Icon16" }, { "Id": 34, "GameId": 460, "Name": "Icon24" }, { "Id": 35, "GameId": 460, "Name": "Icon32" }, { "Id": 36, "GameId": 460, "Name": "Logo" }, { "Id": 37, "GameId": 460, "Name": "CoverLogo" }, { "Id": 38, "GameId": 460, "Name": "Background" } ], "GameFiles": [ { "Id": 16, "GameId": 460, "IsRequired": true, "FileName": "archeage.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 461, "Name": "Team Fortress 2", "Slug": "tf2", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 461, "Name": "Cover" }, { "Id": 33, "GameId": 461, "Name": "Icon16" }, { "Id": 34, "GameId": 461, "Name": "Icon24" }, { "Id": 35, "GameId": 461, "Name": "Icon32" }, { "Id": 36, "GameId": 461, "Name": "Logo" }, { "Id": 37, "GameId": 461, "Name": "CoverLogo" }, { "Id": 38, "GameId": 461, "Name": "Background" } ], "GameFiles": [ { "Id": 51, "GameId": 461, "IsRequired": true, "FileName": "hl2.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 52, "GameId": 461, "IsRequired": true, "FileName": "tf\\resource\\tf2.ttf", "FileType": 1, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 462, "Name": "Heroes of the Storm", "Slug": "hots", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 462, "Name": "Cover" }, { "Id": 33, "GameId": 462, "Name": "Icon16" }, { "Id": 34, "GameId": 462, "Name": "Icon24" }, { "Id": 35, "GameId": 462, "Name": "Icon32" }, { "Id": 36, "GameId": 462, "Name": "Logo" }, { "Id": 37, "GameId": 462, "Name": "CoverLogo" }, { "Id": 38, "GameId": 462, "Name": "Background" } ], "GameFiles": [ { "Id": 24, "GameId": 462, "IsRequired": true, "FileName": "HeroesOfTheStorm.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 129, "GameId": 462, "IsRequired": false, "FileName": "HeroesOfTheStorm_x64.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 155, "GameId": 462, "IsRequired": true, "FileName": "Heroes.app", "FileType": 2, "PlatformType": 5 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 12, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 463, "Name": "DOTA 2", "Slug": "dota2", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 463, "Name": "Cover" }, { "Id": 33, "GameId": 463, "Name": "Icon16" }, { "Id": 34, "GameId": 463, "Name": "Icon24" }, { "Id": 35, "GameId": 463, "Name": "Icon32" }, { "Id": 36, "GameId": 463, "Name": "Logo" }, { "Id": 37, "GameId": 463, "Name": "CoverLogo" }, { "Id": 38, "GameId": 463, "Name": "Background" } ], "GameFiles": [ { "Id": 19, "GameId": 463, "IsRequired": true, "FileName": "dota2.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 464, "Name": "Civilization V", "Slug": "civiilzationV", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 464, "Name": "Cover" }, { "Id": 33, "GameId": 464, "Name": "Icon16" }, { "Id": 34, "GameId": 464, "Name": "Icon24" }, { "Id": 35, "GameId": 464, "Name": "Icon32" }, { "Id": 36, "GameId": 464, "Name": "Logo" }, { "Id": 37, "GameId": 464, "Name": "CoverLogo" }, { "Id": 38, "GameId": 464, "Name": "Background" } ], "GameFiles": [ { "Id": 20, "GameId": 464, "IsRequired": false, "FileName": "CiviilzationV.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 29, "GameId": 464, "IsRequired": false, "FileName": "CivilizationV_DX11.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 465, "Name": "Counter-Strike: GO", "Slug": "csgo", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 465, "Name": "Cover" }, { "Id": 33, "GameId": 465, "Name": "Icon16" }, { "Id": 34, "GameId": 465, "Name": "Icon24" }, { "Id": 35, "GameId": 465, "Name": "Icon32" }, { "Id": 36, "GameId": 465, "Name": "Logo" }, { "Id": 37, "GameId": 465, "Name": "CoverLogo" }, { "Id": 38, "GameId": 465, "Name": "Background" } ], "GameFiles": [ { "Id": 21, "GameId": 465, "IsRequired": true, "FileName": "csgo.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 466, "Name": "Battlefield 4", "Slug": "bf4", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 466, "Name": "Cover" }, { "Id": 33, "GameId": 466, "Name": "Icon16" }, { "Id": 34, "GameId": 466, "Name": "Icon24" }, { "Id": 35, "GameId": 466, "Name": "Icon32" }, { "Id": 36, "GameId": 466, "Name": "Logo" }, { "Id": 37, "GameId": 466, "Name": "CoverLogo" }, { "Id": 38, "GameId": 466, "Name": "Background" } ], "GameFiles": [ { "Id": 22, "GameId": 466, "IsRequired": true, "FileName": "bf4.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 467, "Name": "<NAME>", "Slug": "poe", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 467, "Name": "Cover" }, { "Id": 33, "GameId": 467, "Name": "Icon16" }, { "Id": 34, "GameId": 467, "Name": "Icon24" }, { "Id": 35, "GameId": 467, "Name": "Icon32" }, { "Id": 36, "GameId": 467, "Name": "Logo" }, { "Id": 37, "GameId": 467, "Name": "CoverLogo" }, { "Id": 38, "GameId": 467, "Name": "Background" } ], "GameFiles": [ { "Id": 26, "GameId": 467, "IsRequired": false, "FileName": "PathOfExile.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 167, "GameId": 467, "IsRequired": false, "FileName": "PathOfExileSteam.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 468, "Name": "DayZ", "Slug": "dayz", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 468, "Name": "Cover" }, { "Id": 33, "GameId": 468, "Name": "Icon16" }, { "Id": 34, "GameId": 468, "Name": "Icon24" }, { "Id": 35, "GameId": 468, "Name": "Icon32" }, { "Id": 36, "GameId": 468, "Name": "Logo" }, { "Id": 37, "GameId": 468, "Name": "CoverLogo" }, { "Id": 38, "GameId": 468, "Name": "Background" } ], "GameFiles": [ { "Id": 17, "GameId": 468, "IsRequired": true, "FileName": "dayz.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 469, "Name": "<NAME>", "Slug": "som", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 469, "Name": "Cover" }, { "Id": 33, "GameId": 469, "Name": "Icon16" }, { "Id": 34, "GameId": 469, "Name": "Icon24" }, { "Id": 35, "GameId": 469, "Name": "Icon32" }, { "Id": 36, "GameId": 469, "Name": "Logo" }, { "Id": 37, "GameId": 469, "Name": "CoverLogo" }, { "Id": 38, "GameId": 469, "Name": "Background" } ], "GameFiles": [ { "Id": 30, "GameId": 469, "IsRequired": true, "FileName": "ShadowOfMordor.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 470, "Name": "Life is Feudal", "Slug": "lif", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 470, "Name": "Cover" }, { "Id": 33, "GameId": 470, "Name": "Icon16" }, { "Id": 34, "GameId": 470, "Name": "Icon24" }, { "Id": 35, "GameId": 470, "Name": "Icon32" }, { "Id": 36, "GameId": 470, "Name": "Logo" }, { "Id": 37, "GameId": 470, "Name": "CoverLogo" }, { "Id": 38, "GameId": 470, "Name": "Background" } ], "GameFiles": [ { "Id": 31, "GameId": 470, "IsRequired": true, "FileName": "yo_cm_client.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 12, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 471, "Name": "Warframe", "Slug": "warframe", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 471, "Name": "Cover" }, { "Id": 33, "GameId": 471, "Name": "Icon16" }, { "Id": 34, "GameId": 471, "Name": "Icon24" }, { "Id": 35, "GameId": 471, "Name": "Icon32" }, { "Id": 36, "GameId": 471, "Name": "Logo" }, { "Id": 37, "GameId": 471, "Name": "CoverLogo" }, { "Id": 38, "GameId": 471, "Name": "Background" } ], "GameFiles": [ { "Id": 32, "GameId": 471, "IsRequired": false, "FileName": "Warframe.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 33, "GameId": 471, "IsRequired": false, "FileName": "Warframe.x64.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 12, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 472, "Name": "Borderlands: The Pre-Sequel!", "Slug": "blps", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 472, "Name": "Cover" }, { "Id": 33, "GameId": 472, "Name": "Icon16" }, { "Id": 34, "GameId": 472, "Name": "Icon24" }, { "Id": 35, "GameId": 472, "Name": "Icon32" }, { "Id": 36, "GameId": 472, "Name": "Logo" }, { "Id": 37, "GameId": 472, "Name": "CoverLogo" }, { "Id": 38, "GameId": 472, "Name": "Background" } ], "GameFiles": [ { "Id": 34, "GameId": 472, "IsRequired": true, "FileName": "BorderlandsPreSequel.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 473, "Name": "Evolve", "Slug": "eolve", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 473, "Name": "Cover" }, { "Id": 33, "GameId": 473, "Name": "Icon16" }, { "Id": 34, "GameId": 473, "Name": "Icon24" }, { "Id": 35, "GameId": 473, "Name": "Icon32" }, { "Id": 36, "GameId": 473, "Name": "Logo" }, { "Id": 37, "GameId": 473, "Name": "CoverLogo" }, { "Id": 38, "GameId": 473, "Name": "Background" } ], "GameFiles": [ { "Id": 35, "GameId": 473, "IsRequired": true, "FileName": "Evolve.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 474, "Name": "Company of Heroes 2", "Slug": "CoH2", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 474, "Name": "Cover" }, { "Id": 33, "GameId": 474, "Name": "Icon16" }, { "Id": 34, "GameId": 474, "Name": "Icon24" }, { "Id": 35, "GameId": 474, "Name": "Icon32" }, { "Id": 36, "GameId": 474, "Name": "Logo" }, { "Id": 37, "GameId": 474, "Name": "CoverLogo" }, { "Id": 38, "GameId": 474, "Name": "Background" } ], "GameFiles": [ { "Id": 228, "GameId": 474, "IsRequired": true, "FileName": "RelicCoH2.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 475, "Name": "Call of Duty: Black Ops II", "Slug": "codbops2", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 475, "Name": "Cover" }, { "Id": 33, "GameId": 475, "Name": "Icon16" }, { "Id": 34, "GameId": 475, "Name": "Icon24" }, { "Id": 35, "GameId": 475, "Name": "Icon32" }, { "Id": 36, "GameId": 475, "Name": "Logo" }, { "Id": 37, "GameId": 475, "Name": "CoverLogo" }, { "Id": 38, "GameId": 475, "Name": "Background" } ], "GameFiles": [ { "Id": 57, "GameId": 475, "IsRequired": true, "FileName": "t6sp.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 476, "Name": "Unturned", "Slug": "unturned", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 476, "Name": "Cover" }, { "Id": 33, "GameId": 476, "Name": "Icon16" }, { "Id": 34, "GameId": 476, "Name": "Icon24" }, { "Id": 35, "GameId": 476, "Name": "Icon32" }, { "Id": 36, "GameId": 476, "Name": "Logo" }, { "Id": 37, "GameId": 476, "Name": "CoverLogo" }, { "Id": 38, "GameId": 476, "Name": "Background" } ], "GameFiles": [ { "Id": 49, "GameId": 476, "IsRequired": true, "FileName": "Unturned.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 477, "Name": "War Thunder", "Slug": "war-thunder", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 477, "Name": "Cover" }, { "Id": 33, "GameId": 477, "Name": "Icon16" }, { "Id": 34, "GameId": 477, "Name": "Icon24" }, { "Id": 35, "GameId": 477, "Name": "Icon32" }, { "Id": 36, "GameId": 477, "Name": "Logo" }, { "Id": 37, "GameId": 477, "Name": "CoverLogo" }, { "Id": 38, "GameId": 477, "Name": "Background" } ], "GameFiles": [ { "Id": 58, "GameId": 477, "IsRequired": true, "FileName": "launcher.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 59, "GameId": 477, "IsRequired": true, "FileName": "warthunder.yup", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 478, "Name": "<NAME>", "Slug": "arma3", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 478, "Name": "Cover" }, { "Id": 33, "GameId": 478, "Name": "Icon16" }, { "Id": 34, "GameId": 478, "Name": "Icon24" }, { "Id": 35, "GameId": 478, "Name": "Icon32" }, { "Id": 36, "GameId": 478, "Name": "Logo" }, { "Id": 37, "GameId": 478, "Name": "CoverLogo" }, { "Id": 38, "GameId": 478, "Name": "Background" } ], "GameFiles": [ { "Id": 61, "GameId": 478, "IsRequired": true, "FileName": "arma3.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 479, "Name": "XCOM: Enemy Unknown", "Slug": "xcom", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 479, "Name": "Cover" }, { "Id": 33, "GameId": 479, "Name": "Icon16" }, { "Id": 34, "GameId": 479, "Name": "Icon24" }, { "Id": 35, "GameId": 479, "Name": "Icon32" }, { "Id": 36, "GameId": 479, "Name": "Logo" }, { "Id": 37, "GameId": 479, "Name": "CoverLogo" }, { "Id": 38, "GameId": 479, "Name": "Background" } ], "GameFiles": [ { "Id": 62, "GameId": 479, "IsRequired": true, "FileName": "XComGame.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 480, "Name": "Robocraft", "Slug": "robocraft", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 480, "Name": "Cover" }, { "Id": 33, "GameId": 480, "Name": "Icon16" }, { "Id": 34, "GameId": 480, "Name": "Icon24" }, { "Id": 35, "GameId": 480, "Name": "Icon32" }, { "Id": 36, "GameId": 480, "Name": "Logo" }, { "Id": 37, "GameId": 480, "Name": "CoverLogo" }, { "Id": 38, "GameId": 480, "Name": "Background" } ], "GameFiles": [ { "Id": 45, "GameId": 480, "IsRequired": false, "FileName": "Robocraft.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 46, "GameId": 480, "IsRequired": false, "FileName": "RobocraftClient.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 158, "GameId": 480, "IsRequired": true, "FileName": "Robocraft.app", "FileType": 2, "PlatformType": 5 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 481, "Name": "Total War: ROME II", "Slug": "rome2", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 481, "Name": "Cover" }, { "Id": 33, "GameId": 481, "Name": "Icon16" }, { "Id": 34, "GameId": 481, "Name": "Icon24" }, { "Id": 35, "GameId": 481, "Name": "Icon32" }, { "Id": 36, "GameId": 481, "Name": "Logo" }, { "Id": 37, "GameId": 481, "Name": "CoverLogo" }, { "Id": 38, "GameId": 481, "Name": "Background" } ], "GameFiles": [ { "Id": 50, "GameId": 481, "IsRequired": true, "FileName": "Rome2.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 482, "Name": "PAYDAY: The Heist", "Slug": "payday", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 482, "Name": "Cover" }, { "Id": 33, "GameId": 482, "Name": "Icon16" }, { "Id": 34, "GameId": 482, "Name": "Icon24" }, { "Id": 35, "GameId": 482, "Name": "Icon32" }, { "Id": 36, "GameId": 482, "Name": "Logo" }, { "Id": 37, "GameId": 482, "Name": "CoverLogo" }, { "Id": 38, "GameId": 482, "Name": "Background" } ], "GameFiles": [ { "Id": 63, "GameId": 482, "IsRequired": true, "FileName": "payday_win32_release.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 483, "Name": "Counter-Strike: Source", "Slug": "css", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 483, "Name": "Cover" }, { "Id": 33, "GameId": 483, "Name": "Icon16" }, { "Id": 34, "GameId": 483, "Name": "Icon24" }, { "Id": 35, "GameId": 483, "Name": "Icon32" }, { "Id": 36, "GameId": 483, "Name": "Logo" }, { "Id": 37, "GameId": 483, "Name": "CoverLogo" }, { "Id": 38, "GameId": 483, "Name": "Background" } ], "GameFiles": [ { "Id": 53, "GameId": 483, "IsRequired": true, "FileName": "hl2.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 54, "GameId": 483, "IsRequired": true, "FileName": "cstrike\\resource\\cstrike.ttf", "FileType": 1, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 484, "Name": "<NAME>", "Slug": "gmod", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 484, "Name": "Cover" }, { "Id": 33, "GameId": 484, "Name": "Icon16" }, { "Id": 34, "GameId": 484, "Name": "Icon24" }, { "Id": 35, "GameId": 484, "Name": "Icon32" }, { "Id": 36, "GameId": 484, "Name": "Logo" }, { "Id": 37, "GameId": 484, "Name": "CoverLogo" }, { "Id": 38, "GameId": 484, "Name": "Background" } ], "GameFiles": [ { "Id": 55, "GameId": 484, "IsRequired": true, "FileName": "hl2.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 56, "GameId": 484, "IsRequired": true, "FileName": "garrysmod\\garrysmod.ver", "FileType": 1, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 487, "Name": "PAYDAY 2", "Slug": "payday2", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 487, "Name": "Cover" }, { "Id": 33, "GameId": 487, "Name": "Icon16" }, { "Id": 34, "GameId": 487, "Name": "Icon24" }, { "Id": 35, "GameId": 487, "Name": "Icon32" }, { "Id": 36, "GameId": 487, "Name": "Logo" }, { "Id": 37, "GameId": 487, "Name": "CoverLogo" }, { "Id": 38, "GameId": 487, "Name": "Background" } ], "GameFiles": [ { "Id": 64, "GameId": 487, "IsRequired": true, "FileName": "payday2_win32_release.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 488, "Name": "Civilization: Beyond Earth", "Slug": "civbe", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 488, "Name": "Cover" }, { "Id": 33, "GameId": 488, "Name": "Icon16" }, { "Id": 34, "GameId": 488, "Name": "Icon24" }, { "Id": 35, "GameId": 488, "Name": "Icon32" }, { "Id": 36, "GameId": 488, "Name": "Logo" }, { "Id": 37, "GameId": 488, "Name": "CoverLogo" }, { "Id": 38, "GameId": 488, "Name": "Background" } ], "GameFiles": [ { "Id": 36, "GameId": 488, "IsRequired": false, "FileName": "CivilizationBE_DX11.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 37, "GameId": 488, "IsRequired": false, "FileName": "CivilizationBE_Mantle.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 489, "Name": "<NAME>", "Slug": "fifa15", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 489, "Name": "Cover" }, { "Id": 33, "GameId": 489, "Name": "Icon16" }, { "Id": 34, "GameId": 489, "Name": "Icon24" }, { "Id": 35, "GameId": 489, "Name": "Icon32" }, { "Id": 36, "GameId": 489, "Name": "Logo" }, { "Id": 37, "GameId": 489, "Name": "CoverLogo" }, { "Id": 38, "GameId": 489, "Name": "Background" } ], "GameFiles": [ { "Id": 141, "GameId": 489, "IsRequired": true, "FileName": "fifa15.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 490, "Name": "Call of Duty: Advanced Warfare", "Slug": "codaw", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 490, "Name": "Cover" }, { "Id": 33, "GameId": 490, "Name": "Icon16" }, { "Id": 34, "GameId": 490, "Name": "Icon24" }, { "Id": 35, "GameId": 490, "Name": "Icon32" }, { "Id": 36, "GameId": 490, "Name": "Logo" }, { "Id": 37, "GameId": 490, "Name": "CoverLogo" }, { "Id": 38, "GameId": 490, "Name": "Background" } ], "GameFiles": [ { "Id": 41, "GameId": 490, "IsRequired": false, "FileName": "s1_mp64_ship.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 42, "GameId": 490, "IsRequired": false, "FileName": "s1_sp64_ship.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 491, "Name": "Dragon Age: Inquisition", "Slug": "dai", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 491, "Name": "Cover" }, { "Id": 33, "GameId": 491, "Name": "Icon16" }, { "Id": 34, "GameId": 491, "Name": "Icon24" }, { "Id": 35, "GameId": 491, "Name": "Icon32" }, { "Id": 36, "GameId": 491, "Name": "Logo" }, { "Id": 37, "GameId": 491, "Name": "CoverLogo" }, { "Id": 38, "GameId": 491, "Name": "Background" } ], "GameFiles": [ { "Id": 43, "GameId": 491, "IsRequired": true, "FileName": "DragonAgeInquisition.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 492, "Name": "Rust", "Slug": "rust", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 492, "Name": "Cover" }, { "Id": 33, "GameId": 492, "Name": "Icon16" }, { "Id": 34, "GameId": 492, "Name": "Icon24" }, { "Id": 35, "GameId": 492, "Name": "Icon32" }, { "Id": 36, "GameId": 492, "Name": "Logo" }, { "Id": 37, "GameId": 492, "Name": "CoverLogo" }, { "Id": 38, "GameId": 492, "Name": "Background" } ], "GameFiles": [ { "Id": 48, "GameId": 492, "IsRequired": true, "FileName": "RustClient.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 493, "Name": "Left 4 Dead 2", "Slug": "l4d2", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 493, "Name": "Cover" }, { "Id": 33, "GameId": 493, "Name": "Icon16" }, { "Id": 34, "GameId": 493, "Name": "Icon24" }, { "Id": 35, "GameId": 493, "Name": "Icon32" }, { "Id": 36, "GameId": 493, "Name": "Logo" }, { "Id": 37, "GameId": 493, "Name": "CoverLogo" }, { "Id": 38, "GameId": 493, "Name": "Background" } ], "GameFiles": [ { "Id": 44, "GameId": 493, "IsRequired": true, "FileName": "left4dead2.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 495, "Name": "<NAME>", "Slug": "farcry4", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 495, "Name": "Cover" }, { "Id": 33, "GameId": 495, "Name": "Icon16" }, { "Id": 34, "GameId": 495, "Name": "Icon24" }, { "Id": 35, "GameId": 495, "Name": "Icon32" }, { "Id": 36, "GameId": 495, "Name": "Logo" }, { "Id": 37, "GameId": 495, "Name": "CoverLogo" }, { "Id": 38, "GameId": 495, "Name": "Background" } ], "GameFiles": [ { "Id": 68, "GameId": 495, "IsRequired": true, "FileName": "FarCry4.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 496, "Name": "Grand Theft Auto V", "Slug": "gta5", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 496, "Name": "Cover" }, { "Id": 33, "GameId": 496, "Name": "Icon16" }, { "Id": 34, "GameId": 496, "Name": "Icon24" }, { "Id": 35, "GameId": 496, "Name": "Icon32" }, { "Id": 36, "GameId": 496, "Name": "Logo" }, { "Id": 37, "GameId": 496, "Name": "CoverLogo" }, { "Id": 38, "GameId": 496, "Name": "Background" } ], "GameFiles": [ { "Id": 145, "GameId": 496, "IsRequired": true, "FileName": "GTA5.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 497, "Name": "Binding of Isaac Rebirth", "Slug": "isaac", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 497, "Name": "Cover" }, { "Id": 33, "GameId": 497, "Name": "Icon16" }, { "Id": 34, "GameId": 497, "Name": "Icon24" }, { "Id": 35, "GameId": 497, "Name": "Icon32" }, { "Id": 36, "GameId": 497, "Name": "Logo" }, { "Id": 37, "GameId": 497, "Name": "CoverLogo" }, { "Id": 38, "GameId": 497, "Name": "Background" } ], "GameFiles": [ { "Id": 69, "GameId": 497, "IsRequired": true, "FileName": "isaac-ng.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 498, "Name": "Arma 2 Operation Arrowhead", "Slug": "arma2oa", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 498, "Name": "Cover" }, { "Id": 33, "GameId": 498, "Name": "Icon16" }, { "Id": 34, "GameId": 498, "Name": "Icon24" }, { "Id": 35, "GameId": 498, "Name": "Icon32" }, { "Id": 36, "GameId": 498, "Name": "Logo" }, { "Id": 37, "GameId": 498, "Name": "CoverLogo" }, { "Id": 38, "GameId": 498, "Name": "Background" } ], "GameFiles": [ { "Id": 70, "GameId": 498, "IsRequired": true, "FileName": "ArmA2OA.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 499, "Name": "Heroes & Generals", "Slug": "heroesgenerals", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 499, "Name": "Cover" }, { "Id": 33, "GameId": 499, "Name": "Icon16" }, { "Id": 34, "GameId": 499, "Name": "Icon24" }, { "Id": 35, "GameId": 499, "Name": "Icon32" }, { "Id": 36, "GameId": 499, "Name": "Logo" }, { "Id": 37, "GameId": 499, "Name": "CoverLogo" }, { "Id": 38, "GameId": 499, "Name": "Background" } ], "GameFiles": [ { "Id": 71, "GameId": 499, "IsRequired": false, "FileName": "HeroesAndGeneralsDesktop.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 72, "GameId": 499, "IsRequired": false, "FileName": "hng.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 500, "Name": "Mount and Blade Warband", "Slug": "mbwar", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 500, "Name": "Cover" }, { "Id": 33, "GameId": 500, "Name": "Icon16" }, { "Id": 34, "GameId": 500, "Name": "Icon24" }, { "Id": 35, "GameId": 500, "Name": "Icon32" }, { "Id": 36, "GameId": 500, "Name": "Logo" }, { "Id": 37, "GameId": 500, "Name": "CoverLogo" }, { "Id": 38, "GameId": 500, "Name": "Background" } ], "GameFiles": [ { "Id": 73, "GameId": 500, "IsRequired": true, "FileName": "mb_warband.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 501, "Name": "This War of Mine", "Slug": "twom", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 501, "Name": "Cover" }, { "Id": 33, "GameId": 501, "Name": "Icon16" }, { "Id": 34, "GameId": 501, "Name": "Icon24" }, { "Id": 35, "GameId": 501, "Name": "Icon32" }, { "Id": 36, "GameId": 501, "Name": "Logo" }, { "Id": 37, "GameId": 501, "Name": "CoverLogo" }, { "Id": 38, "GameId": 501, "Name": "Background" } ], "GameFiles": [ { "Id": 74, "GameId": 501, "IsRequired": true, "FileName": "This War of Mine.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 502, "Name": "Counter-Strike Nexon: Zombies", "Slug": "csonline", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 502, "Name": "Cover" }, { "Id": 33, "GameId": 502, "Name": "Icon16" }, { "Id": 34, "GameId": 502, "Name": "Icon24" }, { "Id": 35, "GameId": 502, "Name": "Icon32" }, { "Id": 36, "GameId": 502, "Name": "Logo" }, { "Id": 37, "GameId": 502, "Name": "CoverLogo" }, { "Id": 38, "GameId": 502, "Name": "Background" } ], "GameFiles": [ { "Id": 75, "GameId": 502, "IsRequired": true, "FileName": "cstrike-online.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 503, "Name": "Cube World", "Slug": "cubeworld", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 503, "Name": "Cover" }, { "Id": 33, "GameId": 503, "Name": "Icon16" }, { "Id": 34, "GameId": 503, "Name": "Icon24" }, { "Id": 35, "GameId": 503, "Name": "Icon32" }, { "Id": 36, "GameId": 503, "Name": "Logo" }, { "Id": 37, "GameId": 503, "Name": "CoverLogo" }, { "Id": 38, "GameId": 503, "Name": "Background" } ], "GameFiles": [ { "Id": 76, "GameId": 503, "IsRequired": true, "FileName": "Cube.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 504, "Name": "Euro Truck Simulator 2", "Slug": "eurotrucks2", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 504, "Name": "Cover" }, { "Id": 33, "GameId": 504, "Name": "Icon16" }, { "Id": 34, "GameId": 504, "Name": "Icon24" }, { "Id": 35, "GameId": 504, "Name": "Icon32" }, { "Id": 36, "GameId": 504, "Name": "Logo" }, { "Id": 37, "GameId": 504, "Name": "CoverLogo" }, { "Id": 38, "GameId": 504, "Name": "Background" } ], "GameFiles": [ { "Id": 77, "GameId": 504, "IsRequired": true, "FileName": "eurotrucks2.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 505, "Name": "Infinite Crisis", "Slug": "infinite-crisis", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 505, "Name": "Cover" }, { "Id": 33, "GameId": 505, "Name": "Icon16" }, { "Id": 34, "GameId": 505, "Name": "Icon24" }, { "Id": 35, "GameId": 505, "Name": "Icon32" }, { "Id": 36, "GameId": 505, "Name": "Logo" }, { "Id": 37, "GameId": 505, "Name": "CoverLogo" }, { "Id": 38, "GameId": 505, "Name": "Background" } ], "GameFiles": [ { "Id": 79, "GameId": 505, "IsRequired": true, "FileName": "InfiniteCrisis.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 506, "Name": "Insurgency", "Slug": "insurgency", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 506, "Name": "Cover" }, { "Id": 33, "GameId": 506, "Name": "Icon16" }, { "Id": 34, "GameId": 506, "Name": "Icon24" }, { "Id": 35, "GameId": 506, "Name": "Icon32" }, { "Id": 36, "GameId": 506, "Name": "Logo" }, { "Id": 37, "GameId": 506, "Name": "CoverLogo" }, { "Id": 38, "GameId": 506, "Name": "Background" } ], "GameFiles": [ { "Id": 80, "GameId": 506, "IsRequired": true, "FileName": "insurgency.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 507, "Name": "Kerbal Space Program", "Slug": "ksp", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 507, "Name": "Cover" }, { "Id": 33, "GameId": 507, "Name": "Icon16" }, { "Id": 34, "GameId": 507, "Name": "Icon24" }, { "Id": 35, "GameId": 507, "Name": "Icon32" }, { "Id": 36, "GameId": 507, "Name": "Logo" }, { "Id": 37, "GameId": 507, "Name": "CoverLogo" }, { "Id": 38, "GameId": 507, "Name": "Background" } ], "GameFiles": [ { "Id": 81, "GameId": 507, "IsRequired": false, "FileName": "ksp.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 82, "GameId": 507, "IsRequired": false, "FileName": "KSP_x64.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 508, "Name": "Neverwinter", "Slug": "neverwinter", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 508, "Name": "Cover" }, { "Id": 33, "GameId": 508, "Name": "Icon16" }, { "Id": 34, "GameId": 508, "Name": "Icon24" }, { "Id": 35, "GameId": 508, "Name": "Icon32" }, { "Id": 36, "GameId": 508, "Name": "Logo" }, { "Id": 37, "GameId": 508, "Name": "CoverLogo" }, { "Id": 38, "GameId": 508, "Name": "Background" } ], "GameFiles": [ { "Id": 83, "GameId": 508, "IsRequired": true, "FileName": "Neverwinter.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 509, "Name": "Titanfall", "Slug": "titanfall", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 509, "Name": "Cover" }, { "Id": 33, "GameId": 509, "Name": "Icon16" }, { "Id": 34, "GameId": 509, "Name": "Icon24" }, { "Id": 35, "GameId": 509, "Name": "Icon32" }, { "Id": 36, "GameId": 509, "Name": "Logo" }, { "Id": 37, "GameId": 509, "Name": "CoverLogo" }, { "Id": 38, "GameId": 509, "Name": "Background" } ], "GameFiles": [ { "Id": 84, "GameId": 509, "IsRequired": true, "FileName": "Titanfall.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 510, "Name": "The Sims 4", "Slug": "sims4", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 510, "Name": "Cover" }, { "Id": 33, "GameId": 510, "Name": "Icon16" }, { "Id": 34, "GameId": 510, "Name": "Icon24" }, { "Id": 35, "GameId": 510, "Name": "Icon32" }, { "Id": 36, "GameId": 510, "Name": "Logo" }, { "Id": 37, "GameId": 510, "Name": "CoverLogo" }, { "Id": 38, "GameId": 510, "Name": "Background" } ], "GameFiles": [ { "Id": 86, "GameId": 510, "IsRequired": true, "FileName": "TS4.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 540, "Name": "7 Days to Die", "Slug": "7days", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 540, "Name": "Cover" }, { "Id": 33, "GameId": 540, "Name": "Icon16" }, { "Id": 34, "GameId": 540, "Name": "Icon24" }, { "Id": 35, "GameId": 540, "Name": "Icon32" }, { "Id": 36, "GameId": 540, "Name": "Logo" }, { "Id": 37, "GameId": 540, "Name": "CoverLogo" }, { "Id": 38, "GameId": 540, "Name": "Background" } ], "GameFiles": [ { "Id": 87, "GameId": 540, "IsRequired": true, "FileName": "7DaysToDie.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 541, "Name": "BioShock Infinite", "Slug": "bioshock-infinite", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 541, "Name": "Cover" }, { "Id": 33, "GameId": 541, "Name": "Icon16" }, { "Id": 34, "GameId": 541, "Name": "Icon24" }, { "Id": 35, "GameId": 541, "Name": "Icon32" }, { "Id": 36, "GameId": 541, "Name": "Logo" }, { "Id": 37, "GameId": 541, "Name": "CoverLogo" }, { "Id": 38, "GameId": 541, "Name": "Background" } ], "GameFiles": [ { "Id": 90, "GameId": 541, "IsRequired": true, "FileName": "BioShockInfinite.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 542, "Name": "Call of Duty Black Ops 2 Zombies", "Slug": "cod-blackops2-zombies", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 542, "Name": "Cover" }, { "Id": 33, "GameId": 542, "Name": "Icon16" }, { "Id": 34, "GameId": 542, "Name": "Icon24" }, { "Id": 35, "GameId": 542, "Name": "Icon32" }, { "Id": 36, "GameId": 542, "Name": "Logo" }, { "Id": 37, "GameId": 542, "Name": "CoverLogo" }, { "Id": 38, "GameId": 542, "Name": "Background" } ], "GameFiles": [ { "Id": 94, "GameId": 542, "IsRequired": true, "FileName": "t6zm.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 543, "Name": "Call of Duty Black Ops", "Slug": "cod-blackops", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 543, "Name": "Cover" }, { "Id": 33, "GameId": 543, "Name": "Icon16" }, { "Id": 34, "GameId": 543, "Name": "Icon24" }, { "Id": 35, "GameId": 543, "Name": "Icon32" }, { "Id": 36, "GameId": 543, "Name": "Logo" }, { "Id": 37, "GameId": 543, "Name": "CoverLogo" }, { "Id": 38, "GameId": 543, "Name": "Background" } ], "GameFiles": [ { "Id": 91, "GameId": 543, "IsRequired": true, "FileName": "BlackOps.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 92, "GameId": 543, "IsRequired": true, "FileName": "BlackOpsMP.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 545, "Name": "Chivalry", "Slug": "chivalry", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 545, "Name": "Cover" }, { "Id": 33, "GameId": 545, "Name": "Icon16" }, { "Id": 34, "GameId": 545, "Name": "Icon24" }, { "Id": 35, "GameId": 545, "Name": "Icon32" }, { "Id": 36, "GameId": 545, "Name": "Logo" }, { "Id": 37, "GameId": 545, "Name": "CoverLogo" }, { "Id": 38, "GameId": 545, "Name": "Background" } ], "GameFiles": [ { "Id": 95, "GameId": 545, "IsRequired": true, "FileName": "CMW.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 547, "Name": "<NAME>", "Slug": "chivalry", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 547, "Name": "Cover" }, { "Id": 33, "GameId": 547, "Name": "Icon16" }, { "Id": 34, "GameId": 547, "Name": "Icon24" }, { "Id": 35, "GameId": 547, "Name": "Icon32" }, { "Id": 36, "GameId": 547, "Name": "Logo" }, { "Id": 37, "GameId": 547, "Name": "CoverLogo" }, { "Id": 38, "GameId": 547, "Name": "Background" } ], "GameFiles": [ { "Id": 96, "GameId": 547, "IsRequired": true, "FileName": "CK2game.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 548, "Name": "<NAME>", "Slug": "dark-souls", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 548, "Name": "Cover" }, { "Id": 33, "GameId": 548, "Name": "Icon16" }, { "Id": 34, "GameId": 548, "Name": "Icon24" }, { "Id": 35, "GameId": 548, "Name": "Icon32" }, { "Id": 36, "GameId": 548, "Name": "Logo" }, { "Id": 37, "GameId": 548, "Name": "CoverLogo" }, { "Id": 38, "GameId": 548, "Name": "Background" } ], "GameFiles": [ { "Id": 97, "GameId": 548, "IsRequired": true, "FileName": "DARKSOULS.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 549, "Name": "Dark Souls 2", "Slug": "dark-souls2", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 549, "Name": "Cover" }, { "Id": 33, "GameId": 549, "Name": "Icon16" }, { "Id": 34, "GameId": 549, "Name": "Icon24" }, { "Id": 35, "GameId": 549, "Name": "Icon32" }, { "Id": 36, "GameId": 549, "Name": "Logo" }, { "Id": 37, "GameId": 549, "Name": "CoverLogo" }, { "Id": 38, "GameId": 549, "Name": "Background" } ], "GameFiles": [ { "Id": 98, "GameId": 549, "IsRequired": true, "FileName": "DarkSoulsII.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 551, "Name": "DC Universe Online", "Slug": "dc-online", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 551, "Name": "Cover" }, { "Id": 33, "GameId": 551, "Name": "Icon16" }, { "Id": 34, "GameId": 551, "Name": "Icon24" }, { "Id": 35, "GameId": 551, "Name": "Icon32" }, { "Id": 36, "GameId": 551, "Name": "Logo" }, { "Id": 37, "GameId": 551, "Name": "CoverLogo" }, { "Id": 38, "GameId": 551, "Name": "Background" } ], "GameFiles": [ { "Id": 126, "GameId": 551, "IsRequired": true, "FileName": "DCGAME.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 552, "Name": "Defiance", "Slug": "defiance", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 552, "Name": "Cover" }, { "Id": 33, "GameId": 552, "Name": "Icon16" }, { "Id": 34, "GameId": 552, "Name": "Icon24" }, { "Id": 35, "GameId": 552, "Name": "Icon32" }, { "Id": 36, "GameId": 552, "Name": "Logo" }, { "Id": 37, "GameId": 552, "Name": "CoverLogo" }, { "Id": 38, "GameId": 552, "Name": "Background" } ], "GameFiles": [ { "Id": 99, "GameId": 552, "IsRequired": true, "FileName": "Defiance.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 553, "Name": "Distance", "Slug": "Distance", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 553, "Name": "Cover" }, { "Id": 33, "GameId": 553, "Name": "Icon16" }, { "Id": 34, "GameId": 553, "Name": "Icon24" }, { "Id": 35, "GameId": 553, "Name": "Icon32" }, { "Id": 36, "GameId": 553, "Name": "Logo" }, { "Id": 37, "GameId": 553, "Name": "CoverLogo" }, { "Id": 38, "GameId": 553, "Name": "Background" } ], "GameFiles": [ { "Id": 100, "GameId": 553, "IsRequired": true, "FileName": "Distance.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 554, "Name": "FTL", "Slug": "FTL", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 554, "Name": "Cover" }, { "Id": 33, "GameId": 554, "Name": "Icon16" }, { "Id": 34, "GameId": 554, "Name": "Icon24" }, { "Id": 35, "GameId": 554, "Name": "Icon32" }, { "Id": 36, "GameId": 554, "Name": "Logo" }, { "Id": 37, "GameId": 554, "Name": "CoverLogo" }, { "Id": 38, "GameId": 554, "Name": "Background" } ], "GameFiles": [ { "Id": 101, "GameId": 554, "IsRequired": true, "FileName": "FTLGame.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 555, "Name": "Goat Simulator", "Slug": "goat-simulator", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 555, "Name": "Cover" }, { "Id": 33, "GameId": 555, "Name": "Icon16" }, { "Id": 34, "GameId": 555, "Name": "Icon24" }, { "Id": 35, "GameId": 555, "Name": "Icon32" }, { "Id": 36, "GameId": 555, "Name": "Logo" }, { "Id": 37, "GameId": 555, "Name": "CoverLogo" }, { "Id": 38, "GameId": 555, "Name": "Background" } ], "GameFiles": [ { "Id": 102, "GameId": 555, "IsRequired": true, "FileName": "GoatGame-Win32-Shipping.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 556, "Name": "Grand Theft Auto IV", "Slug": "gta4", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 556, "Name": "Cover" }, { "Id": 33, "GameId": 556, "Name": "Icon16" }, { "Id": 34, "GameId": 556, "Name": "Icon24" }, { "Id": 35, "GameId": 556, "Name": "Icon32" }, { "Id": 36, "GameId": 556, "Name": "Logo" }, { "Id": 37, "GameId": 556, "Name": "CoverLogo" }, { "Id": 38, "GameId": 556, "Name": "Background" } ], "GameFiles": [ { "Id": 103, "GameId": 556, "IsRequired": true, "FileName": "GTAIV.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 557, "Name": "GRID 2", "Slug": "grid2", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 557, "Name": "Cover" }, { "Id": 33, "GameId": 557, "Name": "Icon16" }, { "Id": 34, "GameId": 557, "Name": "Icon24" }, { "Id": 35, "GameId": 557, "Name": "Icon32" }, { "Id": 36, "GameId": 557, "Name": "Logo" }, { "Id": 37, "GameId": 557, "Name": "CoverLogo" }, { "Id": 38, "GameId": 557, "Name": "Background" } ], "GameFiles": [ { "Id": 104, "GameId": 557, "IsRequired": true, "FileName": "GRID2.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 105, "GameId": 557, "IsRequired": true, "FileName": "GRID2_avx.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 559, "Name": "Killing Floor", "Slug": "killing-floor", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 559, "Name": "Cover" }, { "Id": 33, "GameId": 559, "Name": "Icon16" }, { "Id": 34, "GameId": 559, "Name": "Icon24" }, { "Id": 35, "GameId": 559, "Name": "Icon32" }, { "Id": 36, "GameId": 559, "Name": "Logo" }, { "Id": 37, "GameId": 559, "Name": "CoverLogo" }, { "Id": 38, "GameId": 559, "Name": "Background" } ], "GameFiles": [ { "Id": 107, "GameId": 559, "IsRequired": true, "FileName": "KillingFloor.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 560, "Name": "<NAME>", "Slug": "marvel-heroes", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 560, "Name": "Cover" }, { "Id": 33, "GameId": 560, "Name": "Icon16" }, { "Id": 34, "GameId": 560, "Name": "Icon24" }, { "Id": 35, "GameId": 560, "Name": "Icon32" }, { "Id": 36, "GameId": 560, "Name": "Logo" }, { "Id": 37, "GameId": 560, "Name": "CoverLogo" }, { "Id": 38, "GameId": 560, "Name": "Background" } ], "GameFiles": [ { "Id": 109, "GameId": 560, "IsRequired": true, "FileName": "MarvelHeroes2015.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 561, "Name": "Medieval II: Total War", "Slug": "medieval2", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 561, "Name": "Cover" }, { "Id": 33, "GameId": 561, "Name": "Icon16" }, { "Id": 34, "GameId": 561, "Name": "Icon24" }, { "Id": 35, "GameId": 561, "Name": "Icon32" }, { "Id": 36, "GameId": 561, "Name": "Logo" }, { "Id": 37, "GameId": 561, "Name": "CoverLogo" }, { "Id": 38, "GameId": 561, "Name": "Background" } ], "GameFiles": [ { "Id": 110, "GameId": 561, "IsRequired": true, "FileName": "medieval2.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 562, "Name": "Oort Online", "Slug": "oortonline", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 562, "Name": "Cover" }, { "Id": 33, "GameId": 562, "Name": "Icon16" }, { "Id": 34, "GameId": 562, "Name": "Icon24" }, { "Id": 35, "GameId": 562, "Name": "Icon32" }, { "Id": 36, "GameId": 562, "Name": "Logo" }, { "Id": 37, "GameId": 562, "Name": "CoverLogo" }, { "Id": 38, "GameId": 562, "Name": "Background" } ], "GameFiles": [ { "Id": 111, "GameId": 562, "IsRequired": true, "FileName": "oortonline.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 563, "Name": "PlanetSide 2", "Slug": "ps2", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 563, "Name": "Cover" }, { "Id": 33, "GameId": 563, "Name": "Icon16" }, { "Id": 34, "GameId": 563, "Name": "Icon24" }, { "Id": 35, "GameId": 563, "Name": "Icon32" }, { "Id": 36, "GameId": 563, "Name": "Logo" }, { "Id": 37, "GameId": 563, "Name": "CoverLogo" }, { "Id": 38, "GameId": 563, "Name": "Background" } ], "GameFiles": [ { "Id": 112, "GameId": 563, "IsRequired": true, "FileName": "PlanetSide2_x64.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 113, "GameId": 563, "IsRequired": true, "FileName": "PlanetSide2_x86.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 564, "Name": "<NAME>", "Slug": "saints-row3", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 564, "Name": "Cover" }, { "Id": 33, "GameId": 564, "Name": "Icon16" }, { "Id": 34, "GameId": 564, "Name": "Icon24" }, { "Id": 35, "GameId": 564, "Name": "Icon32" }, { "Id": 36, "GameId": 564, "Name": "Logo" }, { "Id": 37, "GameId": 564, "Name": "CoverLogo" }, { "Id": 38, "GameId": 564, "Name": "Background" } ], "GameFiles": [ { "Id": 114, "GameId": 564, "IsRequired": true, "FileName": "SaintsRowTheThird.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 115, "GameId": 564, "IsRequired": true, "FileName": "SaintsRowTheThird_DX11.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 566, "Name": "Starbound", "Slug": "starbound", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 566, "Name": "Cover" }, { "Id": 33, "GameId": 566, "Name": "Icon16" }, { "Id": 34, "GameId": 566, "Name": "Icon24" }, { "Id": 35, "GameId": 566, "Name": "Icon32" }, { "Id": 36, "GameId": 566, "Name": "Logo" }, { "Id": 37, "GameId": 566, "Name": "CoverLogo" }, { "Id": 38, "GameId": 566, "Name": "Background" } ], "GameFiles": [ { "Id": 116, "GameId": 566, "IsRequired": true, "FileName": "starbound.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 117, "GameId": 566, "IsRequired": true, "FileName": "starbound_opengl.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 567, "Name": "Stronghold Kingdoms", "Slug": "stronghold-kingdoms", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 567, "Name": "Cover" }, { "Id": 33, "GameId": 567, "Name": "Icon16" }, { "Id": 34, "GameId": 567, "Name": "Icon24" }, { "Id": 35, "GameId": 567, "Name": "Icon32" }, { "Id": 36, "GameId": 567, "Name": "Logo" }, { "Id": 37, "GameId": 567, "Name": "CoverLogo" }, { "Id": 38, "GameId": 567, "Name": "Background" } ], "GameFiles": [ { "Id": 118, "GameId": 567, "IsRequired": true, "FileName": "StrongholdKingdoms.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 568, "Name": "<NAME>", "Slug": "sunless-sea", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 568, "Name": "Cover" }, { "Id": 33, "GameId": 568, "Name": "Icon16" }, { "Id": 34, "GameId": 568, "Name": "Icon24" }, { "Id": 35, "GameId": 568, "Name": "Icon32" }, { "Id": 36, "GameId": 568, "Name": "Logo" }, { "Id": 37, "GameId": 568, "Name": "CoverLogo" }, { "Id": 38, "GameId": 568, "Name": "Background" } ], "GameFiles": [ { "Id": 119, "GameId": 568, "IsRequired": true, "FileName": "Sunless Sea.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 569, "Name": "The Binding of Isaac", "Slug": "binding-isaac", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 569, "Name": "Cover" }, { "Id": 33, "GameId": 569, "Name": "Icon16" }, { "Id": 34, "GameId": 569, "Name": "Icon24" }, { "Id": 35, "GameId": 569, "Name": "Icon32" }, { "Id": 36, "GameId": 569, "Name": "Logo" }, { "Id": 37, "GameId": 569, "Name": "CoverLogo" }, { "Id": 38, "GameId": 569, "Name": "Background" } ], "GameFiles": [ { "Id": 120, "GameId": 569, "IsRequired": true, "FileName": "Binding_of_Isaac.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 121, "GameId": 569, "IsRequired": true, "FileName": "Isaac.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 570, "Name": "Total War: Shogun 2", "Slug": "shogun2", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 570, "Name": "Cover" }, { "Id": 33, "GameId": 570, "Name": "Icon16" }, { "Id": 34, "GameId": 570, "Name": "Icon24" }, { "Id": 35, "GameId": 570, "Name": "Icon32" }, { "Id": 36, "GameId": 570, "Name": "Logo" }, { "Id": 37, "GameId": 570, "Name": "CoverLogo" }, { "Id": 38, "GameId": 570, "Name": "Background" } ], "GameFiles": [ { "Id": 122, "GameId": 570, "IsRequired": true, "FileName": "Shogun2.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 571, "Name": "Warface", "Slug": "warface", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 571, "Name": "Cover" }, { "Id": 33, "GameId": 571, "Name": "Icon16" }, { "Id": 34, "GameId": 571, "Name": "Icon24" }, { "Id": 35, "GameId": 571, "Name": "Icon32" }, { "Id": 36, "GameId": 571, "Name": "Logo" }, { "Id": 37, "GameId": 571, "Name": "CoverLogo" }, { "Id": 38, "GameId": 571, "Name": "Background" } ], "GameFiles": [ { "Id": 127, "GameId": 571, "IsRequired": true, "FileName": "GAME.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 128, "GameId": 571, "IsRequired": true, "FileName": "GFSDK_GSA.win32.dll", "FileType": 1, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 572, "Name": "Wasteland 2", "Slug": "wl2", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 572, "Name": "Cover" }, { "Id": 33, "GameId": 572, "Name": "Icon16" }, { "Id": 34, "GameId": 572, "Name": "Icon24" }, { "Id": 35, "GameId": 572, "Name": "Icon32" }, { "Id": 36, "GameId": 572, "Name": "Logo" }, { "Id": 37, "GameId": 572, "Name": "CoverLogo" }, { "Id": 38, "GameId": 572, "Name": "Background" } ], "GameFiles": [ { "Id": 124, "GameId": 572, "IsRequired": true, "FileName": "WL2.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 604, "Name": "H1Z1", "Slug": "h1z1", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 604, "Name": "Cover" }, { "Id": 33, "GameId": 604, "Name": "Icon16" }, { "Id": 34, "GameId": 604, "Name": "Icon24" }, { "Id": 35, "GameId": 604, "Name": "Icon32" }, { "Id": 36, "GameId": 604, "Name": "Logo" }, { "Id": 37, "GameId": 604, "Name": "CoverLogo" }, { "Id": 38, "GameId": 604, "Name": "Background" } ], "GameFiles": [ { "Id": 130, "GameId": 604, "IsRequired": true, "FileName": "H1Z1.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 605, "Name": "Fractured Space", "Slug": "Fractured-Space", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 605, "Name": "Cover" }, { "Id": 33, "GameId": 605, "Name": "Icon16" }, { "Id": 34, "GameId": 605, "Name": "Icon24" }, { "Id": 35, "GameId": 605, "Name": "Icon32" }, { "Id": 36, "GameId": 605, "Name": "Logo" }, { "Id": 37, "GameId": 605, "Name": "CoverLogo" }, { "Id": 38, "GameId": 605, "Name": "Background" } ], "GameFiles": [ { "Id": 132, "GameId": 605, "IsRequired": true, "FileName": "spacegame-Win64-Shipping.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 606, "Name": "Brawlhalla", "Slug": "Brawlhalla", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 606, "Name": "Cover" }, { "Id": 33, "GameId": 606, "Name": "Icon16" }, { "Id": 34, "GameId": 606, "Name": "Icon24" }, { "Id": 35, "GameId": 606, "Name": "Icon32" }, { "Id": 36, "GameId": 606, "Name": "Logo" }, { "Id": 37, "GameId": 606, "Name": "CoverLogo" }, { "Id": 38, "GameId": 606, "Name": "Background" } ], "GameFiles": [ { "Id": 133, "GameId": 606, "IsRequired": true, "FileName": "Brawlhalla.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 607, "Name": "<NAME>", "Slug": "grey-goo", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 607, "Name": "Cover" }, { "Id": 33, "GameId": 607, "Name": "Icon16" }, { "Id": 34, "GameId": 607, "Name": "Icon24" }, { "Id": 35, "GameId": 607, "Name": "Icon32" }, { "Id": 36, "GameId": 607, "Name": "Logo" }, { "Id": 37, "GameId": 607, "Name": "CoverLogo" }, { "Id": 38, "GameId": 607, "Name": "Background" } ], "GameFiles": [ { "Id": 134, "GameId": 607, "IsRequired": true, "FileName": "GooG.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 608, "Name": "<NAME>", "Slug": "darkest-dungeon", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 608, "Name": "Cover" }, { "Id": 33, "GameId": 608, "Name": "Icon16" }, { "Id": 34, "GameId": 608, "Name": "Icon24" }, { "Id": 35, "GameId": 608, "Name": "Icon32" }, { "Id": 36, "GameId": 608, "Name": "Logo" }, { "Id": 37, "GameId": 608, "Name": "CoverLogo" }, { "Id": 38, "GameId": 608, "Name": "Background" } ], "GameFiles": [ { "Id": 135, "GameId": 608, "IsRequired": true, "FileName": "Darkest.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 609, "Name": "Total War: ATTILA", "Slug": "totalwar-attila", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 609, "Name": "Cover" }, { "Id": 33, "GameId": 609, "Name": "Icon16" }, { "Id": 34, "GameId": 609, "Name": "Icon24" }, { "Id": 35, "GameId": 609, "Name": "Icon32" }, { "Id": 36, "GameId": 609, "Name": "Logo" }, { "Id": 37, "GameId": 609, "Name": "CoverLogo" }, { "Id": 38, "GameId": 609, "Name": "Background" } ], "GameFiles": [ { "Id": 136, "GameId": 609, "IsRequired": true, "FileName": "attila.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 610, "Name": "Besiege", "Slug": "besiege", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 610, "Name": "Cover" }, { "Id": 33, "GameId": 610, "Name": "Icon16" }, { "Id": 34, "GameId": 610, "Name": "Icon24" }, { "Id": 35, "GameId": 610, "Name": "Icon32" }, { "Id": 36, "GameId": 610, "Name": "Logo" }, { "Id": 37, "GameId": 610, "Name": "CoverLogo" }, { "Id": 38, "GameId": 610, "Name": "Background" } ], "GameFiles": [ { "Id": 137, "GameId": 610, "IsRequired": true, "FileName": "Besiege.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 611, "Name": "<NAME>", "Slug": "rok", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 611, "Name": "Cover" }, { "Id": 33, "GameId": 611, "Name": "Icon16" }, { "Id": 34, "GameId": 611, "Name": "Icon24" }, { "Id": 35, "GameId": 611, "Name": "Icon32" }, { "Id": 36, "GameId": 611, "Name": "Logo" }, { "Id": 37, "GameId": 611, "Name": "CoverLogo" }, { "Id": 38, "GameId": 611, "Name": "Background" } ], "GameFiles": [ { "Id": 138, "GameId": 611, "IsRequired": true, "FileName": "ROK.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 612, "Name": "Cities: Skylines", "Slug": "cities-skylines", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 612, "Name": "Cover" }, { "Id": 33, "GameId": 612, "Name": "Icon16" }, { "Id": 34, "GameId": 612, "Name": "Icon24" }, { "Id": 35, "GameId": 612, "Name": "Icon32" }, { "Id": 36, "GameId": 612, "Name": "Logo" }, { "Id": 37, "GameId": 612, "Name": "CoverLogo" }, { "Id": 38, "GameId": 612, "Name": "Background" } ], "GameFiles": [ { "Id": 139, "GameId": 612, "IsRequired": true, "FileName": "Cities.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 613, "Name": "World of Warships", "Slug": "warships", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 613, "Name": "Cover" }, { "Id": 33, "GameId": 613, "Name": "Icon16" }, { "Id": 34, "GameId": 613, "Name": "Icon24" }, { "Id": 35, "GameId": 613, "Name": "Icon32" }, { "Id": 36, "GameId": 613, "Name": "Logo" }, { "Id": 37, "GameId": 613, "Name": "CoverLogo" }, { "Id": 38, "GameId": 613, "Name": "Background" } ], "GameFiles": [ { "Id": 140, "GameId": 613, "IsRequired": true, "FileName": "WorldOfWarships.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 614, "Name": "Football Manager 2015", "Slug": "football2015", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 614, "Name": "Cover" }, { "Id": 33, "GameId": 614, "Name": "Icon16" }, { "Id": 34, "GameId": 614, "Name": "Icon24" }, { "Id": 35, "GameId": 614, "Name": "Icon32" }, { "Id": 36, "GameId": 614, "Name": "Logo" }, { "Id": 37, "GameId": 614, "Name": "CoverLogo" }, { "Id": 38, "GameId": 614, "Name": "Background" } ], "GameFiles": [ { "Id": 142, "GameId": 614, "IsRequired": true, "FileName": "FM2015.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 615, "Name": "Battlefield Hardline", "Slug": "bfh", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 615, "Name": "Cover" }, { "Id": 33, "GameId": 615, "Name": "Icon16" }, { "Id": 34, "GameId": 615, "Name": "Icon24" }, { "Id": 35, "GameId": 615, "Name": "Icon32" }, { "Id": 36, "GameId": 615, "Name": "Logo" }, { "Id": 37, "GameId": 615, "Name": "CoverLogo" }, { "Id": 38, "GameId": 615, "Name": "Background" } ], "GameFiles": [ { "Id": 143, "GameId": 615, "IsRequired": true, "FileName": "bfh.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 616, "Name": "Pillars of Eternity", "Slug": "pillars", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 616, "Name": "Cover" }, { "Id": 33, "GameId": 616, "Name": "Icon16" }, { "Id": 34, "GameId": 616, "Name": "Icon24" }, { "Id": 35, "GameId": 616, "Name": "Icon32" }, { "Id": 36, "GameId": 616, "Name": "Logo" }, { "Id": 37, "GameId": 616, "Name": "CoverLogo" }, { "Id": 38, "GameId": 616, "Name": "Background" } ], "GameFiles": [ { "Id": 144, "GameId": 616, "IsRequired": true, "FileName": "PillarsOfEternity.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 618, "Name": "Magicka: Wizard Wars", "Slug": "magicka-wizard-wars", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 618, "Name": "Cover" }, { "Id": 33, "GameId": 618, "Name": "Icon16" }, { "Id": 34, "GameId": 618, "Name": "Icon24" }, { "Id": 35, "GameId": 618, "Name": "Icon32" }, { "Id": 36, "GameId": 618, "Name": "Logo" }, { "Id": 37, "GameId": 618, "Name": "CoverLogo" }, { "Id": 38, "GameId": 618, "Name": "Background" } ], "GameFiles": [ { "Id": 146, "GameId": 618, "IsRequired": true, "FileName": "bitsquid_win32_dev.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 620, "Name": "<NAME>", "Slug": "magicka2", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 620, "Name": "Cover" }, { "Id": 33, "GameId": 620, "Name": "Icon16" }, { "Id": 34, "GameId": 620, "Name": "Icon24" }, { "Id": 35, "GameId": 620, "Name": "Icon32" }, { "Id": 36, "GameId": 620, "Name": "Logo" }, { "Id": 37, "GameId": 620, "Name": "CoverLogo" }, { "Id": 38, "GameId": 620, "Name": "Background" } ], "GameFiles": [ { "Id": 147, "GameId": 620, "IsRequired": true, "FileName": "Magicka2.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 621, "Name": "<NAME>", "Slug": "witcher3", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 621, "Name": "Cover" }, { "Id": 33, "GameId": 621, "Name": "Icon16" }, { "Id": 34, "GameId": 621, "Name": "Icon24" }, { "Id": 35, "GameId": 621, "Name": "Icon32" }, { "Id": 36, "GameId": 621, "Name": "Logo" }, { "Id": 37, "GameId": 621, "Name": "CoverLogo" }, { "Id": 38, "GameId": 621, "Name": "Background" } ], "GameFiles": [ { "Id": 148, "GameId": 621, "IsRequired": true, "FileName": "witcher3.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 622, "Name": "Clicker Heroes", "Slug": "clicker-heroes", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 622, "Name": "Cover" }, { "Id": 33, "GameId": 622, "Name": "Icon16" }, { "Id": 34, "GameId": 622, "Name": "Icon24" }, { "Id": 35, "GameId": 622, "Name": "Icon32" }, { "Id": 36, "GameId": 622, "Name": "Logo" }, { "Id": 37, "GameId": 622, "Name": "CoverLogo" }, { "Id": 38, "GameId": 622, "Name": "Background" } ], "GameFiles": [ { "Id": 162, "GameId": 622, "IsRequired": true, "FileName": "Clicker Heroes.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 623, "Name": "ARK: Survival Evolved", "Slug": "ark", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 623, "Name": "Cover" }, { "Id": 33, "GameId": 623, "Name": "Icon16" }, { "Id": 34, "GameId": 623, "Name": "Icon24" }, { "Id": 35, "GameId": 623, "Name": "Icon32" }, { "Id": 36, "GameId": 623, "Name": "Logo" }, { "Id": 37, "GameId": 623, "Name": "CoverLogo" }, { "Id": 38, "GameId": 623, "Name": "Background" } ], "GameFiles": [ { "Id": 159, "GameId": 623, "IsRequired": true, "FileName": "ShooterGame.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 625, "Name": "LEGO Worlds", "Slug": "lego-worlds", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 625, "Name": "Cover" }, { "Id": 33, "GameId": 625, "Name": "Icon16" }, { "Id": 34, "GameId": 625, "Name": "Icon24" }, { "Id": 35, "GameId": 625, "Name": "Icon32" }, { "Id": 36, "GameId": 625, "Name": "Logo" }, { "Id": 37, "GameId": 625, "Name": "CoverLogo" }, { "Id": 38, "GameId": 625, "Name": "Background" } ], "GameFiles": [ { "Id": 160, "GameId": 625, "IsRequired": true, "FileName": "LEGO_Worlds.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 626, "Name": "Rebuild 3: Gangs of Deadsville", "Slug": "rebuild3", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 626, "Name": "Cover" }, { "Id": 33, "GameId": 626, "Name": "Icon16" }, { "Id": 34, "GameId": 626, "Name": "Icon24" }, { "Id": 35, "GameId": 626, "Name": "Icon32" }, { "Id": 36, "GameId": 626, "Name": "Logo" }, { "Id": 37, "GameId": 626, "Name": "CoverLogo" }, { "Id": 38, "GameId": 626, "Name": "Background" } ], "GameFiles": [ { "Id": 164, "GameId": 626, "IsRequired": true, "FileName": "Rebuild3.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 627, "Name": "Galactic Civilizations 3", "Slug": "galciv3", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 627, "Name": "Cover" }, { "Id": 33, "GameId": 627, "Name": "Icon16" }, { "Id": 34, "GameId": 627, "Name": "Icon24" }, { "Id": 35, "GameId": 627, "Name": "Icon32" }, { "Id": 36, "GameId": 627, "Name": "Logo" }, { "Id": 37, "GameId": 627, "Name": "CoverLogo" }, { "Id": 38, "GameId": 627, "Name": "Background" } ], "GameFiles": [ { "Id": 161, "GameId": 627, "IsRequired": true, "FileName": "GalCiv3.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 628, "Name": "Killing Floor 2", "Slug": "kf2", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 628, "Name": "Cover" }, { "Id": 33, "GameId": 628, "Name": "Icon16" }, { "Id": 34, "GameId": 628, "Name": "Icon24" }, { "Id": 35, "GameId": 628, "Name": "Icon32" }, { "Id": 36, "GameId": 628, "Name": "Logo" }, { "Id": 37, "GameId": 628, "Name": "CoverLogo" }, { "Id": 38, "GameId": 628, "Name": "Background" } ], "GameFiles": [ { "Id": 163, "GameId": 628, "IsRequired": true, "FileName": "KFGame.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 629, "Name": "AdVenture Capitalist", "Slug": "adventure-capitalist", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 629, "Name": "Cover" }, { "Id": 33, "GameId": 629, "Name": "Icon16" }, { "Id": 34, "GameId": 629, "Name": "Icon24" }, { "Id": 35, "GameId": 629, "Name": "Icon32" }, { "Id": 36, "GameId": 629, "Name": "Logo" }, { "Id": 37, "GameId": 629, "Name": "CoverLogo" }, { "Id": 38, "GameId": 629, "Name": "Background" } ], "GameFiles": [ { "Id": 165, "GameId": 629, "IsRequired": true, "FileName": "adventure-capitalist.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 631, "Name": "Dirty Bomb", "Slug": "dirty-bomb", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 631, "Name": "Cover" }, { "Id": 33, "GameId": 631, "Name": "Icon16" }, { "Id": 34, "GameId": 631, "Name": "Icon24" }, { "Id": 35, "GameId": 631, "Name": "Icon32" }, { "Id": 36, "GameId": 631, "Name": "Logo" }, { "Id": 37, "GameId": 631, "Name": "CoverLogo" }, { "Id": 38, "GameId": 631, "Name": "Background" } ], "GameFiles": [ { "Id": 152, "GameId": 631, "IsRequired": true, "FileName": "ShooterGame-Win32-Shipping.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 632, "Name": "Rocket League", "Slug": "rocket-league", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 632, "Name": "Cover" }, { "Id": 33, "GameId": 632, "Name": "Icon16" }, { "Id": 34, "GameId": 632, "Name": "Icon24" }, { "Id": 35, "GameId": 632, "Name": "Icon32" }, { "Id": 36, "GameId": 632, "Name": "Logo" }, { "Id": 37, "GameId": 632, "Name": "CoverLogo" }, { "Id": 38, "GameId": 632, "Name": "Background" } ], "GameFiles": [ { "Id": 166, "GameId": 632, "IsRequired": true, "FileName": "RocketLeague.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 633, "Name": "Trove", "Slug": "trove", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 633, "Name": "Cover" }, { "Id": 33, "GameId": 633, "Name": "Icon16" }, { "Id": 34, "GameId": 633, "Name": "Icon24" }, { "Id": 35, "GameId": 633, "Name": "Icon32" }, { "Id": 36, "GameId": 633, "Name": "Logo" }, { "Id": 37, "GameId": 633, "Name": "CoverLogo" }, { "Id": 38, "GameId": 633, "Name": "Background" } ], "GameFiles": [ { "Id": 168, "GameId": 633, "IsRequired": true, "FileName": "Trove.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 634, "Name": "Osu!", "Slug": "osu", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 634, "Name": "Cover" }, { "Id": 33, "GameId": 634, "Name": "Icon16" }, { "Id": 34, "GameId": 634, "Name": "Icon24" }, { "Id": 35, "GameId": 634, "Name": "Icon32" }, { "Id": 36, "GameId": 634, "Name": "Logo" }, { "Id": 37, "GameId": 634, "Name": "CoverLogo" }, { "Id": 38, "GameId": 634, "Name": "Background" } ], "GameFiles": [ { "Id": 170, "GameId": 634, "IsRequired": true, "FileName": "osu!.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 635, "Name": "Skyforge", "Slug": "skyforge", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 635, "Name": "Cover" }, { "Id": 33, "GameId": 635, "Name": "Icon16" }, { "Id": 34, "GameId": 635, "Name": "Icon24" }, { "Id": 35, "GameId": 635, "Name": "Icon32" }, { "Id": 36, "GameId": 635, "Name": "Logo" }, { "Id": 37, "GameId": 635, "Name": "CoverLogo" }, { "Id": 38, "GameId": 635, "Name": "Background" } ], "GameFiles": [ { "Id": 169, "GameId": 635, "IsRequired": true, "FileName": "Skyforge.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 636, "Name": "Awesomenauts", "Slug": "awesomenauts", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 636, "Name": "Cover" }, { "Id": 33, "GameId": 636, "Name": "Icon16" }, { "Id": 34, "GameId": 636, "Name": "Icon24" }, { "Id": 35, "GameId": 636, "Name": "Icon32" }, { "Id": 36, "GameId": 636, "Name": "Logo" }, { "Id": 37, "GameId": 636, "Name": "CoverLogo" }, { "Id": 38, "GameId": 636, "Name": "Background" } ], "GameFiles": [ { "Id": 171, "GameId": 636, "IsRequired": true, "FileName": "Awesomenauts.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 637, "Name": "Empyrion - Galactic Survival", "Slug": "empyrion", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 637, "Name": "Cover" }, { "Id": 33, "GameId": 637, "Name": "Icon16" }, { "Id": 34, "GameId": 637, "Name": "Icon24" }, { "Id": 35, "GameId": 637, "Name": "Icon32" }, { "Id": 36, "GameId": 637, "Name": "Logo" }, { "Id": 37, "GameId": 637, "Name": "CoverLogo" }, { "Id": 38, "GameId": 637, "Name": "Background" } ], "GameFiles": [ { "Id": 172, "GameId": 637, "IsRequired": true, "FileName": "Empyrion.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 638, "Name": "<NAME>", "Slug": "mad-max", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 638, "Name": "Cover" }, { "Id": 33, "GameId": 638, "Name": "Icon16" }, { "Id": 34, "GameId": 638, "Name": "Icon24" }, { "Id": 35, "GameId": 638, "Name": "Icon32" }, { "Id": 36, "GameId": 638, "Name": "Logo" }, { "Id": 37, "GameId": 638, "Name": "CoverLogo" }, { "Id": 38, "GameId": 638, "Name": "Background" } ], "GameFiles": [ { "Id": 173, "GameId": 638, "IsRequired": true, "FileName": "MadMax.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 639, "Name": "METAL GEAR SOLID V: THE PHANTOM PAIN", "Slug": "msgv", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 639, "Name": "Cover" }, { "Id": 33, "GameId": 639, "Name": "Icon16" }, { "Id": 34, "GameId": 639, "Name": "Icon24" }, { "Id": 35, "GameId": 639, "Name": "Icon32" }, { "Id": 36, "GameId": 639, "Name": "Logo" }, { "Id": 37, "GameId": 639, "Name": "CoverLogo" }, { "Id": 38, "GameId": 639, "Name": "Background" } ], "GameFiles": [ { "Id": 174, "GameId": 639, "IsRequired": true, "FileName": "mgsvtpp.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 640, "Name": "Rainbow Six Siege", "Slug": "rainbow6siege", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 640, "Name": "Cover" }, { "Id": 33, "GameId": 640, "Name": "Icon16" }, { "Id": 34, "GameId": 640, "Name": "Icon24" }, { "Id": 35, "GameId": 640, "Name": "Icon32" }, { "Id": 36, "GameId": 640, "Name": "Logo" }, { "Id": 37, "GameId": 640, "Name": "CoverLogo" }, { "Id": 38, "GameId": 640, "Name": "Background" } ], "GameFiles": [ { "Id": 205, "GameId": 640, "IsRequired": true, "FileName": "RainbowSixGame.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 641, "Name": "Star Wars Battlefront", "Slug": "battlefront", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 641, "Name": "Cover" }, { "Id": 33, "GameId": 641, "Name": "Icon16" }, { "Id": 34, "GameId": 641, "Name": "Icon24" }, { "Id": 35, "GameId": 641, "Name": "Icon32" }, { "Id": 36, "GameId": 641, "Name": "Logo" }, { "Id": 37, "GameId": 641, "Name": "CoverLogo" }, { "Id": 38, "GameId": 641, "Name": "Background" } ], "GameFiles": [ { "Id": 180, "GameId": 641, "IsRequired": true, "FileName": "starwarsbattlefront.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 643, "Name": "Total War: Arena", "Slug": "total-war-arena", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 643, "Name": "Cover" }, { "Id": 33, "GameId": 643, "Name": "Icon16" }, { "Id": 34, "GameId": 643, "Name": "Icon24" }, { "Id": 35, "GameId": 643, "Name": "Icon32" }, { "Id": 36, "GameId": 643, "Name": "Logo" }, { "Id": 37, "GameId": 643, "Name": "CoverLogo" }, { "Id": 38, "GameId": 643, "Name": "Background" } ], "GameFiles": [ { "Id": 175, "GameId": 643, "IsRequired": true, "FileName": "Arena.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 644, "Name": "Overwatch", "Slug": "overwatch", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 644, "Name": "Cover" }, { "Id": 33, "GameId": 644, "Name": "Icon16" }, { "Id": 34, "GameId": 644, "Name": "Icon24" }, { "Id": 35, "GameId": 644, "Name": "Icon32" }, { "Id": 36, "GameId": 644, "Name": "Logo" }, { "Id": 37, "GameId": 644, "Name": "CoverLogo" }, { "Id": 38, "GameId": 644, "Name": "Background" } ], "GameFiles": [ { "Id": 178, "GameId": 644, "IsRequired": true, "FileName": "Overwatch.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 645, "Name": "Battle Battalions", "Slug": "battle-battalions", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 645, "Name": "Cover" }, { "Id": 33, "GameId": 645, "Name": "Icon16" }, { "Id": 34, "GameId": 645, "Name": "Icon24" }, { "Id": 35, "GameId": 645, "Name": "Icon32" }, { "Id": 36, "GameId": 645, "Name": "Logo" }, { "Id": 37, "GameId": 645, "Name": "CoverLogo" }, { "Id": 38, "GameId": 645, "Name": "Background" } ], "GameFiles": [ { "Id": 179, "GameId": 645, "IsRequired": true, "FileName": "BattleBattalionsRS.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 646, "Name": "<NAME>", "Slug": "fallout4", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 646, "Name": "Cover" }, { "Id": 33, "GameId": 646, "Name": "Icon16" }, { "Id": 34, "GameId": 646, "Name": "Icon24" }, { "Id": 35, "GameId": 646, "Name": "Icon32" }, { "Id": 36, "GameId": 646, "Name": "Logo" }, { "Id": 37, "GameId": 646, "Name": "CoverLogo" }, { "Id": 38, "GameId": 646, "Name": "Background" } ], "GameFiles": [ { "Id": 182, "GameId": 646, "IsRequired": true, "FileName": "Fallout4.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 647, "Name": "Paladins", "Slug": "paladins", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 647, "Name": "Cover" }, { "Id": 33, "GameId": 647, "Name": "Icon16" }, { "Id": 34, "GameId": 647, "Name": "Icon24" }, { "Id": 35, "GameId": 647, "Name": "Icon32" }, { "Id": 36, "GameId": 647, "Name": "Logo" }, { "Id": 37, "GameId": 647, "Name": "CoverLogo" }, { "Id": 38, "GameId": 647, "Name": "Background" } ], "GameFiles": [ { "Id": 181, "GameId": 647, "IsRequired": true, "FileName": "Paladins.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 648, "Name": "The Division", "Slug": "the-division", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 648, "Name": "Cover" }, { "Id": 33, "GameId": 648, "Name": "Icon16" }, { "Id": 34, "GameId": 648, "Name": "Icon24" }, { "Id": 35, "GameId": 648, "Name": "Icon32" }, { "Id": 36, "GameId": 648, "Name": "Logo" }, { "Id": 37, "GameId": 648, "Name": "CoverLogo" }, { "Id": 38, "GameId": 648, "Name": "Background" } ], "GameFiles": [ { "Id": 183, "GameId": 648, "IsRequired": true, "FileName": "thedivision.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 649, "Name": "Paragon", "Slug": "paragon", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 649, "Name": "Cover" }, { "Id": 33, "GameId": 649, "Name": "Icon16" }, { "Id": 34, "GameId": 649, "Name": "Icon24" }, { "Id": 35, "GameId": 649, "Name": "Icon32" }, { "Id": 36, "GameId": 649, "Name": "Logo" }, { "Id": 37, "GameId": 649, "Name": "CoverLogo" }, { "Id": 38, "GameId": 649, "Name": "Background" } ], "GameFiles": [ { "Id": 197, "GameId": 649, "IsRequired": true, "FileName": "OrionClient-Win64-Shipping.exe", "FileType": 2, "PlatformType": 3 }, { "Id": 198, "GameId": 649, "IsRequired": true, "FileName": "OrionClient-Win32-Shipping.exe", "FileType": 2, "PlatformType": 2 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 650, "Name": "Stellaris", "Slug": "stellaris", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 650, "Name": "Cover" }, { "Id": 33, "GameId": 650, "Name": "Icon16" }, { "Id": 34, "GameId": 650, "Name": "Icon24" }, { "Id": 35, "GameId": 650, "Name": "Icon32" }, { "Id": 36, "GameId": 650, "Name": "Logo" }, { "Id": 37, "GameId": 650, "Name": "CoverLogo" }, { "Id": 38, "GameId": 650, "Name": "Background" } ], "GameFiles": [ { "Id": 185, "GameId": 650, "IsRequired": true, "FileName": "stellaris.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 652, "Name": "Street Fighter V", "Slug": "sf-5", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 652, "Name": "Cover" }, { "Id": 33, "GameId": 652, "Name": "Icon16" }, { "Id": 34, "GameId": 652, "Name": "Icon24" }, { "Id": 35, "GameId": 652, "Name": "Icon32" }, { "Id": 36, "GameId": 652, "Name": "Logo" }, { "Id": 37, "GameId": 652, "Name": "CoverLogo" }, { "Id": 38, "GameId": 652, "Name": "Background" } ], "GameFiles": [], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": false, "BundleAssets": false }, { "ID": 653, "Name": "Dark Souls 3", "Slug": "dark-souls-3", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 653, "Name": "Cover" }, { "Id": 33, "GameId": 653, "Name": "Icon16" }, { "Id": 34, "GameId": 653, "Name": "Icon24" }, { "Id": 35, "GameId": 653, "Name": "Icon32" }, { "Id": 36, "GameId": 653, "Name": "Logo" }, { "Id": 37, "GameId": 653, "Name": "CoverLogo" }, { "Id": 38, "GameId": 653, "Name": "Background" } ], "GameFiles": [ { "Id": 253, "GameId": 653, "IsRequired": true, "FileName": "DarkSoulslll.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 654, "Name": "Total War: Warhammer", "Slug": "tw-warhammer", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 654, "Name": "Cover" }, { "Id": 33, "GameId": 654, "Name": "Icon16" }, { "Id": 34, "GameId": 654, "Name": "Icon24" }, { "Id": 35, "GameId": 654, "Name": "Icon32" }, { "Id": 36, "GameId": 654, "Name": "Logo" }, { "Id": 37, "GameId": 654, "Name": "CoverLogo" }, { "Id": 38, "GameId": 654, "Name": "Background" } ], "GameFiles": [ { "Id": 249, "GameId": 654, "IsRequired": true, "FileName": "Warhammer.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 655, "Name": "Call of Duty: Black Ops III", "Slug": "CoDBO3", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 655, "Name": "Cover" }, { "Id": 33, "GameId": 655, "Name": "Icon16" }, { "Id": 34, "GameId": 655, "Name": "Icon24" }, { "Id": 35, "GameId": 655, "Name": "Icon32" }, { "Id": 36, "GameId": 655, "Name": "Logo" }, { "Id": 37, "GameId": 655, "Name": "CoverLogo" }, { "Id": 38, "GameId": 655, "Name": "Background" } ], "GameFiles": [ { "Id": 203, "GameId": 655, "IsRequired": true, "FileName": "BlackOps3.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 656, "Name": "FIFA 16", "Slug": "FIFA16", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 656, "Name": "Cover" }, { "Id": 33, "GameId": 656, "Name": "Icon16" }, { "Id": 34, "GameId": 656, "Name": "Icon24" }, { "Id": 35, "GameId": 656, "Name": "Icon32" }, { "Id": 36, "GameId": 656, "Name": "Logo" }, { "Id": 37, "GameId": 656, "Name": "CoverLogo" }, { "Id": 38, "GameId": 656, "Name": "Background" } ], "GameFiles": [ { "Id": 202, "GameId": 656, "IsRequired": true, "FileName": "fifa16.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 658, "Name": "Pantheon", "Slug": "pantheon", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 658, "Name": "Cover" }, { "Id": 33, "GameId": 658, "Name": "Icon16" }, { "Id": 34, "GameId": 658, "Name": "Icon24" }, { "Id": 35, "GameId": 658, "Name": "Icon32" }, { "Id": 36, "GameId": 658, "Name": "Logo" }, { "Id": 37, "GameId": 658, "Name": "CoverLogo" }, { "Id": 38, "GameId": 658, "Name": "Background" } ], "GameFiles": [], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 659, "Name": "Football Manager 2016", "Slug": "FM2016", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 659, "Name": "Cover" }, { "Id": 33, "GameId": 659, "Name": "Icon16" }, { "Id": 34, "GameId": 659, "Name": "Icon24" }, { "Id": 35, "GameId": 659, "Name": "Icon32" }, { "Id": 36, "GameId": 659, "Name": "Logo" }, { "Id": 37, "GameId": 659, "Name": "CoverLogo" }, { "Id": 38, "GameId": 659, "Name": "Background" } ], "GameFiles": [ { "Id": 235, "GameId": 659, "IsRequired": false, "FileName": "fm.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 237, "GameId": 659, "IsRequired": false, "FileName": "helper.x86", "FileType": 1, "PlatformType": 1 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 660, "Name": "Doom", "Slug": "Doom", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 660, "Name": "Cover" }, { "Id": 33, "GameId": 660, "Name": "Icon16" }, { "Id": 34, "GameId": 660, "Name": "Icon24" }, { "Id": 35, "GameId": 660, "Name": "Icon32" }, { "Id": 36, "GameId": 660, "Name": "Logo" }, { "Id": 37, "GameId": 660, "Name": "CoverLogo" }, { "Id": 38, "GameId": 660, "Name": "Background" } ], "GameFiles": [ { "Id": 212, "GameId": 660, "IsRequired": false, "FileName": "DOOMx64.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 213, "GameId": 660, "IsRequired": false, "FileName": "DOOMx64vk.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 661, "Name": "Factorio", "Slug": "Factorio", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 661, "Name": "Cover" }, { "Id": 33, "GameId": 661, "Name": "Icon16" }, { "Id": 34, "GameId": 661, "Name": "Icon24" }, { "Id": 35, "GameId": 661, "Name": "Icon32" }, { "Id": 36, "GameId": 661, "Name": "Logo" }, { "Id": 37, "GameId": 661, "Name": "CoverLogo" }, { "Id": 38, "GameId": 661, "Name": "Background" } ], "GameFiles": [ { "Id": 234, "GameId": 661, "IsRequired": true, "FileName": "factorio.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 662, "Name": "Portal", "Slug": "Portal", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 662, "Name": "Cover" }, { "Id": 33, "GameId": 662, "Name": "Icon16" }, { "Id": 34, "GameId": 662, "Name": "Icon24" }, { "Id": 35, "GameId": 662, "Name": "Icon32" }, { "Id": 36, "GameId": 662, "Name": "Logo" }, { "Id": 37, "GameId": 662, "Name": "CoverLogo" }, { "Id": 38, "GameId": 662, "Name": "Background" } ], "GameFiles": [ { "Id": 251, "GameId": 662, "IsRequired": false, "FileName": "portal\\portal_pak_000.vpk", "FileType": 1, "PlatformType": 1 }, { "Id": 252, "GameId": 662, "IsRequired": false, "FileName": "hl2.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 663, "Name": "Portal 2", "Slug": "Portal2", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 663, "Name": "Cover" }, { "Id": 33, "GameId": 663, "Name": "Icon16" }, { "Id": 34, "GameId": 663, "Name": "Icon24" }, { "Id": 35, "GameId": 663, "Name": "Icon32" }, { "Id": 36, "GameId": 663, "Name": "Logo" }, { "Id": 37, "GameId": 663, "Name": "CoverLogo" }, { "Id": 38, "GameId": 663, "Name": "Background" } ], "GameFiles": [ { "Id": 219, "GameId": 663, "IsRequired": true, "FileName": "portal2.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 664, "Name": "NBA 2k16", "Slug": "NBA2k16", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 664, "Name": "Cover" }, { "Id": 33, "GameId": 664, "Name": "Icon16" }, { "Id": 34, "GameId": 664, "Name": "Icon24" }, { "Id": 35, "GameId": 664, "Name": "Icon32" }, { "Id": 36, "GameId": 664, "Name": "Logo" }, { "Id": 37, "GameId": 664, "Name": "CoverLogo" }, { "Id": 38, "GameId": 664, "Name": "Background" } ], "GameFiles": [ { "Id": 243, "GameId": 664, "IsRequired": true, "FileName": "NBA2K16.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 665, "Name": "Hearts of Iron IV", "Slug": "HoIIV", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 665, "Name": "Cover" }, { "Id": 33, "GameId": 665, "Name": "Icon16" }, { "Id": 34, "GameId": 665, "Name": "Icon24" }, { "Id": 35, "GameId": 665, "Name": "Icon32" }, { "Id": 36, "GameId": 665, "Name": "Logo" }, { "Id": 37, "GameId": 665, "Name": "CoverLogo" }, { "Id": 38, "GameId": 665, "Name": "Background" } ], "GameFiles": [ { "Id": 238, "GameId": 665, "IsRequired": true, "FileName": "hoi4.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 666, "Name": "Dead by Daylight", "Slug": "DeadByDaylight", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 666, "Name": "Cover" }, { "Id": 33, "GameId": 666, "Name": "Icon16" }, { "Id": 34, "GameId": 666, "Name": "Icon24" }, { "Id": 35, "GameId": 666, "Name": "Icon32" }, { "Id": 36, "GameId": 666, "Name": "Logo" }, { "Id": 37, "GameId": 666, "Name": "CoverLogo" }, { "Id": 38, "GameId": 666, "Name": "Background" } ], "GameFiles": [ { "Id": 229, "GameId": 666, "IsRequired": true, "FileName": "DeadByDaylight-Win64-Shipping.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 667, "Name": "Tree of Savior", "Slug": "TreeOfSavior", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 667, "Name": "Cover" }, { "Id": 33, "GameId": 667, "Name": "Icon16" }, { "Id": 34, "GameId": 667, "Name": "Icon24" }, { "Id": 35, "GameId": 667, "Name": "Icon32" }, { "Id": 36, "GameId": 667, "Name": "Logo" }, { "Id": 37, "GameId": 667, "Name": "CoverLogo" }, { "Id": 38, "GameId": 667, "Name": "Background" } ], "GameFiles": [ { "Id": 223, "GameId": 667, "IsRequired": true, "FileName": "Client_tos.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 668, "Name": "Europa Universalis IV", "Slug": "EUIV", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 668, "Name": "Cover" }, { "Id": 33, "GameId": 668, "Name": "Icon16" }, { "Id": 34, "GameId": 668, "Name": "Icon24" }, { "Id": 35, "GameId": 668, "Name": "Icon32" }, { "Id": 36, "GameId": 668, "Name": "Logo" }, { "Id": 37, "GameId": 668, "Name": "CoverLogo" }, { "Id": 38, "GameId": 668, "Name": "Background" } ], "GameFiles": [ { "Id": 216, "GameId": 668, "IsRequired": true, "FileName": "eu4.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 669, "Name": "Stardew Valley", "Slug": "StardewValley", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 669, "Name": "Cover" }, { "Id": 33, "GameId": 669, "Name": "Icon16" }, { "Id": 34, "GameId": 669, "Name": "Icon24" }, { "Id": 35, "GameId": 669, "Name": "Icon32" }, { "Id": 36, "GameId": 669, "Name": "Logo" }, { "Id": 37, "GameId": 669, "Name": "CoverLogo" }, { "Id": 38, "GameId": 669, "Name": "Background" } ], "GameFiles": [ { "Id": 222, "GameId": 669, "IsRequired": true, "FileName": "Stardew Valley.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 670, "Name": "Elite: Dangerous", "Slug": "EliteDangerous", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 670, "Name": "Cover" }, { "Id": 33, "GameId": 670, "Name": "Icon16" }, { "Id": 34, "GameId": 670, "Name": "Icon24" }, { "Id": 35, "GameId": 670, "Name": "Icon32" }, { "Id": 36, "GameId": 670, "Name": "Logo" }, { "Id": 37, "GameId": 670, "Name": "CoverLogo" }, { "Id": 38, "GameId": 670, "Name": "Background" } ], "GameFiles": [ { "Id": 214, "GameId": 670, "IsRequired": false, "FileName": "EliteDangerous64.exe", "FileType": 2, "PlatformType": 3 }, { "Id": 215, "GameId": 670, "IsRequired": false, "FileName": "EliteDangerous32.exe", "FileType": 2, "PlatformType": 2 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 671, "Name": "ShellShock Live", "Slug": "ShellShockLive", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 671, "Name": "Cover" }, { "Id": 33, "GameId": 671, "Name": "Icon16" }, { "Id": 34, "GameId": 671, "Name": "Icon24" }, { "Id": 35, "GameId": 671, "Name": "Icon32" }, { "Id": 36, "GameId": 671, "Name": "Logo" }, { "Id": 37, "GameId": 671, "Name": "CoverLogo" }, { "Id": 38, "GameId": 671, "Name": "Background" } ], "GameFiles": [ { "Id": 246, "GameId": 671, "IsRequired": true, "FileName": "ShellShockLive.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 672, "Name": "Undertale", "Slug": "Undertale", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 672, "Name": "Cover" }, { "Id": 33, "GameId": 672, "Name": "Icon16" }, { "Id": 34, "GameId": 672, "Name": "Icon24" }, { "Id": 35, "GameId": 672, "Name": "Icon32" }, { "Id": 36, "GameId": 672, "Name": "Logo" }, { "Id": 37, "GameId": 672, "Name": "CoverLogo" }, { "Id": 38, "GameId": 672, "Name": "Background" } ], "GameFiles": [ { "Id": 247, "GameId": 672, "IsRequired": true, "FileName": "UNDERTALE.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 673, "Name": "Hurtworld", "Slug": "Hurtworld", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 673, "Name": "Cover" }, { "Id": 33, "GameId": 673, "Name": "Icon16" }, { "Id": 34, "GameId": 673, "Name": "Icon24" }, { "Id": 35, "GameId": 673, "Name": "Icon32" }, { "Id": 36, "GameId": 673, "Name": "Logo" }, { "Id": 37, "GameId": 673, "Name": "CoverLogo" }, { "Id": 38, "GameId": 673, "Name": "Background" } ], "GameFiles": [ { "Id": 239, "GameId": 673, "IsRequired": true, "FileName": "Hurtworldclient.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 674, "Name": "Don't Starve", "Slug": "DontStarve", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 674, "Name": "Cover" }, { "Id": 33, "GameId": 674, "Name": "Icon16" }, { "Id": 34, "GameId": 674, "Name": "Icon24" }, { "Id": 35, "GameId": 674, "Name": "Icon32" }, { "Id": 36, "GameId": 674, "Name": "Logo" }, { "Id": 37, "GameId": 674, "Name": "CoverLogo" }, { "Id": 38, "GameId": 674, "Name": "Background" } ], "GameFiles": [ { "Id": 230, "GameId": 674, "IsRequired": false, "FileName": "dontstarve_steam.exe ", "FileType": 2, "PlatformType": 4 }, { "Id": 233, "GameId": 674, "IsRequired": false, "FileName": "tier0_s.dll", "FileType": 1, "PlatformType": 1 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 675, "Name": "Don't Starve Together", "Slug": "DSTogether", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 675, "Name": "Cover" }, { "Id": 33, "GameId": 675, "Name": "Icon16" }, { "Id": 34, "GameId": 675, "Name": "Icon24" }, { "Id": 35, "GameId": 675, "Name": "Icon32" }, { "Id": 36, "GameId": 675, "Name": "Logo" }, { "Id": 37, "GameId": 675, "Name": "CoverLogo" }, { "Id": 38, "GameId": 675, "Name": "Background" } ], "GameFiles": [ { "Id": 231, "GameId": 675, "IsRequired": false, "FileName": "dontstarve_Steam", "FileType": 2, "PlatformType": 4 }, { "Id": 232, "GameId": 675, "IsRequired": false, "FileName": "dontstarve_dedicated_server_nullrenderer.exe", "FileType": 1, "PlatformType": 1 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 676, "Name": "Civilization IV", "Slug": "CivIV", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 676, "Name": "Cover" }, { "Id": 33, "GameId": 676, "Name": "Icon16" }, { "Id": 34, "GameId": 676, "Name": "Icon24" }, { "Id": 35, "GameId": 676, "Name": "Icon32" }, { "Id": 36, "GameId": 676, "Name": "Logo" }, { "Id": 37, "GameId": 676, "Name": "CoverLogo" }, { "Id": 38, "GameId": 676, "Name": "Background" } ], "GameFiles": [ { "Id": 221, "GameId": 676, "IsRequired": false, "FileName": "Civ4BeyondSword.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": false, "BundleAssets": false }, { "ID": 677, "Name": "Civilization III", "Slug": "CivIII", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 677, "Name": "Cover" }, { "Id": 33, "GameId": 677, "Name": "Icon16" }, { "Id": 34, "GameId": 677, "Name": "Icon24" }, { "Id": 35, "GameId": 677, "Name": "Icon32" }, { "Id": 36, "GameId": 677, "Name": "Logo" }, { "Id": 37, "GameId": 677, "Name": "CoverLogo" }, { "Id": 38, "GameId": 677, "Name": "Background" } ], "GameFiles": [ { "Id": 220, "GameId": 677, "IsRequired": false, "FileName": "Civ3Conquest.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": false, "BundleAssets": false }, { "ID": 678, "Name": "<NAME>", "Slug": "InsanityClicker", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 678, "Name": "Cover" }, { "Id": 33, "GameId": 678, "Name": "Icon16" }, { "Id": 34, "GameId": 678, "Name": "Icon24" }, { "Id": 35, "GameId": 678, "Name": "Icon32" }, { "Id": 36, "GameId": 678, "Name": "Logo" }, { "Id": 37, "GameId": 678, "Name": "CoverLogo" }, { "Id": 38, "GameId": 678, "Name": "Background" } ], "GameFiles": [ { "Id": 217, "GameId": 678, "IsRequired": true, "FileName": "Insanity Clicker.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 679, "Name": "<NAME>", "Slug": "RememberMe", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 679, "Name": "Cover" }, { "Id": 33, "GameId": 679, "Name": "Icon16" }, { "Id": 34, "GameId": 679, "Name": "Icon24" }, { "Id": 35, "GameId": 679, "Name": "Icon32" }, { "Id": 36, "GameId": 679, "Name": "Logo" }, { "Id": 37, "GameId": 679, "Name": "CoverLogo" }, { "Id": 38, "GameId": 679, "Name": "Background" } ], "GameFiles": [ { "Id": 248, "GameId": 679, "IsRequired": true, "FileName": "RememberMe.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 680, "Name": "H1Z1: King of the Kill", "Slug": "H1Z1KotK", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 680, "Name": "Cover" }, { "Id": 33, "GameId": 680, "Name": "Icon16" }, { "Id": 34, "GameId": 680, "Name": "Icon24" }, { "Id": 35, "GameId": 680, "Name": "Icon32" }, { "Id": 36, "GameId": 680, "Name": "Logo" }, { "Id": 37, "GameId": 680, "Name": "CoverLogo" }, { "Id": 38, "GameId": 680, "Name": "Background" } ], "GameFiles": [], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": false, "BundleAssets": false }, { "ID": 681, "Name": "<NAME>", "Slug": "StarCitizen", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 681, "Name": "Cover" }, { "Id": 33, "GameId": 681, "Name": "Icon16" }, { "Id": 34, "GameId": 681, "Name": "Icon24" }, { "Id": 35, "GameId": 681, "Name": "Icon32" }, { "Id": 36, "GameId": 681, "Name": "Logo" }, { "Id": 37, "GameId": 681, "Name": "CoverLogo" }, { "Id": 38, "GameId": 681, "Name": "Background" } ], "GameFiles": [ { "Id": 201, "GameId": 681, "IsRequired": true, "FileName": "StarCitizen.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 682, "Name": "No Man's Sky", "Slug": "no-mans-sky", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 682, "Name": "Cover" }, { "Id": 33, "GameId": 682, "Name": "Icon16" }, { "Id": 34, "GameId": 682, "Name": "Icon24" }, { "Id": 35, "GameId": 682, "Name": "Icon32" }, { "Id": 36, "GameId": 682, "Name": "Logo" }, { "Id": 37, "GameId": 682, "Name": "CoverLogo" }, { "Id": 38, "GameId": 682, "Name": "Background" } ], "GameFiles": [ { "Id": 194, "GameId": 682, "IsRequired": true, "FileName": "NMS.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 11, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 687, "Name": "Battlefield 1", "Slug": "Battlefield1", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 687, "Name": "Cover" }, { "Id": 33, "GameId": 687, "Name": "Icon16" }, { "Id": 34, "GameId": 687, "Name": "Icon24" }, { "Id": 35, "GameId": 687, "Name": "Icon32" }, { "Id": 36, "GameId": 687, "Name": "Logo" }, { "Id": 37, "GameId": 687, "Name": "CoverLogo" }, { "Id": 38, "GameId": 687, "Name": "Background" } ], "GameFiles": [ { "Id": 208, "GameId": 687, "IsRequired": true, "FileName": "bf1.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 720, "Name": "<NAME>", "Slug": "albiononline", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 720, "Name": "Cover" }, { "Id": 33, "GameId": 720, "Name": "Icon16" }, { "Id": 34, "GameId": 720, "Name": "Icon24" }, { "Id": 35, "GameId": 720, "Name": "Icon32" }, { "Id": 36, "GameId": 720, "Name": "Logo" }, { "Id": 37, "GameId": 720, "Name": "CoverLogo" }, { "Id": 38, "GameId": 720, "Name": "Background" } ], "GameFiles": [ { "Id": 200, "GameId": 720, "IsRequired": true, "FileName": "Albion-Online.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 721, "Name": "Battlerite", "Slug": "battlerite", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 721, "Name": "Cover" }, { "Id": 33, "GameId": 721, "Name": "Icon16" }, { "Id": 34, "GameId": 721, "Name": "Icon24" }, { "Id": 35, "GameId": 721, "Name": "Icon32" }, { "Id": 36, "GameId": 721, "Name": "Logo" }, { "Id": 37, "GameId": 721, "Name": "CoverLogo" }, { "Id": 38, "GameId": 721, "Name": "Background" } ], "GameFiles": [ { "Id": 199, "GameId": 721, "IsRequired": true, "FileName": "Battlerite.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 722, "Name": "FIFA 17", "Slug": "FIFA17", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 722, "Name": "Cover" }, { "Id": 33, "GameId": 722, "Name": "Icon16" }, { "Id": 34, "GameId": 722, "Name": "Icon24" }, { "Id": 35, "GameId": 722, "Name": "Icon32" }, { "Id": 36, "GameId": 722, "Name": "Logo" }, { "Id": 37, "GameId": 722, "Name": "CoverLogo" }, { "Id": 38, "GameId": 722, "Name": "Background" } ], "GameFiles": [ { "Id": 206, "GameId": 722, "IsRequired": true, "FileName": "FIFA17.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 724, "Name": "Breakaway", "Slug": "breakaway", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 724, "Name": "Cover" }, { "Id": 33, "GameId": 724, "Name": "Icon16" }, { "Id": 34, "GameId": 724, "Name": "Icon24" }, { "Id": 35, "GameId": 724, "Name": "Icon32" }, { "Id": 36, "GameId": 724, "Name": "Logo" }, { "Id": 37, "GameId": 724, "Name": "CoverLogo" }, { "Id": 38, "GameId": 724, "Name": "Background" } ], "GameFiles": [ { "Id": 211, "GameId": 724, "IsRequired": true, "FileName": "Relay_x64.exe ", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 725, "Name": "Streamline", "Slug": "streamline", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 725, "Name": "Cover" }, { "Id": 33, "GameId": 725, "Name": "Icon16" }, { "Id": 34, "GameId": 725, "Name": "Icon24" }, { "Id": 35, "GameId": 725, "Name": "Icon32" }, { "Id": 36, "GameId": 725, "Name": "Logo" }, { "Id": 37, "GameId": 725, "Name": "CoverLogo" }, { "Id": 38, "GameId": 725, "Name": "Background" } ], "GameFiles": [], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": false, "BundleAssets": false }, { "ID": 726, "Name": "Gears of War 4", "Slug": "Gears4", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 726, "Name": "Cover" }, { "Id": 33, "GameId": 726, "Name": "Icon16" }, { "Id": 34, "GameId": 726, "Name": "Icon24" }, { "Id": 35, "GameId": 726, "Name": "Icon32" }, { "Id": 36, "GameId": 726, "Name": "Logo" }, { "Id": 37, "GameId": 726, "Name": "CoverLogo" }, { "Id": 38, "GameId": 726, "Name": "Background" } ], "GameFiles": [], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": false, "BundleAssets": false }, { "ID": 727, "Name": "Civilization VI", "Slug": "Civ6", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 727, "Name": "Cover" }, { "Id": 33, "GameId": 727, "Name": "Icon16" }, { "Id": 34, "GameId": 727, "Name": "Icon24" }, { "Id": 35, "GameId": 727, "Name": "Icon32" }, { "Id": 36, "GameId": 727, "Name": "Logo" }, { "Id": 37, "GameId": 727, "Name": "CoverLogo" }, { "Id": 38, "GameId": 727, "Name": "Background" } ], "GameFiles": [ { "Id": 210, "GameId": 727, "IsRequired": true, "FileName": "CivilizationVI.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 728, "Name": "Watchdogs", "Slug": "watchdogs", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 728, "Name": "Cover" }, { "Id": 33, "GameId": 728, "Name": "Icon16" }, { "Id": 34, "GameId": 728, "Name": "Icon24" }, { "Id": 35, "GameId": 728, "Name": "Icon32" }, { "Id": 36, "GameId": 728, "Name": "Logo" }, { "Id": 37, "GameId": 728, "Name": "CoverLogo" }, { "Id": 38, "GameId": 728, "Name": "Background" } ], "GameFiles": [], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": false, "BundleAssets": false }, { "ID": 729, "Name": "Watchdogs 2", "Slug": "watchdogs2", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 729, "Name": "Cover" }, { "Id": 33, "GameId": 729, "Name": "Icon16" }, { "Id": 34, "GameId": 729, "Name": "Icon24" }, { "Id": 35, "GameId": 729, "Name": "Icon32" }, { "Id": 36, "GameId": 729, "Name": "Logo" }, { "Id": 37, "GameId": 729, "Name": "CoverLogo" }, { "Id": 38, "GameId": 729, "Name": "Background" } ], "GameFiles": [ { "Id": 227, "GameId": 729, "IsRequired": true, "FileName": "Watchdogs2.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 730, "Name": "<NAME>", "Slug": "shadowwar2", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 730, "Name": "Cover" }, { "Id": 33, "GameId": 730, "Name": "Icon16" }, { "Id": 34, "GameId": 730, "Name": "Icon24" }, { "Id": 35, "GameId": 730, "Name": "Icon32" }, { "Id": 36, "GameId": 730, "Name": "Logo" }, { "Id": 37, "GameId": 730, "Name": "CoverLogo" }, { "Id": 38, "GameId": 730, "Name": "Background" } ], "GameFiles": [ { "Id": 244, "GameId": 730, "IsRequired": true, "FileName": "ShadowWarrior2.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 731, "Name": "<NAME>", "Slug": "mafia3", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 731, "Name": "Cover" }, { "Id": 33, "GameId": 731, "Name": "Icon16" }, { "Id": 34, "GameId": 731, "Name": "Icon24" }, { "Id": 35, "GameId": 731, "Name": "Icon32" }, { "Id": 36, "GameId": 731, "Name": "Logo" }, { "Id": 37, "GameId": 731, "Name": "CoverLogo" }, { "Id": 38, "GameId": 731, "Name": "Background" } ], "GameFiles": [ { "Id": 240, "GameId": 731, "IsRequired": true, "FileName": "mafia3.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 732, "Name": "Planet Coaster", "Slug": "planetcoaster", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 732, "Name": "Cover" }, { "Id": 33, "GameId": 732, "Name": "Icon16" }, { "Id": 34, "GameId": 732, "Name": "Icon24" }, { "Id": 35, "GameId": 732, "Name": "Icon32" }, { "Id": 36, "GameId": 732, "Name": "Logo" }, { "Id": 37, "GameId": 732, "Name": "CoverLogo" }, { "Id": 38, "GameId": 732, "Name": "Background" } ], "GameFiles": [ { "Id": 226, "GameId": 732, "IsRequired": true, "FileName": "PlanetCoaster.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 733, "Name": "Football Manager 2017", "Slug": "FM2017", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 733, "Name": "Cover" }, { "Id": 33, "GameId": 733, "Name": "Icon16" }, { "Id": 34, "GameId": 733, "Name": "Icon24" }, { "Id": 35, "GameId": 733, "Name": "Icon32" }, { "Id": 36, "GameId": 733, "Name": "Logo" }, { "Id": 37, "GameId": 733, "Name": "CoverLogo" }, { "Id": 38, "GameId": 733, "Name": "Background" } ], "GameFiles": [ { "Id": 241, "GameId": 733, "IsRequired": false, "FileName": "icudt57.dll", "FileType": 1, "PlatformType": 1 }, { "Id": 242, "GameId": 733, "IsRequired": false, "FileName": "fm.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 734, "Name": "NBA 2k17", "Slug": "NBA2k17", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 734, "Name": "Cover" }, { "Id": 33, "GameId": 734, "Name": "Icon16" }, { "Id": 34, "GameId": 734, "Name": "Icon24" }, { "Id": 35, "GameId": 734, "Name": "Icon32" }, { "Id": 36, "GameId": 734, "Name": "Logo" }, { "Id": 37, "GameId": 734, "Name": "CoverLogo" }, { "Id": 38, "GameId": 734, "Name": "Background" } ], "GameFiles": [ { "Id": 250, "GameId": 734, "IsRequired": true, "FileName": "NBA2K17.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 735, "Name": "Astroneer", "Slug": "astroneer", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 735, "Name": "Cover" }, { "Id": 33, "GameId": 735, "Name": "Icon16" }, { "Id": 34, "GameId": 735, "Name": "Icon24" }, { "Id": 35, "GameId": 735, "Name": "Icon32" }, { "Id": 36, "GameId": 735, "Name": "Logo" }, { "Id": 37, "GameId": 735, "Name": "CoverLogo" }, { "Id": 38, "GameId": 735, "Name": "Background" } ], "GameFiles": [ { "Id": 254, "GameId": 735, "IsRequired": true, "FileName": "Astro-Win64-Shipping.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false }, { "ID": 4402, "Name": "Tyranny", "Slug": "tyranny", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 31, "GameId": 4402, "Name": "Cover" }, { "Id": 33, "GameId": 4402, "Name": "Icon16" }, { "Id": 34, "GameId": 4402, "Name": "Icon24" }, { "Id": 35, "GameId": 4402, "Name": "Icon32" }, { "Id": 36, "GameId": 4402, "Name": "Logo" }, { "Id": 37, "GameId": 4402, "Name": "CoverLogo" }, { "Id": 38, "GameId": 4402, "Name": "Background" } ], "GameFiles": [ { "Id": 255, "GameId": 4402, "IsRequired": true, "FileName": "Tyranny.exe", "FileType": 2, "PlatformType": 4 } ], "GameDetectionHints": [], "FileParsingRules": [], "CategorySections": [], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": false, "SupportsVoice": false, "Order": 0, "SupportsNotifications": true, "BundleAssets": false } ]; <file_sep>/source/reducers/gamesReducer.ts import { GamesState } from "../state/GamesState"; import { FetchGamesStarted, FetchGamesSucceeded, FetchGamesFailed, SetDetailIndex, UpdateProgress, FETCH_GAMES_STARTED, FETCH_GAMES_SUCCEEDED, FETCH_GAMES_FAILED, SET_DETAIL_INDEX, UPDATE_PROGRESS, } from '../actions/games'; import { Game } from '../models/Game'; type Actions = FetchGamesStarted | FetchGamesSucceeded | FetchGamesFailed | SetDetailIndex | UpdateProgress; const initialState: GamesState = { games: [], isFetching: false, isError: false, detailIndex: null, progress: 0, }; export function gamesReducer(state: GamesState = initialState, action: Actions) { switch (action.type) { case UPDATE_PROGRESS: return Object.assign({}, state, { progress: action.progress }); case SET_DETAIL_INDEX: return Object.assign({}, state, { detailIndex: action.detailIndex }); case FETCH_GAMES_STARTED: return Object.assign({}, state, { isFetching: true, progress: 0 }); case FETCH_GAMES_FAILED: return Object.assign({}, state, { isFetching: false, isError: true }); case FETCH_GAMES_SUCCEEDED: const sortedGames = action.games.sort((gameA: Game, gameB: Game) => gameA.Order - gameB.Order); return Object.assign({}, state, { isFetching: false, isError: false, games: sortedGames }); default: return state; } } <file_sep>/source/__tests__/fixtures/index.ts import { GamesState } from '../../state/GamesState'; import { gamesData } from './gamesDataFixture'; export const initialStateFixture = { games: [], isFetching: false, isError: false, detailIndex: null, progress: 0, } as GamesState; export const gamesDataFixture = gamesData; export const gameData = { "ID": 1, "Name": "World of Warcraft", "Slug": "wow", "DateModified": "0001-01-01T00:00:00", "Assets": [ { "Id": 33, "GameId": 1, "Name": "Icon16" }, { "Id": 34, "GameId": 1, "Name": "Icon24" }, { "Id": 35, "GameId": 1, "Name": "Icon32" }, { "Id": 36, "GameId": 1, "Name": "Logo" } ], "GameFiles": [ { "Id": 1, "GameId": 1, "IsRequired": false, "FileName": "WoW.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 2, "GameId": 1, "IsRequired": false, "FileName": "WoW-64.exe", "FileType": 2, "PlatformType": 3 }, { "Id": 3, "GameId": 1, "IsRequired": false, "FileName": "World of Warcraft Launcher.exe", "FileType": 3, "PlatformType": 4 }, { "Id": 4, "GameId": 1, "IsRequired": false, "FileName": "world.MPQ.lock", "FileType": 4, "PlatformType": 1 }, { "Id": 151, "GameId": 1, "IsRequired": false, "FileName": "World of Warcraft.app", "FileType": 2, "PlatformType": 5 }, { "Id": 187, "GameId": 1, "IsRequired": false, "FileName": "WowB.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 188, "GameId": 1, "IsRequired": false, "FileName": "WowB-64.exe", "FileType": 2, "PlatformType": 3 }, { "Id": 189, "GameId": 1, "IsRequired": false, "FileName": "World of Warcraft Beta Launcher.exe", "FileType": 3, "PlatformType": 4 }, { "Id": 190, "GameId": 1, "IsRequired": false, "FileName": "WowT.exe", "FileType": 2, "PlatformType": 4 }, { "Id": 191, "GameId": 1, "IsRequired": false, "FileName": "WoWT-64.exe", "FileType": 2, "PlatformType": 3 }, { "Id": 192, "GameId": 1, "IsRequired": false, "FileName": "World of Warcraft Public Test Launcher.exe", "FileType": 3, "PlatformType": 4 }, { "Id": 195, "GameId": 1, "IsRequired": false, "FileName": "World of Warcraft Beta.app", "FileType": 2, "PlatformType": 5 }, { "Id": 196, "GameId": 1, "IsRequired": false, "FileName": "World of Warcraft Public Test.app", "FileType": 2, "PlatformType": 5 } ], "GameDetectionHints": [ { "ID": 2, "HintType": 1, "HintPath": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Blizzard Entertainment\\World of Warcraft", "HintKey": "InstallPath", "HintOptions": 0 }, { "ID": 3, "HintType": 1, "HintPath": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Blizzard Entertainment\\World of Warcraft", "HintKey": "InstallPath", "HintOptions": 0 }, { "ID": 4, "HintType": 1, "HintPath": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\VirtualStore\\MACHINE\\SOFTWARE\\Blizzard Entertainment\\World of Warcraft", "HintKey": "InstallPath", "HintOptions": 0 }, { "ID": 5, "HintType": 2, "HintPath": "%PROGRAMFILES(x86)%\\World of Warcraft", "HintKey": "", "HintOptions": 0 }, { "ID": 6, "HintType": 2, "HintPath": "%PROGRAMFILES%\\World of Warcraft", "HintKey": "", "HintOptions": 0 }, { "ID": 7, "HintType": 2, "HintPath": "%Public%\\Games\\World of Warcraft", "HintKey": "", "HintOptions": 0 }, { "ID": 1014, "HintType": 2, "HintPath": "/Applications/World of Warcraft", "HintKey": "", "HintOptions": 0 }, { "ID": 1026, "HintType": 1, "HintPath": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Blizzard Entertainment\\World of Warcraft\\PTR", "HintKey": "InstallPath", "HintOptions": 0 }, { "ID": 1027, "HintType": 1, "HintPath": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Blizzard Entertainment\\World of Warcraft\\PTR", "HintKey": "InstallPath", "HintOptions": 0 }, { "ID": 1028, "HintType": 1, "HintPath": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\VirtualStore\\MACHINE\\SOFTWARE\\Blizzard Entertainment\\World of Warcraft\\PTR", "HintKey": "InstallPath", "HintOptions": 0 }, { "ID": 1034, "HintType": 2, "HintPath": "%PROGRAMFILES(x86)%\\World of Warcraft Beta", "HintKey": "", "HintOptions": 0 }, { "ID": 1035, "HintType": 2, "HintPath": "%PROGRAMFILES%\\World of Warcraft Beta", "HintKey": "", "HintOptions": 0 } ], "FileParsingRules": [ { "CommentStripPattern": "(?s)<!--.*?-->", "FileExtension": ".xml", "InclusionPattern": "(?i)<(?:Include|Script)\\s+file=[\"\"']((?:(?<!\\.\\.).)+)[\"\"']\\s*/>" }, { "CommentStripPattern": "(?m)\\s*#.*$", "FileExtension": ".toc", "InclusionPattern": "(?mi)^\\s*((?:(?<!\\.\\.).)+\\.(?:xml|lua))\\s*$" } ], "CategorySections": [ { "ID": 1, "GameID": 1, "Name": "Addons", "PackageType": 1, "Path": "interface\\addons", "InitialInclusionPattern": "(?i)^([^/]+)[\\\\/]\\1\\.toc$", "ExtraIncludePattern": "(?i)^[^/\\\\]+[/\\\\]Bindings\\.xml$" } ], "MaxFreeStorage": 0, "MaxPremiumStorage": 0, "MaxFileSize": 0, "SupportsAddons": true, "SupportsVoice": false, "Order": 12, "SupportsNotifications": true, "BundleAssets": true };
864b59da7c368a63e177162dc4528257abf7ca40
[ "TypeScript", "Text" ]
10
Text
bartlett705/tango-sierra
20df23b965ee92d2b696000bd86f8b4829534e7c
39a253c1cdd74b034d7148b55826f52d72c121a7
refs/heads/master
<repo_name>lucas-clemente/seminar-macroscopicity<file_sep>/assets/js/main.js // Generated by CoffeeScript 1.6.2 (function() { var refs; refs = {}; $('[data-reflabel]').each(function() { var $this; $this = $(this); $this.addClass('reference'); $this.find('a').prepend('<i class="icon-file-alt"></i> '); return refs[$this.data('reflabel')] = $this; }); $('[data-ref]').each(function() { var $this, ref, refname; $this = $(this); refname = $this.data('ref'); ref = refs[refname]; if (!ref) { return console.warn('unresolved reference ' + refname); } return $this.prepend(ref.clone()); }); $('h1').each(function() { if (this.parentElement.id === "title") { return; } return $(this).prepend('<i class="icon-double-angle-right"></i> '); }); $(document).keypress(function(e) { if (e.keyCode !== 102) { return; } e.preventDefault(); if (document.documentElement.requestFullScreen) { return document.documentElement.requestFullScreen(); } else if (document.documentElement.mozRequestFullScreen) { return document.documentElement.mozRequestFullScreen(); } else if (document.documentElement.webkitRequestFullScreen) { return document.documentElement.webkitRequestFullScreen(); } }); }).call(this); <file_sep>/README.md # Wed Seminar about Macroscopicity Measures MPQ Theory group, <NAME>, 2013-05-15 See it in action [here](https://clemente.io/seminar-macroscopicity/), or have a look at the sources. Made using [impress.js](https://github.com/bartaz/impress.js/). Image references can be found in the [source](/index.html).
88b85d63fb589fbe9aa4ad2844e51a97a550707a
[ "JavaScript", "Markdown" ]
2
JavaScript
lucas-clemente/seminar-macroscopicity
3988b6a5649e34a2dba1ced9403f43cb3e62b81b
3fdd0d1376fc28c3e35903f66e22dafe0306792b
refs/heads/master
<repo_name>wsaunders1014/CodeIgniterTestBuild<file_sep>/api/application/models/Theatres_model.php <?php class Theatres_model extends CI_Model { public function __construct(){ $this->load->database(); } public function get_theatres(){ $query = $this->db->get('theatres'); return $query->result_array(); } public function post_theatres($name,$zip,$city){ $data = array('name'=> $name,'zipcode'=>$zip,'city'=>$city); return $this->db->insert('theatres',$data); } }<file_sep>/api/application/views/admin/theatres_view.php <div class="row"> <div class="col-lg-4 col-lg-offset-4"> <?php foreach ($theatres as $theatre) { ?> <li><?php echo $theatre['name']; ?></li> <?php } ?> </div> </div>
38cef06146b29edc28f056d18f890abbfe0d505a
[ "PHP" ]
2
PHP
wsaunders1014/CodeIgniterTestBuild
940ea89b5335d50e5c2326576c8778d9619a1d33
cfae8c937cb0f2cdb8b7d312cb29653df9aa1e8f
refs/heads/master
<repo_name>ska-telescope/csp-lmc-prototype<file_sep>/Dockerfile FROM nexus.engageska-portugal.pt/ska-docker/ska-python-buildenv:0.2.2 AS buildenv FROM nexus.engageska-portugal.pt/ska-docker/ska-python-runtime:0.2.2 AS runtime # create ipython profile to so that itango doesn't fail if ipython hasn't run yet RUN ipython profile create #install lmc-base-classes USER root RUN DEBIAN_FRONTEND=noninteractive pip3 install https://nexus.engageska-portugal.pt/repository/pypi/packages/lmcbaseclasses/0.1.3+163bf057/lmcbaseclasses-0.1.3+163bf057.tar.gz CMD ["/venv/bin/python", "/app/csplmc/CspMaster/CspMaster.py"] <file_sep>/csplmc/CspTelState/README.md The development of this device has been stopped. Need to evaluate if its functionality can be or not implemented at CspSubarray level. The current implementation of the MVP does not rely on the CspTelState TANGO Device to provide the configuration information to SDP. <file_sep>/csplmc/CbfTestMaster/CbfTestMaster.py # -*- coding: utf-8 -*- # # This file is part of the CbfTestMaster project # # # # Distributed under the terms of the GPL license. # See LICENSE.txt for more info. """ CSP.LMC subelement Test Master Tango device prototype Test TANGO device class to test connection with the CSPMaster prototype. It simulates the CbfMaster sub-element. """ from __future__ import absolute_import import sys import os import time file_path = os.path.dirname(os.path.abspath(__file__)) module_path = os.path.abspath(os.path.join(file_path, os.pardir)) sys.path.insert(0, module_path) # Tango imports import tango from tango import DebugIt from tango.server import run from tango.server import Device, DeviceMeta from tango.server import attribute, command from tango.server import device_property from tango import AttrQuality, DispLevel, DevState from tango import AttrWriteType, PipeWriteType # Additional import # PROTECTED REGION ID(CbfTestMaster.additionnal_import) ENABLED START # from future.utils import with_metaclass import threading from commons.global_enum import HealthState from skabase.SKAMaster.SKAMaster import SKAMaster # PROTECTED REGION END # // CbfTestMaster.additionnal_import __all__ = ["CbfTestMaster", "main"] class CbfTestMaster(with_metaclass(DeviceMeta,SKAMaster)): """ CbfTestMaster TANGO device class to test connection with the CSPMaster prototype """ # PROTECTED REGION ID(CbfTestMaster.class_variable) ENABLED START # # PROTECTED REGION END # // CbfTestMaster.class_variable # ----------------- # Device Properties # ----------------- # ---------- # Attributes # ---------- commandProgress = attribute( dtype='uint16', label="Command progress percentage", max_value=100, min_value=0, polling_period=1000, abs_change=5, rel_change=2, doc="Percentage progress implemented for commands that result in state/mode transitions for a large \nnumber of components and/or are executed in stages (e.g power up, power down)", ) vccCapabilityAddress = attribute( dtype=('str',), max_dim_x=197, ) fspCapabilityAddress = attribute( dtype=('str',), max_dim_x=27, ) reportVCCState = attribute( dtype=('DevState',), max_dim_x=197, ) reportVccHealthState = attribute( dtype=('uint16',), max_dim_x=197, ) reportVCCAdminMode = attribute( dtype=('uint16',), max_dim_x=197, ) reportFSPState = attribute( dtype=('DevState',), max_dim_x=27, ) reportFSPHealthState = attribute( dtype=('uint16',), max_dim_x=27, ) reportFSPAdminMode = attribute( dtype=('uint16',), max_dim_x=27, ) reportFSPSubarrayMembership = attribute( dtype=('uint16',), max_dim_x=27, ) reportVCCSubarrayMembership = attribute( dtype=('uint16',), max_dim_x=197, ) # --------------- # General methods # --------------- def init_subelement(self): """ Simulate the sub-element device initialization """ self.set_state(tango.DevState.STANDBY) def on_subelement(self): """ Simulate the sub-element transition from STANDBY to ON """ self.set_state(tango.DevState.ON) self._health_state = HealthState.DEGRADED.value def standby_subelement(self): """ Simulate the sub-element transition from ON to STANDBY """ self.set_state(tango.DevState.STANDBY) self._health_state = HealthState.DEGRADED.value def off_subelement(self): """ Simulate the sub-element transition from STANDBY to OFF """ self.set_state(tango.DevState.OFF) self._health_state = HealthState.UNKNOWN.value def init_device(self): SKAMaster.init_device(self) # PROTECTED REGION ID(CbfTestMaster.init_device) ENABLED START # self.set_state(tango.DevState.INIT) self._health_state = HealthState.UNKNOWN.value # start a timer to simulate device intialization thread = threading.Timer(1, self.init_subelement) thread.start() # PROTECTED REGION END # // CbfTestMaster.init_device def always_executed_hook(self): # PROTECTED REGION ID(CbfTestMaster.always_executed_hook) ENABLED START # pass # PROTECTED REGION END # // CbfTestMaster.always_executed_hook def delete_device(self): # PROTECTED REGION ID(CbfTestMaster.delete_device) ENABLED START # pass # PROTECTED REGION END # // CbfTestMaster.delete_device # ------------------ # Attributes methods # ------------------ def read_commandProgress(self): # PROTECTED REGION ID(CbfTestMaster.commandProgress_read) ENABLED START # return 0 # PROTECTED REGION END # // CbfTestMaster.commandProgress_read def read_vccCapabilityAddress(self): # PROTECTED REGION ID(CbfTestMaster.vccCapabilityAddress_read) ENABLED START # return [''] # PROTECTED REGION END # // CbfTestMaster.vccCapabilityAddress_read def read_fspCapabilityAddress(self): # PROTECTED REGION ID(CbfTestMaster.fspCapabilityAddress_read) ENABLED START # return [''] # PROTECTED REGION END # // CbfTestMaster.fspCapabilityAddress_read def read_reportVCCState(self): # PROTECTED REGION ID(CbfTestMaster.reportVCCState_read) ENABLED START # return [tango.DevState.UNKNOWN] # PROTECTED REGION END # // CbfTestMaster.reportVCCState_read def read_reportVccHealthState(self): # PROTECTED REGION ID(CbfTestMaster.reportVccHealthState_read) ENABLED START # return [0] # PROTECTED REGION END # // CbfTestMaster.reportVccHealthState_read def read_reportVCCAdminMode(self): # PROTECTED REGION ID(CbfTestMaster.reportVCCAdminMode_read) ENABLED START # return [0] # PROTECTED REGION END # // CbfTestMaster.reportVCCAdminMode_read def read_reportFSPState(self): # PROTECTED REGION ID(CbfTestMaster.reportFSPState_read) ENABLED START # return [tango.DevState.UNKNOWN] # PROTECTED REGION END # // CbfTestMaster.reportFSPState_read def read_reportFSPHealthState(self): # PROTECTED REGION ID(CbfTestMaster.reportFSPHealthState_read) ENABLED START # return [0] # PROTECTED REGION END # // CbfTestMaster.reportFSPHealthState_read def read_reportFSPAdminMode(self): # PROTECTED REGION ID(CbfTestMaster.reportFSPAdminMode_read) ENABLED START # return [0] # PROTECTED REGION END # // CbfTestMaster.reportFSPAdminMode_read def read_reportFSPSubarrayMembership(self): # PROTECTED REGION ID(CbfTestMaster.fspMembership_read) ENABLED START # return [0] # PROTECTED REGION END # // CbfTestMaster.fspMembership_read def read_reportVCCSubarrayMembership(self): # PROTECTED REGION ID(CbfTestMaster.vccMembership_read) ENABLED START # return [0] # PROTECTED REGION END # // CbfTestMaster.vccMembership_read # -------- # Commands # -------- @command( dtype_in=('str',), doc_in="If the array length is0, the command apllies to the whole\nCSP Element.\nIf the array length is > 1, each array element specifies the FQDN of the\nCSP SubElement to switch ON.", ) @DebugIt() def On(self, argin): # PROTECTED REGION ID(CbfTestMaster.On) ENABLED START # thread = threading.Timer(2, self.on_subelement) thread.start() # PROTECTED REGION END # // CbfTestMaster.On @command( dtype_in=('str',), doc_in="If the array length is0, the command apllies to the whole\nCSP Element.\nIf the array length is > 1, each array element specifies the FQDN of the\nCSP SubElement to switch OFF.", ) @DebugIt() def Off(self, argin): # PROTECTED REGION ID(CbfTestMaster.Off) ENABLED START # thread = threading.Timer(1, self.off_subelement) thread.start() # PROTECTED REGION END # // CbfTestMaster.Off @command( dtype_in=('str',), doc_in="If the array length is0, the command apllies to the whole\nCSP Element.\n\ If the array length is > 1, each array element specifies the FQDN of the\n\ CSP SubElement to switch OFF.", ) @DebugIt() def Standby(self, argin): # PROTECTED REGION ID(CbfTestMaster.Standby) ENABLED START # thread = threading.Timer(2, self.standby_subelement) thread.start() # PROTECTED REGION END # // CbfTestMaster.Standby def is_Off_allowed(self): # PROTECTED REGION ID(CbfTestMaster.is_Off_allowed) ENABLED START # if self.get_state() not in [DevState.STANDBY]: return False return True # PROTECTED REGION END # // CbfTestMaster.is_Off_allowed. def is_Standby_allowed(self): # PROTECTED REGION ID(CbfTestMaster.is_Standby_allowed) ENABLED START # if self.get_state() not in [DevState.ON, DevState.OFF]: return False return True # PROTECTED REGION END # // CbfTestMaster.is_Standby_allowed def is_On_allowed(self): # PROTECTED REGION ID(CbfTestMaster.is_On_allowed) ENABLED START # if self.get_state() not in [DevState.STANDBY]: return False return True # PROTECTED REGION END # // CbfTestMaster.is_On_allowed # ---------- # Run server # ---------- def main(args=None, **kwargs): # PROTECTED REGION ID(CbfTestMaster.main) ENABLED START # return run((CbfTestMaster,), args=args, **kwargs) # PROTECTED REGION END # // CbfTestMaster.main if __name__ == '__main__': main() <file_sep>/csplmc/CspSubarray/CspSubarray/CspSubarray.py # -*- coding: utf-8 -*- # # This file is part of the CspSubarray project # # # # Distributed under the terms of the GPL license. # See LICENSE.txt for more info. """ **CspSubarray TANGO Device Class** CSP subarray functionality is modeled via a TANGO Device Class, named *CspSubarray*. This class exports a set of attributes and methods required for configuration, control and monitoring of the subarray. """ # PROTECTED REGION ID (CspSubarray.standardlibray_import) ENABLED START # # Python standard library # Python standard library from __future__ import absolute_import import sys import os from future.utils import with_metaclass from collections import defaultdict # PROTECTED REGION END# //CspMaster.standardlibray_import # tango imports import tango from tango import DebugIt, EventType, DeviceProxy, AttrWriteType from tango.server import run, DeviceMeta, attribute, command, device_property, class_property # Additional import # PROTECTED REGION ID(CspMaster.additionnal_import) ENABLED START # # #import global_enum as const from skabase.SKASubarray import SKASubarray import json # PROTECTED REGION END # // CspMaster.additionnal_import # PROTECTED REGION ID (CspSubarray.add_path) ENABLED START # # add the path to import global_enum package. file_path = os.path.dirname(os.path.abspath(__file__)) commons_pkg_path = os.path.abspath(os.path.join(file_path, "../../commons")) sys.path.insert(0, commons_pkg_path) from global_enum import HealthState, AdminMode, ObsState, ObsMode # PROTECTED REGION END# //CspSubarray.add_path __all__ = ["CspSubarray", "main"] class CspSubarray(with_metaclass(DeviceMeta, SKASubarray)): """ CSP subarray functionality is modeled via a TANGO Device Class, named *CspSubarray*. This class exports a set of attributes and methods required for configuration, control and monitoring of the subarray. """ # PROTECTED REGION ID(CspSubarray.class_variable) ENABLED START # # --------------- # Event Callback functions # --------------- def __cmd_ended(self, evt): """ Method immediately executed when the asynchronous invoked command returns. Args: evt: A CmdDoneEvent object. This class is used to pass data to the callback method in asynchronous callback model for command execution. It has the following members: - device : (DeviceProxy) The DeviceProxy object on which the call was executed. - cmd_name : (str) The command name - argout_raw : (DeviceData) The command argout - argout : The command argout - err : (bool) A boolean flag set to true if the command failed. False otherwise - errors : (sequence<DevError>) The error stack - ext Returns: None """ # NOTE:if we try to access to evt.cmd_name or other paramters, sometime # the callback crashes withthis error: # terminate called after throwing an instance of 'boost::python::error_already_set' # try: # Can happen evt empty?? if evt: if not evt.err: msg = "Device {} is processing command {}".format(evt.device, evt.cmd_name) # TODO: # update the valid_scan_configuration attribute. If the command # is running the configuration has been validated # if cmd == "ConfigureScan": # ....... self.dev_logging(msg, tango.LogLevel.LOG_INFO) else: msg = "Error in executing command {} ended on device {}.\n".format(evt.cmd_name, evt.device) msg += " Desc: {}".format(evt.errors[0].desc) self.dev_logging(msg, tango.LogLevel.LOG_ERROR) # obsState and obsMode values take on the CbfSubarray's values via # the subscribe/publish mechanism else: self.dev_logging("cmd_ended callback: evt is empty!!", tango.LogLevel.LOG_ERRO) except tango.DevFailed as df: msg = ("CommandCallback cmd_ended failure - desc: {}" " reason: {}".format(df.args[0].desc, df.args[0].reason)) self.dev_logging(msg, tango.LogLevel.LOG_ERROR) except Exception as ex: msg = "CommandCallBack cmd_ended general exception: {}".format(str(ex)) self.dev_logging(msg, tango.LogLevel.LOG_ERROR) def __scm_change_callback(self, evt): """ *Class private method.* Retrieve the values of the sub-element sub-arrays SCM attributes subscribed for change event at device initialization. Args: evt: The event data Returns: None """ try: dev_name = evt.device.dev_name() if not evt.err: # check if the device name is in the list of the subarray fqdn if dev_name in self._se_subarrays_fqdn: if evt.attr_value.name.lower() == "healthstate": self._se_subarray_healthstate[dev_name] = evt.attr_value.value elif evt.attr_value.name.lower() == "state": self._se_subarray_state[dev_name] = evt.attr_value.value elif evt.attr_value.name.lower() == "adminmode": self._se_subarray_adminmode[dev_name] = evt.attr_value.value elif evt.attr_value.name.lower() == "obsstate": # look for transition from SCANNING to READY/IDLE before # storing the new value into the attribute if self._se_subarray_obsstate[dev_name] == ObsState.SCANNING: if evt.attr_value.value in [ObsState.READY, ObsState.IDLE]: self.dev_logging("Scan ended on subarray {}".format(dev_name), tango.LogLevel.LOG_INFO) self._se_subarray_obsstate[dev_name] = evt.attr_value.value else: self.dev_logging(("Attribute {} not yet handled".format(evt.attr_name)), tango.LogLevel.LOG_ERR) else: log_msg = ("Unexpected change event for" " attribute: {}".format(str(evt.attr_name))) self.dev_logging(log_msg, tango.LogLevel.LOG_WARN) return # update the SCM values for the CSP subarray if evt.attr_value.name.lower() in ["state", "healthstate"]: self.__set_subarray_state() if evt.attr_value.name.lower() == "obsstate": self.__set_subarray_obs_state() else: for item in evt.errors: # TODO:handle API_EventTimeout log_msg = "{}: on attribute {}".format(item.reason, str(evt.attr_name)) self.dev_logging(log_msg, tango.LogLevel.LOG_WARN) # NOTE: received when a command execution takes more than 3 sec. # (TANGO TIMEOUT default value) if item.reason == "API_CommandTimeout": self.dev_logging(("Command Timeout out"), tango.LogLevel.LOG_WARN) except tango.DevFailed as df: self.dev_logging(str(df.args[0].desc), tango.LogLevel.LOG_ERR) # # Class private methods # def __connect_to_subarrays(self): """ *Class private method.* Establish connection with each sub-element subarray. If connection succeeds, the CspSubarray device subscribes the State, healthState and adminMode attributes of each Sub-element subarray and registers a callback function to handle the events. Exceptions are logged. Returns: None Raises: tango.DevFailed: raises an exception if connection with a sub-element subarray fails """ subarrays_fqdn = [] subarrays_fqdn.append(self._cbf_subarray_fqdn) subarrays_fqdn.append(self._pss_subarray_fqdn) for fqdn in subarrays_fqdn: # initialize the list for each dictionary key-name self._se_subarray_event_id[fqdn] = [] try: log_msg = "Trying connection to {} device".format(str(fqdn)) self.dev_logging(log_msg, int(tango.LogLevel.LOG_INFO)) device_proxy = DeviceProxy(fqdn) device_proxy.ping() # add to the FQDN subarray list, only the subarrays # available in the TANGO DB self._se_subarrays_fqdn.append(fqdn) # store the Sub-elements subarray proxies self._se_subarrays_proxies[fqdn] = device_proxy # Subscription of the Sub-element subarray SCM states ev_id = device_proxy.subscribe_event("State", EventType.CHANGE_EVENT, self.__scm_change_callback, stateless=True) self._se_subarray_event_id[fqdn].append(ev_id) ev_id = device_proxy.subscribe_event("healthState", EventType.CHANGE_EVENT, self.__scm_change_callback, stateless=True) self._se_subarray_event_id[fqdn].append(ev_id) ev_id = device_proxy.subscribe_event("obsState", EventType.CHANGE_EVENT, self.__scm_change_callback, stateless=True) self._se_subarray_event_id[fqdn].append(ev_id) ev_id = device_proxy.subscribe_event("adminMode", EventType.CHANGE_EVENT, self.__scm_change_callback, stateless=True) self._se_subarray_event_id[fqdn].append(ev_id) except tango.DevFailed as df: for item in df.args: if "DB_DeviceNotDefined" in item.reason: log_msg = ("Failure in connection to {}" " device: {}".format(str(fqdn), str(item.reason))) self.dev_logging(log_msg, tango.LogLevel.LOG_ERROR) tango.Except.throw_exception(df.args[0].reason, "Connection to {} failed".format(fqdn), "Connect to subarrays", tango.ErrSeverity.ERR) def __connect_to_master(self): """ *Class private method.* Establish connection with the CSP Master and Sub-element Master devices to get information about: * the CBF/PSS/PST Master address * the max number of CBF capabilities for each supported capability type Returns: None Raises: DevFailed: when connections to the CspMaster and sub-element Master devices fail. """ try: self.dev_logging("Trying connection to {}".format(self.CspMaster), tango.LogLevel.LOG_INFO) cspMasterProxy = tango.DeviceProxy(self.CspMaster) cspMasterProxy.ping() # get the list of CSP capabilities to recover the max number of # capabilities for each type self._csp_capabilities = cspMasterProxy.maxCapabilities # try connection to CbfMaster to get information about the number of # capabilities and the receptor/vcc mapping if cspMasterProxy.cbfAdminMode in [AdminMode.ONLINE, AdminMode.MAINTENANCE]: self._cbfAddress = cspMasterProxy.cbfMasterAddress self._cbfMasterProxy = tango.DeviceProxy(self._cbfAddress) self._cbfMasterProxy.ping() cbf_capabilities = self._cbfMasterProxy.maxCapabilities # build the list of receptor ids receptor_to_vcc = self._cbfMasterProxy.receptorToVcc self._receptor_to_vcc_map = dict([int(ID) for ID in pair.split(":")] for pair in receptor_to_vcc) # build the list of the installed receptors self._receptor_id_list = list(self._receptor_to_vcc_map.keys()) for _, cap_string in enumerate(cbf_capabilities): cap_type, cap_num = cap_string.split(':') self._cbf_capabilities[cap_type] = int(cap_num) # try connection to PssMaster # Do we need to connect to PssMaster? # All SearchBeams information should be available via the CspMaster if cspMasterProxy.pssAdminMode in [AdminMode.ONLINE, AdminMode.MAINTENANCE]: self._pssAddress = cspMasterProxy.pssMasterAddress self._pssMasterProxy = tango.DeviceProxy(self._pssAddress) self._pssMasterProxy.ping() #TODO: retrieve information about the available SearchBeams # try connection to PstMaster # Do we need to connect to PstMaster? # All TimingBeams information should be available via the CspMaster if cspMasterProxy.pstAdminMode in [AdminMode.ONLINE, AdminMode.MAINTENANCE]: self._pstAddress = cspMasterProxy.pstMasterAddress self._pstMasterProxy = tango.DeviceProxy(self._pstAddress) self._pstMasterProxy.ping() #TODO: retrieve information about the available TimingBeams except AttributeError as attr_err: msg = "Attribute error: {}".format(str(attr_err)) self.dev_logging(msg, tango.LogLevel.LOG_ERROR) except tango.DevFailed as df: tango.Except.throw_exception("Connection Failed", df.args[0].desc, "connect_to_master", tango.ErrSeverity.ERR) def __is_subarray_available(self, subarray_name): """ *Class private method.* Check if the sub-element subarray is exported in the TANGO DB. If the subarray device is not present in the list of the connected subarrays, the connection with the device is performed. Args: subarray_name : the FQDN of the subarray Returns: True if the connection with the subarray is established, False otherwise """ try: proxy = self._se_subarrays_proxies[subarray_name] proxy.ping() except KeyError: # Raised when a mapping (dictionary) key is not found in the set # of existing keys. # no proxy registered for the subarray device proxy = tango.DeviceProxy(subarray_name) proxy.ping() self._se_subarrays_proxies[subarray_name] = proxy except tango.DevFailed: return False return True def __set_subarray_state(self): """ *Class private method* Set the subarray State and healthState. Args: None Returns: None """ self.set_state(self._se_subarray_state[self._cbf_subarray_fqdn]) self._health_state = HealthState.DEGRADED if ((self._se_subarray_healthstate[self._cbf_subarray_fqdn] == HealthState.FAILED) or \ (self._se_subarray_state[self._cbf_subarray_fqdn] == tango.DevState.FAULT)): self._health_state = HealthState.FAILED self.set_state(tango.DevState.FAULT) if len(self._se_subarray_healthstate) == 3 and \ list(self._se_subarray_healthstate.values()) == [HealthState.OK, HealthState.OK, HealthState.OK]: self._health_state = HealthState.OK def __set_subarray_obs_state(self): """ *Class private method* Set the subarray obsState attribute value. It works only for IMAGING. Args: None Returns: None """ # NOTE: when ObsMode value is set, it should be considered to set the final # sub-array ObsState value cbf_sub_obstate = self._se_subarray_obsstate[self._cbf_subarray_fqdn] # next line currently not used # pss_sub_obstate = self._se_subarray_obsstate[self._pss_subarray_fqdn] # TODO: how implement ObsState for PST? # Next lines are valid only for IMAGING mode!! self._obs_state = cbf_sub_obstate if cbf_sub_obstate == ObsState.IDLE: self._obs_mode = ObsMode.IDLE # TODO:ObsMode could be defined as a mask because we can have more # than one obs_mode active for a sub-array def __is_remove_resources_allowed(self): """ **Class private method ** *TANGO is_allowed method*: filter the external request depending on the \ current device state.\n Check if the method to release the allocated resources can be issued\n Resources can be removed from a subarray when its *State* is ON or OFF- Returns: True if the command can be executed, otherwise False """ if self.get_state() in [tango.DevState.ON, tango.DevState.OFF]: return True return False def __is_add_resources_allowed(self): """ **Class private method ** *TANGO is_allowed method*: filter the external request depending on the \ current device state.\n Check if the method to add resources to a subarraycan be issued\n Resources can be assigned to a subarray when its *State* is OFF or ON- Returns: True if the command can be executed, otherwise False """ if self.get_state() in [tango.DevState.ON, tango.DevState.OFF]: return True return False # PROTECTED REGION END # // CspSubarray.class_variable # ----------------- # Class Properties # ----------------- CbfSubarrayPrefix = class_property( dtype='str', default_value="mid_csp_cbf/sub_elt/subarray_" ) """ *Class property* The CBF sub-element subarray FQDN prefix. *Type*: DevString Example: *mid_csp_cbf/sub_elt/subarray_* """ PssSubarrayPrefix = class_property( dtype='str', default_value="mid_csp_pss/sub_elt/subarray_" ) """ *Class property* The PSS sub-element subarray FQDN prefix. *Type*: DevString Example: *mid_csp_pss/sub_elt/subarray_* """ # ----------------- # Device Properties # ----------------- CspMaster = device_property( dtype='str', default_value="mid_csp/elt/master" ) """ *Device property* The CspMaster FQDN. *Type*: DevString """ # ---------- # Attributes # ---------- scanID = attribute( dtype='uint64', access=AttrWriteType.READ_WRITE, ) """ *Class attribute* The identification number of the scan. *Type*: DevULong64 """ corrInherentCap = attribute( dtype='str', ) """ *Class attribute* The CspSubarray Correlation inherent Capability FQDN. *Type*: DevString\n """ pssInherentCap = attribute( dtype='str', ) """ *Class attribute* The CspSubarray Pss inherent Capability FQDN. *Type*: DevString """ pstInherentCap = attribute( dtype='str', ) """ *Class attribute* The CspSubarray Pst inherent Capability FQDN. *Type*: DevString """ vlbiInherentCap = attribute( dtype='str', ) """ *Class attribute* The CspSubarray Vlbi inherent Capability FQDN. *Type*: DevString """ cbfSubarrayState = attribute( dtype='DevState', ) """ *Class attribute* The CBF sub-element subarray State attribute value. *Type*: DevState """ pssSubarrayState = attribute( dtype='DevState', ) """ *Class attribute* The PSS sub-element subarray State attribute value. *Type*: DevState """ cbfSubarrayHealthState = attribute( dtype='DevEnum', label="CBF Subarray Health State", doc="CBF Subarray Health State", enum_labels=["OK", "DEGRADED", "FAILED", "UNKNOWN", ], ) """ *Class attribute* The CBF sub-element subarray healthState attribute value. *Type*: DevEnum *enum_labels*: ["OK", "DEGRADED", "FAILED", "UNKNOWN", ] """ pssSubarrayHealthState = attribute( dtype='DevEnum', label="PSS Subarray Health State", doc="PSS Subarray Health State", enum_labels=["OK", "DEGRADED", "FAILED", "UNKNOWN", ], ) """ *Class attribute* The PSS sub-element subarray healthState attribute value. *Type*: DevEnum *enum_labels*: ["OK", "DEGRADED", "FAILED", "UNKNOWN", ] """ cbfSubarrayObsState = attribute( dtype='DevEnum', label="CBF Subarray Observing State", doc="The CBF subarray observing state.", enum_labels=["IDLE", "CONFIGURING", "READY", "SCANNING", "PAUSED", "ABORTED", "FAULT", ], ) """ *Class attribute* The CBF sub-element subarray obsState attribute value. *Type*: DevEnum *enum_labels*: ["IDLE", "CONFIGURING", "READY", "SCANNING", "PAUSED", "ABORTED", "FAULT", ] """ pssSubarrayObsState = attribute( dtype='DevEnum', label="PSS Subarray Observing State", doc="The PSS subarray observing state.", enum_labels=["IDLE", "CONFIGURING", "READY", "SCANNING", "PAUSED", "ABORTED", "FAULT", ], ) """ *Class attribute* The PSS sub-element subarray obsState attribute value. *Type*: DevEnum *enum_labels*: ["IDLE", "CONFIGURING", "READY", "SCANNING", "PAUSED", "ABORTED", "FAULT", ] """ pssSubarrayAddr = attribute( dtype='str', doc="The PSS Subarray TANGO address.", ) """ *Class attribute* The PSS sub-element subarray FQDN. *Type*: DevString """ cbfSubarrayAddr = attribute( dtype='str', doc="The CBF Subarray TANGO address.", ) """ *Class attribute* The CBF sub-element subarray FQDN. *Type*: DevString """ validScanConfiguration = attribute( dtype='str', label="Valid Scan Configuration", doc="Store the last valid scan configuration.", ) """ *Class attribute* The last valid scan configuration JSON-encoded string. *Type*: DevString """ fsp = attribute( dtype=('uint16',), max_dim_x=27, ) """ *Class attribute* The list of receptor IDs assigned to the subarray. *Type*: array of DevUShort """ vcc = attribute( dtype=('uint16',), max_dim_x=197, ) """ *Class attribute* The list of VCC IDs assigned to the subarray. *Type*: array of DevUShort """ searchBeams = attribute( dtype=('uint16',), max_dim_x=1500, ) """ *Class attribute* The list of Search Beam Capability IDs assigned to the subarray. *Type*: array of DevUShort """ timingBeams = attribute( dtype=('uint16',), max_dim_x=16, ) """ *Class attribute* The list of Timing Beam Capability IDs assigned to the subarray. *Type*: array of DevUShort """ vlbiBeams = attribute( dtype=('uint16',), max_dim_x=20, ) """ *Class attribute* The list of Vlbi Beam Capability IDs assigned to the subarray. *Type*: array of DevUShort """ searchBeamsState = attribute( dtype=('DevState',), max_dim_x=1500, ) """ *Class attribute* The *State* attribue value of the Search Beam Capabilities assigned to the subarray. *Type*: array of DevState """ timingBeamsState = attribute( dtype=('DevState',), max_dim_x=16, ) """ *Class attribute* The *State* attribue value of the Timing Beam Capabilities assigned to the subarray. *Type*: array of DevState """ vlbiBeamsState = attribute( dtype=('DevState',), max_dim_x=20, ) """ *Class attribute* The *State* attribue value of the Vlbi Beam Capabilities assigned to the subarray. *Type*: array of DevState """ searchBeamsHealthState = attribute( dtype=('uint16',), max_dim_x=1500, doc="The healthState ttribute value of the Search Beams Capbilities \ assigned to the subarray.", ) """ *Class attribute* The *healthState* attribute value of the Search Beams Capbilities assigned to the subarray. *Type*: array of DevUShort. References: See *Common definition* paragraph for corrispondences among Ushort values and label """ timingBeamsHealthState = attribute( dtype=('uint16',), max_dim_x=16, ) """ *Class attribute* The *healthState* attribute value of the Timing Beams Capbilities assigned to the subarray. *Type*: array of DevUShort. References: See *Common definition* paragraph for corrispondences among Ushort values and label """ vlbiBeamsHealthState = attribute( dtype=('uint16',), max_dim_x=20, ) """ *Class attribute* The *healthState* attribute value of the Vlbi Beams Capbilities assigned to the subarray. *Type*: array of DevUShort. References: See *Common definition* paragraph for corrispondences among Ushort values \ and healthState labels. """ timingBeamsObsState = attribute( dtype=('uint16',), max_dim_x=16, label="Timing Beams obsState", doc="The observation state of assigned timing beams.", ) """ *Class attribute* The *obsState* attribute value of the Timing Beams Capbilities assigned to the subarray. *Type*: array of DevUShort. References: See *Common definition* paragraph for corrispondences among Ushort values \ and obsState labels. """ receptors = attribute(name="receptors", label="receptors", forwarded=True) """ The list of receptors assigned to the subarray. *Forwarded attribute* *_root_att*: mid_csp_cbf/sub_elt/subarray_N/receptors """ vccState = attribute(name="vccState", label="vccState", forwarded=True) """ The State attribute value of the VCCs assigned to the subarray. *Forwarded attribute* *_root_att*: mid_csp_cbf/sub_elt/subarray_N/reportVCCState """ vccHealthState = attribute(name="vccHealthState", label="vccHealthState", forwarded=True) """ The healthState attribute value of the VCCs assigned to the subarray. *Forwarded attribute* *_root_att*: mid_csp_cbf/sub_elt/subarray_N/reportVCChealthState """ cbfOutputLink = attribute(name="cbfOutputLink", label="cbfOutputLink", forwarded=True) """ The CBF Subarray output links information. *Forwarded attribute* *_root_att*: mid_csp_cbf/sub_elt/subarray_N/cbfOutputLinksDistribution """ # # These attributes are not defined in CbfMaster. #fspState = attribute(name="fspState", label="fspState", # forwarded=True #) #fspHealthState = attribute(name="fspHealthState",label="fspHealthState", # forwarded=True #) # --------------- # General methods # --------------- def init_device(self): """ *Class method* Perform device initialization. during initiazlization the CspSubarray device : * connects to CSP Master and sub-element master devices * sub-element sub-array devices with the same subarray ID * subscribes to the sub-element subarrays State,healthState, obsState attributes\ for change event """ SKASubarray.init_device(self) # PROTECTED REGION ID(CspSubarray.init_device) ENABLED START # self.set_state(tango.DevState.INIT) self._health_state = HealthState.UNKNOWN self._admin_mode = AdminMode.OFFLINE # NOTE: need to adjust SKAObsDevice class because some of its # attributes (such as obs_state, obs_mode and command_progress) are not # visibile from the derived classes!! self._obs_mode = ObsMode.IDLE self._obs_state = ObsState.IDLE # get subarray ID if self.SubID: self._subarray_id = int(self.SubID) else: self._subarray_id = int(self.get_name()[-2:]) # last two chars of FQDN # sub-element Subarray State and healthState initialization self._se_subarray_state = defaultdict(lambda: tango.DevState.UNKNOWN) self._se_subarray_healthstate = defaultdict(lambda: HealthState.UNKNOWN) self._se_subarray_obsstate = defaultdict(lambda: ObsState.IDLE) self._se_subarray_adminmode = defaultdict(lambda: AdminMode.OFFLINE) # initialize the list with the capabilities belonging to the sub-array # Do we need to know the max number of capabilities for each type? self._search_beams = [] # list of SearchBeams assigned to subarray self._timing_beams = [] # list of TimingBeams assigned to subarray self._vlbi_beams = [] # list of VlbiBeams assigned to subarray self._vcc = [] # list of VCCs assigned to subarray self._fsp = [] # list of FSPs assigned to subarray` self._cbf_subarray_fqdn = '' self._pss_subarray_fqdn = '' self._se_subarrays_fqdn = [] self._se_subarrays_proxies = {} self._se_subarray_event_id = {} self._receptor_to_vcc_map = {} self._csp_capabilities = '' self._valid_scan_configuration = '' # initialize proxy to CBFMaster device self._cbfMasterProxy = 0 self._cbfAddress = '' self._cbf_capabilities = {} # initialize proxy to PssMaster device self._pssMasterProxy = 0 self._pssAddress = '' # initialize proxy to PstMaster device self._pstMasterProxy = 0 self._pstAddress = '' # set storage and element logging level self._storage_logging_level = int(tango.LogLevel.LOG_INFO) self._element_logging_level = int(tango.LogLevel.LOG_INFO) # build the sub-element sub-array FQDNs self._cbf_subarray_fqdn = '{}{:02d}'.format(self.CbfSubarrayPrefix, self._subarray_id) self._pss_subarray_fqdn = '{}{:02d}'.format(self.PssSubarrayPrefix, self._subarray_id) try: self.__connect_to_master() self.__connect_to_subarrays() except tango.DevFailed as df: log_msg = "Error in {}: {}". format(df.args[0].origin, df.args[0].desc) self.dev_logging(log_msg, tango.LogLevel.LOG_ERROR) # to use the push model in command_inout_asynch (the one with the callback parameter), # change the global TANGO model to PUSH_CALLBACK. apiutil = tango.ApiUtil.instance() apiutil.set_asynch_cb_sub_model(tango.cb_sub_model.PUSH_CALLBACK) # PROTECTED REGION END # // CspSubarray.init_device def always_executed_hook(self): # PROTECTED REGION ID(CspSubarray.always_executed_hook) ENABLED START # pass # PROTECTED REGION END # // CspSubarray.always_executed_hook def delete_device(self): # PROTECTED REGION ID(CspSubarray.delete_device) ENABLED START # #release the allocated event resources for fqdn in self._se_subarrays_fqdn: event_to_remove = [] try: for event_id in self._se_subarray_event_id[fqdn]: try: self._se_subarrays_proxies[fqdn].unsubscribe_event(event_id) # self._se_subarray_event_id[fqdn].remove(event_id) # in Pyton3 can't remove the element from the list while looping on it. # Store the unsubscribed events in a temporary list and remove them later. event_to_remove.append(event_id) except tango.DevFailed as df: msg = ("Unsubscribe event failure.Reason: {}. " "Desc: {}".format(df.args[0].reason, df.args[0].desc)) self.dev_logging(msg, tango.LogLevel.LOG_ERROR) except KeyError as key_err: # NOTE: in PyTango unsubscription of a not-existing event id raises a # KeyError exception not a DevFailed!! msg = "Unsubscribe event failure. Reason: {}".format(str(key_err)) self.dev_logging(msg, tango.LogLevel.LOG_ERROR) # remove the events from the list for k in event_to_remove: self._se_subarray_event_id[fqdn].remove(k) # check if there are still some registered events. What to do in this case?? if self._se_subarray_event_id[fqdn]: msg = "Still subscribed events: {}".format(self._se_subarray_event_id) self.dev_logging(msg, tango.LogLevel.LOG_WARN) else: # delete the dictionary entry self._se_subarray_event_id.pop(fqdn) except KeyError as key_err: msg = " Can't retrieve the information of key {}".format(key_err) self.dev_logging(msg, tango.LogLevel.LOG_ERROR) # clear the subarrays list and dictionary self._se_subarrays_fqdn.clear() self._se_subarrays_proxies.clear() # PROTECTED REGION END # // CspSubarray.delete_device # ------------------ # Attributes methods # ------------------ def read_scanID(self): """ *Attribute method* Returns: The scan configuration ID. """ # PROTECTED REGION ID(CspSubarray.scanID_read) ENABLED START # return self._scan_ID # PROTECTED REGION END # // CspSubarray.scanID_read def write_scanID(self, value): """ Note: Not yet implemented. *Attribute method* Set the scan configuration ID to the defined value. Args: value: the scan configuration ID Type: DevUshort Returns: The scan configuration ID. """ # PROTECTED REGION ID(CspSubarray.scanID_write) ENABLED START # self._scan_ID = value return # PROTECTED REGION END # // CspSubarray.scanID_write def read_corrInherentCap(self): """ *Attribute method* Returns: The CspSubarray Correlation Inherent Capability FQDN. *Type*: DevString """ # PROTECTED REGION ID(CspSubarray.corrInherentCap_read) ENABLED START # return '' # PROTECTED REGION END # // CspSubarray.corrInherentCap_read def read_pssInherentCap(self): """ *Attribute method* Returns: The CspSubarray PSS Inherent Capability FQDN. *Type*: DevString """ # PROTECTED REGION ID(CspSubarray.pssInherentCap_read) ENABLED START # return '' # PROTECTED REGION END # // CspSubarray.pssInherentCap_read def read_pstInherentCap(self): """ *Attribute method* Returns: The CspSubarray PST Inherent Capability FQDN. *Type*: DevString """ # PROTECTED REGION ID(CspSubarray.pstInherentCap_read) ENABLED START # return '' # PROTECTED REGION END # // CspSubarray.pstInherentCap_read def read_vlbiInherentCap(self): """ *Attribute method* Returns: The CspSubarray VLBI Inherent Capability FQDN. *Type*: DevString """ # PROTECTED REGION ID(CspSubarray.vlbiInherentCap_read) ENABLED START # return '' # PROTECTED REGION END # // CspSubarray.vlbiInherentCap_read def read_cbfSubarrayState(self): """ *Attribute method* Returns: The CBF sub-element subarray *State* attribute value. *Type*: DevState """ # PROTECTED REGION ID(CspSubarray.cbfSubarrayState_read) ENABLED START # return self._se_subarray_state[self._cbf_subarray_fqdn] # PROTECTED REGION END # // CspSubarray.cbfSubarrayState_read def read_pssSubarrayState(self): """ *Attribute method* Returns: The PSS sub-element subarray *State* attribute value. *Type*: DevState """ # PROTECTED REGION ID(CspSubarray.pssSubarrayState_read) ENABLED START # return self._se_subarray_state[self._pss_subarray_fqdn] # PROTECTED REGION END # // CspSubarray.pssSubarrayState_read def read_cbfSubarrayHealthState(self): """ *Attribute method* Returns: The CBF sub-element subarray *healtState* attribute value. *Type*: DevUShort """ # PROTECTED REGION ID(CspSubarray.cbfSubarrayHealthState_read) ENABLED START # return self._se_subarray_healthstate[self._cbf_subarray_fqdn] # PROTECTED REGION END # // CspSubarray.cbfSubarrayHealthState_read def read_pssSubarrayHealthState(self): """ *Attribute method* Returns: The PSS sub-element subarray *healtState* attribute value. *Type*: DevUShort """ # PROTECTED REGION ID(CspSubarray.pssSubarrayHealthState_read) ENABLED START # return self._se_subarray_healthstate[self._pss_subarray_fqdn] # PROTECTED REGION END # // CspSubarray.pssSubarrayHealthState_read def read_cbfSubarrayObsState(self): """ *Attribute method* Returns: The CBF sub-element subarray *obsState* attribute value. *Type*: DevUShort """ # PROTECTED REGION ID(CspSubarray.cbfSubarrayObsState_read) ENABLED START # return self._se_subarray_obsstate[self._cbf_subarray_fqdn] # PROTECTED REGION END # // CspSubarray.cbfSubarrayObsState_read def read_pssSubarrayObsState(self): """ *Attribute method* Returns: The PSS sub-element subarray *obsState* attribute value. *Type*: DevUShort """ # PROTECTED REGION ID(CspSubarray.pssSubarrayObsState_read) ENABLED START # return self._se_subarray_obsstate[self._pss_subarray_fqdn] # PROTECTED REGION END # // CspSubarray.pssSubarrayObsState_read def read_pssSubarrayAddr(self): """ *Attribute method* Returns: The PSS sub-element subarray FQDN. *Type*: DevString """ # PROTECTED REGION ID(CspSubarray.pssSubarrayAddr_read) ENABLED START # return self._pss_subarray_fqdn # PROTECTED REGION END # // CspSubarray.pssSubarrayAddr_read def read_cbfSubarrayAddr(self): """ *Attribute method* Returns: The CSP sub-element subarray FQDN. *Type*: DevString """ # PROTECTED REGION ID(CspSubarray.cbfSubarrayAddr_read) ENABLED START # return self._cbf_subarray_fqdn # PROTECTED REGION END # // CspSubarray.cbfSubarrayAddr_read def read_validScanConfiguration(self): """ *Attribute method* Returns: The last programmed scan configuration. *Type*: DevString (JSON-encoded) """ # PROTECTED REGION ID(CspSubarray.validScanConfiguration_read) ENABLED START # return self._valid_scan_configuration # PROTECTED REGION END # // CspSubarray.validScanConfiguration_read def read_fsp(self): """ *Attribute method* Returns: The list of FSP IDs assigned to the subarray. *Type*: array of DevUShort. """ # PROTECTED REGION ID(CspSubarray.fsp_read) ENABLED START # return self._fsp # PROTECTED REGION END # // CspSubarray.fsp_read def read_vcc(self): """ *Attribute method* Returns: The list of VCC IDs assigned to the subarray. *Type*: array of DevUShort. """ # PROTECTED REGION ID(CspSubarray.vcc_read) ENABLED START # self._vcc = [] try: assigned_receptors = self._se_subarrays_proxies[self._cbf_subarray_fqdn].receptors # NOTE: if receptors attribute is empty, assigned_receptors is an empty numpy array # and it will just be skipped by the for loop for receptor_id in assigned_receptors: vcc_id = self._receptor_to_vcc_map[receptor_id] self._vcc.append(vcc_id) except KeyError as key_err: msg = "No {} found".format(key_err) tango.Except.throw_exception("Read attribute failure", msg, "read_vcc", tango.ErrSeverity.ERR) except tango.DevFailed as df: tango.Except.throw_exception("Read attribute failure", df.args[0].desc, "read_vcc", tango.ErrSeverity.ERR) return self._vcc # PROTECTED REGION END # // CspSubarray.vcc_read def read_searchBeams(self): """ *Attribute method* Returns: The list of Search Beam Capability IDs assigned to the subarray. *Type*: array of DevUShort. """ # PROTECTED REGION ID(CspSubarray.vcc_read) ENABLED START # return self._search_beams # PROTECTED REGION END # // CspSubarray.vcc_read def read_timingBeams(self): """ *Attribute method* Returns: The list of Timing Beam Capability IDs assigned to the subarray. *Type*: array of DevUShort. """ # PROTECTED REGION ID(CspSubarray.vcc_read) ENABLED START # return self._timing_beams # PROTECTED REGION END # // CspSubarray.vcc_read def read_vlbiBeams(self): """ *Attribute method* Returns: The list of Vlbi Beam Capability IDs assigned to the subarray. *Type*: array of DevUShort. """ # PROTECTED REGION ID(CspSubarray.vcc_read) ENABLED START # return self._vlbi_beams # PROTECTED REGION END # // CspSubarray.vcc_read def read_searchBeamsState(self): """ *Attribute method* Returns: The Search Beam Capabilities *State* attribute value. *Type*: array of DevState """ # PROTECTED REGION ID(CspSubarray.searchBeamsState_read) ENABLED START # return [tango.DevState.UNKNOWN] # PROTECTED REGION END # // CspSubarray.searchBeamsState_read def read_timingBeamsState(self): """ *Attribute method* Returns: The Timing Beam Capabilities *State* attribute value. *Type*: array of DevState """ # PROTECTED REGION ID(CspSubarray.timingBeamsState_read) ENABLED START # return [tango.DevState.UNKNOWN] # PROTECTED REGION END # // CspSubarray.timingBeamsState_read def read_vlbiBeamsState(self): """ *Attribute method* Returns: The Vlbi Beam Capabilities *State* attribute value. *Type*: array of DevState """ # PROTECTED REGION ID(CspSubarray.vlbiBeamsState_read) ENABLED START # return [tango.DevState.UNKNOWN] # PROTECTED REGION END # // CspSubarray.vlbiBeamsState_read def read_searchBeamsHealthState(self): """ *Attribute method* Returns: The Search Beam Capabilities *healthState* attribute value. *Type*: array of DevUShort """ # PROTECTED REGION ID(CspSubarray.searchBeamsHealthState_read) ENABLED START # return [0] # PROTECTED REGION END # // CspSubarray.searchBeamsHealthState_read def read_timingBeamsHealthState(self): """ *Attribute method* Returns: The Timing Beam Capabilities *healthState* attribute value. *Type*: array of DevUShort """ # PROTECTED REGION ID(CspSubarray.timingBeamsHealthState_read) ENABLED START # return [0] # PROTECTED REGION END # // CspSubarray.timingBeamsHealthState_read def read_vlbiBeamsHealthState(self): """ *Attribute method* Returns: The Vlbi Beam Capabilities *healthState* attribute value. *Type*: array of DevUShort """ # PROTECTED REGION ID(CspSubarray.vlbiBeamsHealthState_read) ENABLED START # return [0] # PROTECTED REGION END # // CspSubarray.vlbiBeamsHealthState_read def read_timingBeamsObsState(self): """ *Attribute method* Returns: The Timing Beam Capabilities *obsState* attribute value. *Type*: array of DevUShort """ # PROTECTED REGION ID(CspSubarray.timingBeamsObsState_read) ENABLED START # return [0] # PROTECTED REGION END # // CspSubarray.timingBeamsObsState_read # -------- # Commands # -------- def is_EndScan_allowed(self): """ *TANGO is_allowed method*: filter the external request depending on the \ current device state.\n Check if the Scan method can be issued on the subarray.\n The Scan() method can be issue on a subarray if its *State* is *ON*. Returns: True if the command can be executed, otherwise False """ #TODO: checks other states? if self.get_state() in [tango.DevState.ON]: return True return False @command( ) @DebugIt() def EndScan(self): """ *Class method* End the execution of a running scan. After successful execution, the CspSubarray \ *ObsState* is IDLE. Raises: tango.DevFailed: if the subarray *obsState* is not SCANNING or if an exception is caught during the command execution. Note: Still to implement the check on AdminMode values: the command can be processed \ only when the CspSubarray is *ONLINE* or *MAINTENANCE* """ # PROTECTED REGION ID(CspSubarray.EndScan) ENABLED START # # Check if the EndScan command can be executed. This command is allowed when the # Subarray State is SCANNING. if self._obs_state != ObsState.SCANNING: log_msg = ("Subarray obs_state is {}" ", not SCANNING".format(ObsState(self._obs_state).name)) tango.Except.throw_exception("Command failed", log_msg, "EndScan", tango.ErrSeverity.ERR) proxy = 0 #TODO:the command is forwarded only to CBF. Future implementation has to # check the observing mode and depending on this, the command is forwarded to # the interested sub-elements. if self.__is_subarray_available(self._cbf_subarray_fqdn): try: proxy = self._se_subarrays_proxies[self._cbf_subarray_fqdn] # forward asynchrnously the command to the CbfSubarray proxy.command_inout_asynch("EndScan", self.__cmd_ended) except tango.DevFailed as df: log_msg = '' for item in df.args: log_msg += item.reason + " " + item.desc self.dev_logging(log_msg, tango.LogLevel.LOG_ERROR) tango.Except.re_throw_exception(df, "Command failed", "CspSubarray EndScan command failed", "Command()", tango.ErrSeverity.ERR) except KeyError as key_err: msg = " Can't retrieve the information of key {}".format(key_err) self.dev_logging(msg, tango.LogLevel.LOG_ERROR) tango.Except.throw_exception("Command failed", msg, "EndScan", tango.ErrSeverity.ERR) else: log_msg = "Subarray {} not registered".format(str(self._cbf_subarray_fqdn)) self.dev_logging(log_msg, tango.LogLevel.LOG_ERROR) tango.Except.throw_exception("Command failed", log_msg, "EndScan", tango.ErrSeverity.ERR) # PROTECTED REGION END # // CspSubarray.EndScan def is_Scan_allowed(self): """ *TANGO is_allowed method*: filter the external request depending on the current \ device state.\n Check if the Scan method can be issued on the subarray.\n A scan configuration can be performed when the subarray *State* is ON (that is, \ at least one receptor is assigned to it) Returns: True if the command can be executed, otherwise False """ #TODO: checks other states? if self.get_state() == tango.DevState.ON: return True return False @command( dtype_in='str', doc_in="Activation time of the scan, as seconds since the Linux epoch" ) @DebugIt() def Scan(self, argin): """ *Class method* Start the execution of scan. Raises: tango.DevFailed: if the subarray *obsState* is not READY or if an exception is caught\ during the command execution. Note: Still to implement the check on AdminMode values: the command can be processed \ only when the CspSubarray is *ONLINE* or *MAINTENANCE* """ # PROTECTED REGION ID(CspSubarray.Scan) ENABLED START # # TODO: add check for adminMode. The subarray is able to perform configuration only # if its adminMode is ONLINE/MAINTENANCE. # # Check if the Scan command can be executed. This command is allowed when the # Subarray State is READY. if self._obs_state != ObsState.READY.value: log_msg = "Subarray is in {} state, not READY".format(ObsState(self._obs_state).name) tango.Except.throw_exception("Command failed", log_msg, "Scan", tango.ErrSeverity.ERR) proxy = 0 if self.__is_subarray_available(self._cbf_subarray_fqdn): try: proxy = self._se_subarrays_proxies[self._cbf_subarray_fqdn] # forward the command to the CbfSubarray asynchrnously proxy.command_inout_asynch("Scan", argin, self.__cmd_ended) # self._obs_state = ObsState.SCANNING.value except tango.DevFailed as df: log_msg = '' for item in df.args: log_msg += item.reason + " " + item.desc self.dev_logging(log_msg, tango.LogLevel.LOG_ERROR) tango.Except.re_throw_exception(df, "Command failed", "CspSubarray Scan command failed", "Command()", tango.ErrSeverity.ERR) except KeyError as key_err: msg = " Can't retrieve the information of key {}".format(key_err) self.dev_logging(msg, tango.LogLevel.LOG_ERROR) tango.Except.throw_exception("Command failed", msg, "Scan", tango.ErrSeverity.ERR) else: log_msg = "Subarray {} not registered".format(str(self._cbf_subarray_fqdn)) self.dev_logging(log_msg, tango.LogLevel.LOG_ERROR) tango.Except.throw_exception("Command failed", log_msg, "Scan", tango.ErrSeverity.ERR) # PROTECTED REGION END # // CspSubarray.Scan def is_AddReceptors_allowed(self): """ *TANGO is_allowed method*: filter the external request depending on the current \ device state.\n Check if the AddReceptors method can be issued on the subarray.\n Receptors can be added to a Subarray when its *State* is *OFF* or *ON*. Returns: True if the command can be executed, otherwise False """ return self.__is_add_resources_allowed() @command( dtype_in=('uint16',), doc_in="List of the receptor IDs to add to the subarray.", ) @DebugIt() def AddReceptors(self, argin): """ *Class method* Add the specified receptor IDs to the subarray. The command can be executed only if the CspSubarray *ObsState* is *IDLE*. Args: argin: the list of receptor IDs Type: array of DevUShort Returns: None Raises: tango.DevFailed: if the CbfSubarray is not available or if an exception\ is caught during command execution. Note: Still to implement the check on AdminMode values: the command can be processed \ only when the CspSubarray is *ONLINE* or *MAINTENANCE* """ # PROTECTED REGION ID(CspSubarray.AddReceptors) ENABLED START # # Each vcc_id map to a vcc_fqdn inside CbfMaster, for example: # vcc_id = 1 -> mid_csp_cbf/vcc/vcc_001 # vcc_id = 2 -> mid_csp_cbf/vcc/vcc_002 # ..... # vcc_id = 17 -> mid_csp_cbf/vcc/vcc_017 # vcc_id and receptor_id is not the same. The map between vcc_id and receptor_id # is built by CbfMaster and exported as attribute. # The max number of VCC allocated is defined by the VCC property of the CBF Master. # TODO: add check for adminMode. The subarray is able to perform configuration only # if its adminMode is ONLINE/MAINTENANCE, # # Check if the AddReceptors command can be executed. Receptors can be assigned to a subarray # only when its obsState is IDLE. if self._obs_state != ObsState.IDLE: log_msg = ("AddReceptors not allowed when subarray" " ObsState is {}".format(ObsState(self._obs_state).name)) tango.Except.throw_exception("Command failed", log_msg, "AddReceptors", tango.ErrSeverity.ERR) # the list of available receptor IDs. This number is mantained by the CspMaster # and reported on request. available_receptors = [] # the list of receptor to assign to the subarray receptor_to_assign = [] try: # access to CspMaster to get information about the list of available receptors # and the receptors affiliation to subarrays. cspMasterProxy = tango.DeviceProxy(self.CspMaster) cspMasterProxy.ping() available_receptors = cspMasterProxy.availableReceptorIDs #!!!!!!!!!!!!!!!!! # NOTE: need to check if available_receptors is None: this happens when all # the provided receptors are assigned. # NOTE: if the Tango attribute is read-only (as in the case of availableReceptorIDs) # the read method returns a None type. If the Tango attribute is RW the read methods # returns an empty tuple (whose length is 0) # # 2019-09-20 NOTE: the previous statement is true for the images of Tango and Pytango # 9.2.5, with PyTango not compiled with numpy support!!! # After moving to TANGO and PyTango 9.3.0 (compiled with numpy support) # if there is no available receptor the call to cspMasterProxy.availableReceptorIDs # returns an array= [0] (an empty list generates the error "DeviceAttribute object has # no attribute 'value'"). The length of the array is 1 and its value is 0. # Checks on available_receptors need to be changed (see below). # # 2019-10-18: with the new TANGO/PyTango images release (PyTango 9.3.1, # TANGO 9.3.3, numpy 1.17.2) # the issue of "DeviceAttribute object has no attribute 'value'" has been resolved. Now # a TANGO RO attribute initialized to an empty list (see self._available_receptorIDs), # returns a NoneType object (as before with PyTango/TANGO 9.2.5 images). # The behavior now is coherent, but I don't revert to the old code: this methods keep # returning an array with one element = 0 when receptors are not available. #!!!!!!!!!!!!!!!!! #if not available_receptors: # old code!! # NO available receptors! if available_receptors[0] == 0: log_msg = "No available receptor to add to subarray {}".format(self._subarray_id) self.dev_logging(log_msg, tango.LogLevel.LOG_WARN) return receptor_membership = cspMasterProxy.receptorMembership except tango.DevFailed as df: msg = "Failure in getting receptors information:" + str(df.args[0].reason) tango.Except.throw_exception("Command failed", msg, "AddReceptors", tango.ErrSeverity.ERR) except AttributeError as attr_err: msg = "Failure in reading {}: {}".format(str(attr_err.args[0]), attr_err.__doc__) tango.Except.throw_exception("Command failed", msg, "AddReceptors", tango.ErrSeverity.ERR) for receptorId in argin: # check if the specified receptor id is a valid number (that is, belongs to the list # of provided receptors) if receptorId in self._receptor_id_list: # check if the receptor id is one of the available receptor Ids if receptorId in available_receptors: receptor_to_assign.append(receptorId) else: # retrieve the subarray owner sub_id = receptor_membership[receptorId - 1] log_msg = "Receptor {} already assigned to subarray {}".format(str(receptorId), str(sub_id)) self.dev_logging(log_msg, tango.LogLevel.LOG_WARN) else: log_msg = "Invalid receptor id: {}".format(str(receptorId)) self.dev_logging(log_msg, tango.LogLevel.LOG_WARN) # check if the list of receptors to assign is empty if not receptor_to_assign: log_msg = "The required receptors are already assigned to a subarray" self.dev_logging(log_msg, tango.LogLevel.LOG_INFO) return # check if the CspSubarray is already connected to the CbfSubarray proxy = 0 if self.__is_subarray_available(self._cbf_subarray_fqdn): try: proxy = self._se_subarrays_proxies[self._cbf_subarray_fqdn] # remove possible receptor repetition tmp = set(receptor_to_assign) receptor_to_assign = list(tmp) # forward the command to the CbfSubarray proxy.command_inout("AddReceptors", receptor_to_assign) except KeyError as key_err: msg = " Can't retrieve the information of key {}".format(key_err) self.dev_logging(msg, tango.LogLevel.LOG_ERROR) tango.Except.throw_exception("Command failed", msg, "AddReceptors", tango.ErrSeverity.ERR) except tango.DevFailed as df: log_msg = "AddReceptor command failure." for item in df.args: log_msg += "Reason: {}. Desc: {}".format(item.reason, item.desc) self.dev_logging(log_msg, tango.LogLevel.LOG_ERROR) tango.Except.re_throw_exception(df, "Command failed", "CspSubarray AddReceptors command failed", "Command()", tango.ErrSeverity.ERR) except TypeError as err: # Raised when an operation or function is applied to an object of # inappropriate type. The associated value is a string giving details about # the type mismatch. log_msg = "TypeError: {}".format(str(err)) self.dev_logging(log_msg, tango.LogLevel.LOG_ERROR) tango.Except.throw_exception("Command failed", log_msg, "AddReceptors", tango.ErrSeverity.ERR) else: log_msg = "Subarray {} not registered!".format(str(self._cbf_subarray_fqdn)) self.dev_logging(log_msg, tango.LogLevel.LOG_ERROR) tango.Except.throw_exception("Command failed", log_msg, "AddReceptors", tango.ErrSeverity.ERR) # PROTECTED REGION END # // CspSubarray.AddReceptors def is_RemoveReceptors_allowed(self): """ *TANGO is_allowed method*: filter the external request depending on the \ current device state.\n Check if the method can be issued on the subarray.\n Re can be removed from a subarray when its *State* is ON or OFF- Returns: True if the command can be executed, otherwise False """ return self.__is_remove_resources_allowed() @command( dtype_in=('uint16',), doc_in="The list with the receptor IDs to remove", ) @DebugIt() def RemoveReceptors(self, argin): """ Remove the receptor IDs from the subarray. Args: argin: The list of the receptor IDs to remove from the subarray. Type: array of DevUShort Returns: None Raises: tango.DevFailed: raised if the subarray *obState* attribute is not IDLE, or \ when an exception is caught during command execution. """ # PROTECTED REGION ID(CspSubarray.RemoveReceptors) ENABLED START # # Check if the RemoveReceptors command can be executed. Receptors can be removed # from a subarray only when its obsState is IDLE or READY. if self._obs_state != ObsState.IDLE.value: #get the obs_state label log_msg = ("Command RemoveReceptors not allowed when subarray " "ObsState is {}".format(ObsState(self._obs_state).name)) tango.Except.throw_exception("Command failed", log_msg, "RemoveReceptors", tango.ErrSeverity.ERR) # check if the CspSubarray is already connected to the CbfSubarray proxy = 0 if self.__is_subarray_available(self._cbf_subarray_fqdn): try: proxy = self._se_subarrays_proxies[self._cbf_subarray_fqdn] # read from CbfSubarray the list of assigned receptors receptors = proxy.receptors #!!!!!!!!!!!!!!!!! # 2019-09-20: New images for TANGO and PyTango images has been released. PyTango # is now compiled with th numpy support. In this case the proxy.receptors call # does no more return an empty tuple but an empty numpy array. # Checks on receptors content need to be changed (see below) # NB: the receptors attribute implemented by the CbfSubarray is declared as RW. # In this case the read method returns an empty numpy array ([]) whose length is 0. #!!!!!!!!!!!!!!!!! # check if the list of assigned receptors is empty. #if not receptors: if len(receptors) == 0: self.dev_logging("RemoveReceptors: no receptor to remove", tango.LogLevel.LOG_INFO) return receptors_to_remove = [] # check if the receptors to remove belong to the subarray for receptor_id in argin: if receptor_id in receptors: receptors_to_remove.append(receptor_id) # forward the command to CbfSubarray proxy.RemoveReceptors(receptors_to_remove) receptors = proxy.receptors except tango.DevFailed as df: log_msg = "RemoveReceptors:" + df.args[0].desc self.dev_logging(log_msg, tango.LogLevel.LOG_ERROR) tango.Except.re_throw_exception(df, "Command failed", "CspSubarray RemoveReceptors command failed", "Command()", tango.ErrSeverity.ERR) else: log_msg = "Subarray {} not registered!".format(str(self._cbf_subarray_fqdn)) self.dev_logging(log_msg, tango.LogLevel.LOG_ERROR) tango.Except.throw_exception("Command failed", log_msg, "RemoveReceptors", tango.ErrSeverity.ERR) # PROTECTED REGION END # // CspSubarray.RemoveReceptors def is_RemoveAllReceptors_allowed(self): """ *TANGO is_allowed method*: filter the external request depending on the \ current device state.\n Check if the method can be issued on the subarray.\n Resources can be removed from a subarray when its *State* is ON or OFF- Returns: True if the command can be executed, otherwise False """ return self.__is_remove_resources_allowed() @command( ) @DebugIt() def RemoveAllReceptors(self): """ *Class method.* Remove all the assigned receptors from the subarray. Returns: None Raises: tango.DevFailed: raised if the subarray *obState* attribute is not IDLE or READY, or \ when an exception is caught during command execution. """ # PROTECTED REGION ID(CspSubarray.RemoveAllReceptors) ENABLED START # # Check if the RemoveAllReceptors command can be executed. Receptors can be removed # from a subarray only when its obsState is IDLE or READY. if self._obs_state != ObsState.IDLE.value: log_msg = ("Command RemoveAllReceptors not allowed when subarray" " ObsState is {}".format(ObsState(self._obs_state).name)) tango.Except.throw_exception("Command failed", log_msg, "RemoveAllReceptors", tango.ErrSeverity.ERR) proxy = 0 if self.__is_subarray_available(self._cbf_subarray_fqdn): try: proxy = self._se_subarrays_proxies[self._cbf_subarray_fqdn] # check if the list of assigned receptors is empty receptors = proxy.receptors #!!!!!!!!!!!!!!!!! # 09/20/2019 ATT: New images for TANGO and PyTango images has been released. # PyTango is now compiled with th numpy support. In this case the proxy.receptors # call does no more return an empty tuple but an empty numpy array. # Checks on receptors content need to be changed (see below) # NB: the receptors attribute implemented by the CbfSubarray is declared as RW. # In this case the read method returns an empty numpy array ([]) whose length is 0 #!!!!!!!!!!!!!!!!! #if not receptors: if len(receptors) == 0: self.dev_logging("RemoveAllReceptors: no receptor to remove", tango.LogLevel.LOG_INFO) return # forward the command to the CbfSubarray proxy.command_inout("RemoveAllReceptors") #self._vcc = [] except tango.DevFailed as df: log_msg = ("RemoveAllReceptors failure. Reason: {} " "Desc: {}".format(df.args[0].reason, df.args[0].desc)) self.dev_logging(log_msg, tango.LogLevel.LOG_ERROR) tango.Except.re_throw_exception(df, "Command failed", "CspSubarray RemoveAllReceptors command failed", "Command()", tango.ErrSeverity.ERR) except KeyError as key_err: log_msg = "No key {} found".format(str(key_err)) tango.Except.throw_exception("Command failed", log_msg, "RemoveAllReceptors", tango.ErrSeverity.ERR) else: log_msg = "Subarray {} not registered!".format(str(self._cbf_subarray_fqdn)) self.dev_logging(log_msg, tango.LogLevel.LOG_ERROR) tango.Except.throw_exception("Command failed", log_msg, "RemoveAllReceptors", tango.ErrSeverity.ERR) # PROTECTED REGION END # // CspSubarray.RemoveAllReceptors def is_ConfigureScan_allowed(self): """ *TANGO is_allowed method*: filter the external request depending on the current\ device state.\n Check if the ConfigureScan method can be issued on the subarray.\n A scan configuration can be performed when the subarray *State* is ON (that is, \ at least one receptor is assigned to it) Returns: True if the command can be executed, otherwise False """ # TODO:checks other states? if self.get_state() == tango.DevState.ON: return True return False @command( dtype_in='str', doc_in="A Json-encoded string with the scan configuration.", ) @DebugIt() def ConfigureScan(self, argin): """ Note: Part of this code (the input string parsing) comes from the CBF project\ developed by J.Jjang (NRC-Canada) *Class method.* Configure a scan for the subarray.\n The command can be execuced when the CspSubarray State is *ON* and the \ ObsState is *IDLE* or *READY*.\n If the configuration for the scan is not correct (invalid parameters or invalid JSON)\ the configuration is not applied and the ObsState of the CspSubarray remains IDLE. Args: argin: a JSON-encoded string with the parameters to configure a scan. Returns: None Raises: tango.DevFailed exception if the CspSubarray ObsState is not valid or if an exception\ is caught during command execution. Note: Still to implement the check on AdminMode values: the command can be processed \ only when the CspSubarray is *ONLINE* or *MAINTENANCE* """ # PROTECTED REGION ID(CspSubarray.ConfigureScan) ENABLED START # # TODO: add check for adminMode. The subarray is able to perform configuration only # if its adminMode is ONLINE/MAINTENANCE, # # check obs_state: the subarray can be configured only when the obs_state is # IDLE or READY (re-configuration) if self._obs_state not in [ObsState.IDLE, ObsState.READY]: log_msg = ("Subarray is in {} state, not IDLE or" " READY".format(ObsState(self._obs_state).name)) tango.Except.throw_exception("Command failed", log_msg, "ConfgureScan", tango.ErrSeverity.ERR) # check connection with CbfSubarray if not self.__is_subarray_available(self._cbf_subarray_fqdn): log_msg = "Subarray {} not registered!".format(str(self._cbf_subarray_fqdn)) self.dev_logging(log_msg, tango.LogLevel.LOG_ERROR) tango.Except.throw_exception("Command failed", log_msg, "ConfigureScan execution", tango.ErrSeverity.ERR) # the dictionary with the scan configuration argin_dict = {} try: # for test purpose we load the json configuration from an # external file. # TO REMOVE!! if "load" in argin: # skip the 'load' chars and remove spaces from the filename fn = (argin[4:]).strip() filename = os.path.join(commons_pkg_path, fn) with open(filename) as json_file: # load the file into a dictionary argin_dict = json.load(json_file) # dump the dictionary into the input string to forward # to CbfSubarray argin = json.dumps(argin_dict) else: argin_dict = json.loads(argin) except FileNotFoundError as file_err: self.dev_logging(str(file_err), tango.LogLevel.LOG_ERROR) tango.Except.throw_exception("Command failed", str(file_err), "ConfigureScan execution", tango.ErrSeverity.ERR) except json.JSONDecodeError as e: # argument not a valid JSON object # this is a fatal error msg = ("Scan configuration object is not a valid JSON object." "Aborting configuration:{}".format(str(e))) self.dev_logging(msg, tango.LogLevel.LOG_ERROR) tango.Except.throw_exception("Command failed", msg, "ConfigureScan execution", tango.ErrSeverity.ERR) # Validate scanID. # If not given, abort the scan configuration. # If malformed, abort the scan configuration. if "scanID" in argin_dict: if int(argin_dict["scanID"]) <= 0: # scanID not positive msg = ("'scanID' must be positive (received {}). " "Aborting configuration.".format(int(argin_dict["scanID"]))) # this is a fatal error self.dev_logging(msg, tango.LogLevel.LOG_ERROR) tango.Except.throw_exception("Command failed", msg, "ConfigureScan execution", tango.ErrSeverity.ERR) #TODO:add on CspMaster the an attribute with the list of scanID # of each sub-array #elif any(map(lambda i: i == int(argin_dict["scanID"]), # self._proxy_csp_master.subarrayScanID)): # scanID already taken # msg = "'scanID' must be unique (received {}). "\ # "Aborting configuration.".format(int(argin_dict["scanID"])) # this is a fatal error # self.dev_logging(msg, tango.LogLevel.LOG_ERROR) # tango.Except.throw_exception("Command failed", msg, "ConfigureScan execution", # tango.ErrSeverity.ERR) else: # scanID is valid self._scan_ID = int(argin_dict["scanID"]) else: # scanID not given msg = "'scanID' must be given. Aborting configuration." # this is a fatal error self.dev_logging(msg, tango.LogLevel.LOG_ERROR) tango.Except.throw_exception("Command failed", msg, "ConfigureScan execution", tango.ErrSeverity.ERR) # Validate frequencyBand. # If not given, abort the scan configuration. # If malformed, abort the scan configuration. frequency_band = 0 if "frequencyBand" in argin_dict: frequency_bands = ["1", "2", "3", "4", "5a", "5b"] if argin_dict["frequencyBand"] in frequency_bands: frequency_band = frequency_bands.index(argin_dict["frequencyBand"]) else: msg = ("'frequencyBand' must be one of {} (received {}). " "Aborting configuration.".format(frequency_bands, argin_dict["frequencyBand"])) # this is a fatal error self.dev_logging(msg, tango.LogLevel.LOG_ERROR) tango.Except.throw_exception("Command failed", msg, "ConfigureScan execution", tango.ErrSeverity.ERR) else: # frequencyBand not given msg = "'frequencyBand' must be given. Aborting configuration." # this is a fatal error self.dev_logging(msg, tango.LogLevel.LOG_ERROR) tango.Except.throw_exception("Command failed", msg, "ConfigureScan execution", tango.ErrSeverity.ERR) # ======================================================================= # # At this point, self._scan_ID, self._receptors, and self._frequency_band # # are guaranteed to be properly configured. # # ======================================================================= # # Validate band5Tuning, if frequencyBand is 5a or 5b. # If not given, abort the scan configuration. # If malformed, abort the scan configuration. if frequency_band in [4, 5]: # frequency band is 5a or 5b if "band5Tuning" in argin_dict: # check if streamTuning is an array of length 2 try: assert len(argin_dict["band5Tuning"]) == 2 except (TypeError, AssertionError): msg = ("'band5Tuning' must be an array of length 2." "Aborting configuration.") # this is a fatal error self.dev_logging(msg, tango.LogLevel.LOG_ERROR) tango.Except.throw_exception("Command failed", msg, "ConfigureScan execution", tango.ErrSeverity.ERR) stream_tuning = [*map(float, argin_dict["band5Tuning"])] if frequency_band == 4: if not all([5.85 <= stream_tuning[i] <= 7.25 for i in [0, 1]]): msg = ("Elements in 'band5Tuning must be floats between" " 5.85 and 7.25 (received {} and {}) for a " "'frequencyBand' of 5a." "Aborting configuration.".format(stream_tuning[0], stream_tuning[1])) # this is a fatal error self.dev_logging(msg, tango.LogLevel.LOG_ERROR) tango.Except.throw_exception("Command failed", msg, "ConfigureScan execution", tango.ErrSeverity.ERR) else: # self._frequency_band == 5 if not all([9.55 <= stream_tuning[i] <= 14.05 for i in [0, 1]]): msg = ("Elements in 'band5Tuning must be floats between " "9.55 and 14.05 (received {} and {}) for a " "'frequencyBand' of 5b. " "Aborting configuration.".format(stream_tuning[0], stream_tuning[1])) # this is a fatal error self.dev_logging(msg, tango.LogLevel.LOG_ERROR) tango.Except.throw_exception("Command failed", msg, "ConfigureScan execution", tango.ErrSeverity.ERR) else: msg = ("'band5Tuning' must be given for a" " 'frequencyBand' of {}. " "Aborting configuration".format(["5a", "5b"][frequency_band - 4])) # this is a fatal error self.dev_logging(msg, tango.LogLevel.LOG_ERROR) tango.Except.throw_exception("Command failed", msg, "ConfigureScan execution", tango.ErrSeverity.ERR) # Forward the ConfigureScan command to CbfSubarray. try: proxy = self._se_subarrays_proxies[self._cbf_subarray_fqdn] proxy.ping() # self._obs_state = ObsState.CONFIGURING.value # use asynchrnous model # in this case the obsMode and the valid scan configuraiton are set # at command end proxy.command_inout_asynch("ConfigureScan", argin, self.__cmd_ended) #self._valid_scan_configuration = argin except tango.DevFailed as df: log_msg = '' for item in df.args: log_msg += item.reason + " " + item.desc self.dev_logging(log_msg, tango.LogLevel.LOG_ERROR) tango.Except.re_throw_exception(df, "Command failed", "CspSubarray ConfigureScan command failed", "Command()", tango.ErrSeverity.ERR) # PROTECTED REGION END # // CspSubarray.ConfigureScan @command( dtype_in='uint16', doc_in="The number of SearchBeams Capabilities to assign to the subarray", ) @DebugIt() def AddNumOfSearchBeams(self, argin): """ Note: Still to be implemented *Class method* Add the specified number of Search Beams capabilities to the subarray. Args: argin: The number of SearchBeams Capabilities to assign to the subarray Returns: None """ # PROTECTED REGION ID(CspSubarray.AddSearchBeams) ENABLED START # return # PROTECTED REGION END # // CspSubarray.AddSearchBeams @command( dtype_in='uint16', doc_in="The number of SearchBeam Capabilities to remove from the sub-arrays.\n\ All the search beams are removed from the sub-array if the input number \n\ is equal to the max number of search bem capabilities (1500 for MID)", ) @DebugIt() def RemoveNumOfSearchBeams(self, argin): """ Note: Still to be implemented *Class method* Remove the specified number of Search Beams capabilities from the subarray. Args: argin: The number of SearchBeams Capabilities to remove from \ the subarray. If equal to the max number of search bem capabilities \ (1500 for MID), all the search beams are removed. Returns: None """ # PROTECTED REGION ID(CspSubarray.RemoveSearchBeams) ENABLED START # return # PROTECTED REGION END # // CspSubarray.RemoveSearchBeams @command( dtype_in=('uint16',), doc_in="The list of timing beams IDs to assign to the subarray", ) @DebugIt() def AddTimingBeams(self, argin): """ Note: Still to be implemented *Class method* Add the specified Timing Beams Capability IDs to the subarray. Args: argin: The list of Timing Beams Capability IDs to assign to the subarray. Type: array of DevUShort Returns: None """ # PROTECTED REGION ID(CspSubarray.AddTimingBeams) ENABLED START # return # PROTECTED REGION END # // CspSubarray.AddTimingBeams @command( dtype_in=('uint16',), doc_in="The list of Vlbi beams ID to assign to the subarray.", ) @DebugIt() def AddVlbiBeams(self, argin): """ Note: Still to be implemented *Class method* Add the specified Vlbi Beams Capability IDs to the subarray. Args: argin: The list of Vlbi Beams Capability IDs to assign to the subarray. Type: array of DevUShort Returns: None """ # PROTECTED REGION ID(CspSubarray.AddVlbiBeams) ENABLED START # return # PROTECTED REGION END # // CspSubarray.AddVlbiBeams @command( dtype_in=('uint16',), doc_in="The list of Search Beam Capabilities ID to assign \ to the sub-array.", ) @DebugIt() def AddSearchBeamsID(self, argin): """ Note: Still to be implemented *Class method* Add the specified Search Beams Capability IDs to the subarray. This method requires some knowledge of the internal behavior of the PSS machine,\ because Seach Beam capabilities with PSS pipelines belonging to the same PSS \ node, can't be assigned to different subarrays. Args: argin: The list of Search Beams Capability IDs to assign to the subarray. Type: array of DevUShort Returns: None References: AddNumOfSearchBeams """ # PROTECTED REGION ID(CspSubarray.AddSearchBeamsID) ENABLED START # return # PROTECTED REGION END # // CspSubarray.AddSearchBeamsID @command( dtype_in=('uint16',), doc_in="The list of Search Beams IDs to remove from the sub-array.", ) @DebugIt() def RemoveSearchBeamsID(self, argin): """ Note: Still to be implemented *Class method* Remove the specified Search Beam Capability IDs from the subarray. Args: argin: The list of Timing Beams Capability IDs to remove from the subarray. Type: Array of unsigned short Returns: None """ # PROTECTED REGION ID(CspSubarray.RemoveSearchBeamsID) ENABLED START # return # PROTECTED REGION END # // CspSubarray.RemoveSearchBeamsID @command( dtype_in=('uint16',), doc_in="The list of Timing Beams IDs to remove from the sub-array.", ) @DebugIt() def RemoveTimingBeams(self): """ Note: Still to be implemented *Class method* Remove the specified Timing Beam Capability IDs from the subarray. Args: argin: The list of Timing Beams Capability IDs to remove from the subarray. Type: Array of DevUShort Returns: None """ # PROTECTED REGION ID(CspSubarray.RemoveTimingBeams) ENABLED START # return # PROTECTED REGION END # // CspSubarray.RemoveTimingBeams @command( dtype_in=('uint16',), doc_in="The list of Timing Beams IDs to remove from the sub-array.", ) @DebugIt() def RemoveVlbiBeams(self): """ Note: Still to be implemented *Class method* Remove the specified Vlbi Beam Capability IDs from the subarray. Args: argin: The list of Timing Beams Capability IDs to remove from the subarray. Type: Array of DevUShort Returns: None """ # PROTECTED REGION ID(CspSubarray.RemoveVlbiBeams) ENABLED START # return # PROTECTED REGION END # // CspSubarray.RemoveVlbiBeams def is_EndSB_allowed(self): """ *TANGO is_allowed method*: filter the external request depending on the \ current device state.\n Check if the EndSB method can be issued on the subarray.\ The EndSB method can be issued on a subarrays when its *State* is *ON*. Returns: True if the command can be executed, otherwise False """ if self.dev_state() == tango.DevState.ON: return True return False @command( ) @DebugIt() def EndSB(self): """ *Class method* Set the subarray *ObsState* to *IDLE*.\n The command is executed only when the CspSubarray *State* is *ON* and *ObsState* \ is *READY* or *IDLE*. Raises: tango.DevFailed exception if the CspSubarray ObsState is not valid or if an exception\ is caught during command execution. Note: Still to implement the check on AdminMode values: the command can be processed \ only when the CspSubarray is *ONLINE* or *MAINTENANCE* """ # PROTECTED REGION ID(CspSubarray.EndSB) ENABLED START # # TODO: add check for adminMode. The subarray is able to perform configuration only # if its adminMode is ONLINE/MAINTENANCE, if self._obs_state not in [ObsState.IDLE, ObsState.READY]: log_msg = ("Subarray is in {} state, not IDLE or" " READY".format(ObsState(self._obs_state).name)) tango.Except.throw_exception("Command failed", log_msg, "Scan", tango.ErrSeverity.ERR) # check connection with CbfSubarray if not self.__is_subarray_available(self._cbf_subarray_fqdn): log_msg = "Subarray {} not registered!".format(str(self._cbf_subarray_fqdn)) self.dev_logging(log_msg, tango.LogLevel.LOG_ERROR) tango.Except.throw_exception("Command failed", log_msg, "EndSB execution", tango.ErrSeverity.ERR) try: proxy = self._se_subarrays_proxies[self._cbf_subarray_fqdn] proxy.ping() proxy.command_inout_asynch("EndSB", self.__cmd_ended) except tango.DevFailed as df: log_msg = '' for item in df.args: log_msg += item.reason + " " + item.desc self.dev_logging(log_msg, tango.LogLevel.LOG_ERROR) tango.Except.re_throw_exception(df, "Command failed", "CspSubarray EndSB command failed", "Command()", tango.ErrSeverity.ERR) # PROTECTED REGION END # // CspSubarray.EndSB # ---------- # Run server # ---------- def main(args=None, **kwargs): # PROTECTED REGION ID(CspSubarray.main) ENABLED START # return run((CspSubarray,), args=args, **kwargs) # PROTECTED REGION END # // CspSubarray.main if __name__ == '__main__': main() <file_sep>/code-analysis.sh #!/usr/bin/env bash echo "STATIC CODE ANALYSIS" echo "====================" echo echo "MODULE ANALYSIS" echo "---------------" pylint --rcfile=.pylintrc csplmc/CspMaster/CspMaster pylint --rcfile=.pylintrc csplmc/CspSubarray/CspSubarray echo "TESTS ANALYSIS" echo "--------------" pylint --rcfile=.pylintrc csplmc/CspMaster/test pylint --rcfile=.pylintrc csplmc/CspSubarray/test <file_sep>/test-harness/Makefile # Use bash shell with pipefail option enabled so that the return status of a # piped command is the value of the last (rightmost) commnand to exit with a # non-zero status. This lets us pipe output into tee but still exit on test # failures. SHELL = /bin/bash .SHELLFLAGS = -o pipefail -c all: test lint # wait for the device to be available before beginning the test # A temporary volume is mounted at /build when 'make test' is executing. # The following steps copy across useful output to this volume which can # then be extracted to form the CI summary for the test procedure. test: retry --max=10 -- tango_admin --ping-device mid_csp_cbf/sub_elt/master retry --max=10 -- tango_admin --ping-device mid_csp_cbf/sub_elt/subarray_01 retry --max=10 -- tango_admin --ping-device mid_csp_cbf/sub_elt/subarray_02 retry --max=10 -- tango_admin --ping-device mid_csp/elt/master retry --max=10 -- tango_admin --ping-device mid_csp/elt/subarray_01 retry --max=10 -- tango_admin --ping-device mid_csp/elt/subarray_02 cd /app/csplmc/CspSubarray && python setup.py test | tee setup_py_test.stdout cd /app/csplmc/CspMaster && python setup.py test | tee setup_py_test.stdout mkdir -p /build/reports; \ mv /app/csplmc/CspMaster/setup_py_test.stdout /build/csp_master_setup_test.stdout; \ mv /app/csplmc/CspMaster/htmlcov /build/csp_master_htmlcov; \ mv /app/csplmc/CspMaster/coverage.xml /build/csp_master_coverage.xml; \ mv /app/csplmc/CspSubarray/setup_py_test.stdout /build/csp_subarray_setup_test.stdout; \ mv /app/csplmc/CspSubarray/htmlcov /build/csp_subarray_htmlcov; \ mv /app/csplmc/CspSubarray/coverage.xml /build/reports/code-coverage.xml; lint: pip3 install pylint2junit; \ mkdir -p /build/reports; \ cd /app && pylint --output-format=parseable csplmc | tee /build/code_analysis.stdout; \ cd /app && pylint --output-format=pylint2junit.JunitReporter csplmc > /build/reports/linting.xml; .PHONY: all test lint <file_sep>/csplmc/CspSubarray/docs/src/index.rst CspSubarray ************************ .. automodule:: CspSubarray .. autoclass:: CspSubarray :members: <file_sep>/csplmc/CspSubarray/test/CspSubarray_two_devices_test.py #!/usr/bin/env python # -*- coding: utf-8 -*- # # This file is part of the csp-lmc-prototype project # # Distributed under the terms of the BSD-3-Clause license. # See LICENSE.txt for more info. """Contain the tests for the CspSubarray.""" # Standard imports import sys import os import time # Tango imports import tango from tango import DevState import pytest # Path file_path = os.path.dirname(os.path.abspath(__file__)) # insert base package directory to import global_enum # module in commons folder commons_pkg_path = os.path.abspath(os.path.join(file_path, "../../commons")) sys.path.insert(0, commons_pkg_path) path = os.path.join(os.path.dirname(__file__), os.pardir) sys.path.insert(0, os.path.abspath(path)) #Local imports from CspSubarray import CspSubarray from global_enum import ObsState # Device test case @pytest.mark.usefixtures("csp_master", "csp_subarray01", "cbf_subarray01", "csp_subarray02", "tm_leafnode1") class TestCspSubarray_two_devices(object): def test_add_receptors_to_sub1_and_sub2(self, csp_subarray01, csp_subarray02, csp_master, tm_leafnode1): """ Test allocation of receptors with two subarrays. Both subarrays move to State ON after assignment. """ csp_subarray01.Init() time.sleep(2) tm_leafnode1.Init() if csp_master.state() == DevState.STANDBY: csp_master.On("") time.sleep(2) assert (csp_subarray01.state() == DevState.OFF and csp_subarray02.state() == DevState.OFF and csp_subarray01.obsState == ObsState.IDLE and csp_subarray02.obsState == ObsState.IDLE) # add receptors 1,4 to subarray 01 receptor_to_assign = [1, 4] csp_subarray01.AddReceptors(receptor_to_assign) time.sleep(2) # add receptors 2,3 to subarray 02 receptor_to_assign = [2, 3] csp_subarray02.AddReceptors(receptor_to_assign) time.sleep(2) assert (csp_subarray01.obsState == ObsState.IDLE and csp_subarray02.obsState == ObsState.IDLE and csp_subarray01.state() == tango.DevState.ON and csp_subarray02.state() == tango.DevState.ON) def test_configureScan_sub1_and_sub2(self, csp_subarray01, csp_subarray02): """ Test scan configuration with two subarrays. """ assert (csp_subarray01.state() == tango.DevState.ON and csp_subarray02.state() == tango.DevState.ON) filename1 = os.path.join(commons_pkg_path, "test_ConfigureScan_basic.json") filename2 = os.path.join(commons_pkg_path, "test_ConfigureScan_band1_sub2.json") config_file1 = open(filename1) config_file2 = open(filename2) csp_subarray01.ConfigureScan(config_file1.read().replace("\n", "")) csp_subarray02.ConfigureScan(config_file2.read().replace("\n", "")) time.sleep(4) assert (csp_subarray01.obsState == ObsState.READY and csp_subarray02.obsState == ObsState.READY) config_file1.close() config_file2.close() def test_start_scan_sub1_and_sub2(self, csp_subarray01, csp_subarray02): """ Test Scan method with two subarrays. """ assert (csp_subarray01.obsState == ObsState.READY and csp_subarray02.obsState == ObsState.READY) csp_subarray01.Scan(" ") csp_subarray02.Scan(" ") time.sleep(2) assert (csp_subarray01.obsState == ObsState.SCANNING and csp_subarray02.obsState == ObsState.SCANNING) def test_end_scan(self, csp_subarray01, csp_subarray02): """ Test EndScan method with two subarrays. """ assert (csp_subarray01.obsState == ObsState.SCANNING and csp_subarray02.obsState == ObsState.SCANNING) csp_subarray01.EndScan() csp_subarray02.EndScan() time.sleep(2) assert (csp_subarray01.obsState == ObsState.READY and csp_subarray02.obsState == ObsState.READY) <file_sep>/csplmc/release.py # -*- coding: utf-8 -*- # # This file is part of the CentralNode project # # # # Distributed under the terms of the BSD-3-Clause license. # See LICENSE.txt for more info. """Release information for Python Package""" name = """tangods-csplmc""" version = "0.2.1" version_info = version.split(".") description = """SKA Csp LMC TANGO Devices""" author = "E.G" author_email = "<EMAIL>" license = """BSD-3-Clause""" url = """www.tango-controls.org""" copyright = """""" <file_sep>/csplmc/CspSubarray/test/CspSubarray_test.py #!/usr/bin/env python # -*- coding: utf-8 -*- # # This file is part of the csp-lmc-prototype project # # # # Distributed under the terms of the BSD-3-Clause license. # See LICENSE.txt for more info. """Contain the tests for the CspSubarray.""" # Standard imports import sys import os import time import random import numpy as np # Tango imports import tango from tango import DevState import pytest # Path file_path = os.path.dirname(os.path.abspath(__file__)) # insert base package directory to import global_enum # module in commons folder commons_pkg_path = os.path.abspath(os.path.join(file_path, "../../commons")) sys.path.insert(0, commons_pkg_path) path = os.path.join(os.path.dirname(__file__), os.pardir) sys.path.insert(0, os.path.abspath(path)) #Local imports from CspSubarray import CspSubarray from global_enum import ObsState # Device test case @pytest.mark.usefixtures("csp_master", "csp_subarray01", "cbf_subarray01", "csp_subarray02") class TestCspSubarray(object): def test_State(self, csp_subarray01, csp_master): """ Test for State after CSP startup. The CspSubarray State at start is OFF. """ csp_subarray01.Init() time.sleep(2) state = csp_subarray01.state() assert state in [DevState.DISABLE] #switch-on the CspMaster csp_master_state = csp_master.state() assert csp_master_state == DevState.STANDBY csp_master.On("") time.sleep(2) state = csp_subarray01.state() assert state in [DevState.OFF] def test_add_invalid_receptor_ids(self, csp_subarray01, csp_master): """ Test the assignment of a number of invalid receptor IDs to a CspSubarray. The AddReceptors method fails raising a tango.DevFailed exception. """ receptors_list = csp_master.availableReceptorIDs # receptor_list is a numpy array # all(): test whether all array elements evaluate to True. assert receptors_list.all() invalid_receptor_to_assign = [] # try to add 3 invalid receptors for id_num in range(1, 198): if id_num not in receptors_list: invalid_receptor_to_assign.append(id_num) if len(invalid_receptor_to_assign) > 3: break csp_subarray01.AddReceptors(invalid_receptor_to_assign) time.sleep(2) receptors = csp_subarray01.receptors # receptors is a numpy array. In this test the returned array has to be # empty (no receptor assigned) # # Note: # any returns True if any value is True. Otherwise False # all returns True if no value is False. Otherwise True # In the case of np.array([]).any() or any([]), there are no True values, because you have # a 0-dimensional array or a 0-length list. Therefore, the result is False. # In the case of np.array([]).all() or all([]), there are no False values, because you have # a 0-dimensional array or a 0-length list. Therefore, the result is True. assert not receptors.any() def test_add_valid_receptor_ids(self, csp_subarray01, csp_master): """ Test the assignment of valid receptors to a CspSubarray """ # get the list of available receptorIDs (the read operation # returns a numpy array) receptor_list = csp_master.availableReceptorIDs # assert the array is not empty assert receptor_list.any() csp_subarray01.AddReceptors(receptor_list) # sleep a while to wait for attribute updated time.sleep(2) # read the list of assigned receptors receptors = csp_subarray01.receptors assert set(receptor_list) == set(receptors) def test_add_already_assigned_receptor_ids(self, csp_subarray01, csp_master): """ Test the assignment of already assigned receptors to a CspSubarray """ # read the list of receptors allocated to the subarray assigned_receptors = csp_subarray01.receptors # assert the list of receptor is not empty assert assigned_receptors.any() # add to the subarray an already assigned receptor receptors_to_add = [assigned_receptors[0]] csp_subarray01.AddReceptors(receptors_to_add) time.sleep(2) receptors = csp_subarray01.receptors # check the array read first and the array read last are equal assert np.array_equal(receptors, assigned_receptors) def test_State_after_receptors_assignment(self, csp_subarray01): """ Test the CspSubarray State after receptors assignment. After assignment State is ON """ # read the list of assigned receptors and check it's not # empty assigned_receptors = csp_subarray01.receptors assert assigned_receptors.any() # read the CspSubarray State state = csp_subarray01.state() assert state == DevState.ON def test_remove_receptors(self, csp_subarray01): """ Test the partial deallocation of receptors from a CspSubarray. """ # read the list of assigned receptors and check it's not # empty assigned_receptors = csp_subarray01.receptors assert assigned_receptors.any() init_number_of_receptors = len(assigned_receptors) # check there is more than one receptor assigned to # the subarray assert init_number_of_receptors > 1 i = random.randrange(1, 4, 1) receptor_to_remove = [] receptor_to_remove.append(i) # remove only one receptor (with a random ID) csp_subarray01.RemoveReceptors(receptor_to_remove) time.sleep(4) assigned_receptors = csp_subarray01.receptors final_number_of_receptors = len(assigned_receptors) assert (init_number_of_receptors - final_number_of_receptors) == 1 def test_assign_valid_and_invalid_receptors(self, csp_subarray01, csp_master): """ Test the allocation of receptors when some receptor IDs are not valid. """ # read the list of assigned receptors and check it's not # empty receptors_to_add = [] assigned_receptors = csp_subarray01.receptors num_of_initial_receptors = len(assigned_receptors) assert assigned_receptors.any() # add valid receptors to the list of resources to assign available_receptors = csp_master.availableReceptorIDs for id_num in available_receptors: receptors_to_add.append(id_num) num_of_valid_receptors = len(receptors_to_add) # add 3 invalid receptor iteration = 0 for id_num in range(1, 198): #skip the assigned receptors if id_num in assigned_receptors: continue else: receptors_to_add.append(id_num) iteration += 1 if iteration == 3: break assert receptors_to_add csp_subarray01.AddReceptors(receptors_to_add) time.sleep(2) assigned_receptors = csp_subarray01.receptors final_number_of_receptors = len(assigned_receptors) assert final_number_of_receptors == (num_of_initial_receptors + num_of_valid_receptors) def test_remove_all_receptors(self, csp_subarray01): """ Test the complete deallocation of receptors from a CspSubarray. Final CspSubarray state is OFF """ # read the list of assigned receptors and check it's not # empty assigned_receptors = csp_subarray01.receptors assert assigned_receptors.any() csp_subarray01.RemoveAllReceptors() time.sleep(2) assigned_receptors = csp_subarray01.receptors # check the array is empty (any() in this case returns False) assert not assigned_receptors.any() time.sleep(2) assert csp_subarray01.state() == DevState.OFF def test_configureScan_invalid_state(self, csp_subarray01): """ Test that the ConfigureScan() command fails if the Subarray state is not ON """ # check the subarray state is Off (the previous test has removed # all the receptors from the subarray, so its state should be OFF subarray_state = csp_subarray01.State() assert subarray_state == tango.DevState.OFF filename = os.path.join(commons_pkg_path, "test_ConfigureScan_basic.json") f = open(filename) with pytest.raises(tango.DevFailed) as df: csp_subarray01.ConfigureScan(f.read().replace("\n", "")) if df: err_msg = str(df.value.args[0].desc) assert "Command ConfigureScan not allowed" in err_msg def test_configureScan(self, csp_subarray01, csp_master): """ Test that the ConfigureScan() command is issued when the Subarray state is ON and ObsState is IDLE or READY """ obs_state = csp_subarray01.obsState assert obs_state in [ObsState.IDLE, ObsState.READY] receptor_list = csp_master.availableReceptorIDs time.sleep(2) # receptor_list is a numpy array. If there is no available receptor to assign, # receptor_list is a numpy array with only one element whose value is 0, that is: # receptor_list = [0] -> means no available receptor # To assert the list of receptor is not empty use the numpy any() # method # assert (receptor_list.size and (receptor_list[0] != 0)) assert receptor_list.any() # assign only receptors [1,4] for which the configuration addresses are provided in # the configuration JSON file receptors_to_assign = [1, 4] csp_subarray01.AddReceptors(receptors_to_assign) time.sleep(2) subarray_state = csp_subarray01.State() assert subarray_state == tango.DevState.ON filename = os.path.join(commons_pkg_path, "test_ConfigureScan_basic.json") f = open(filename) csp_subarray01.ConfigureScan(f.read().replace("\n", "")) f.close() time.sleep(5) obs_state = csp_subarray01.obsState assert obs_state == ObsState.READY def test_start_scan(self, csp_subarray01): """ Test that a subarray is able to process the Scan command when its ObsState is READY """ obs_state = csp_subarray01.obsState assert obs_state == ObsState.READY csp_subarray01.Scan(" ") time.sleep(2) obs_state = csp_subarray01.obsState assert obs_state == ObsState.SCANNING def test_end_scan(self, csp_subarray01): """ Test that a subarray is able to process the EndScan command when its ObsState is SCANNING. """ obs_state = csp_subarray01.obsState assert obs_state == ObsState.SCANNING csp_subarray01.EndScan() time.sleep(3) obs_state = csp_subarray01.obsState assert obs_state == ObsState.READY def test_remove_receptors_when_ready(self, csp_subarray01): """ Test that the complete deallocation of receptors fails when the CspSubarray ObsMode is READY. Receptors can be removed only when the subarray ObsState is IDLE! """ obs_state = csp_subarray01.obsState assert obs_state == ObsState.READY with pytest.raises(tango.DevFailed) as df: csp_subarray01.RemoveAllReceptors() if df: err_msg = str(df.value.args[0].desc) assert "Command RemoveAllReceptors not allowed" in err_msg def test_remove_receptors_when_idle(self, csp_subarray01): """ Test the complete deallocation of receptors from a CspSubarray when the subarray is IDLE. """ obs_state = csp_subarray01.obsState assert obs_state == ObsState.READY # command transition to IDLE csp_subarray01.EndSB() time.sleep(3) obs_state = csp_subarray01.obsState assert obs_state == ObsState.IDLE csp_subarray01.RemoveAllReceptors() time.sleep(3) subarray_state = csp_subarray01.state() assert subarray_state == tango.DevState.OFF assert obs_state == ObsState.IDLE <file_sep>/stop_prototype.sh #!/bin/bash # # Script to stopt the CSP.LMC prototype TANGO devices. # The script looks for the TANGO servers. If they are running it get their # pids and send them a TERM signal. # # get the pid of the Csp prototype TANGO servers server_running=$(ps -ef | grep '[p]ython csplmc' | awk '{print $9}') # check if they are running and in case kill them len=${#server_running} if [ $len -gt 0 ]; then echo "Stopping the Csp prototype devices" server_pid=$(ps -ef | grep '[p]ython csplmc' | awk '{print $2}') for t1 in $server_pid ;do kill -9 $t1 if [ $? -eq 0 ]; then echo "Stopped server (PID $t1)" else echo "Failure in stopping the TANGO device servers" fi done else echo "No Csp prototype TANGO device running" fi <file_sep>/README.md [![Documentation Status](https://readthedocs.org/projects/csp-lmc-prototype/badge/?version=latest)](https://developer.skatelescope.org/projects/csp-lmc-prototype/en/latest/?badge=latest) [![coverage report](https://gitlab.com/ska-telescope/csp-lmc-prototype/badges/master/coverage.svg)](https://ska-telescope.gitlab.io/csp-lmc-prototype/) [![pipeline status](https://gitlab.com/ska-telescope/csp-lmc-prototype/badges/master/pipeline.svg)](https://gitlab.com/ska-telescope/csp-lmc-prototype/pipelines) ## Table of contents * [Description](#description) * [Getting started](#getting-started) * [Prerequisities](#prerequisities) * [Run on local host](#how-to-run-on-local-host) * [Start the devices](#start-the-devices) * [Configure the devices](#configure-the-devices) * [Run in containers](#how-to-run-in-docker-containers) * [Running tests](#running-tests) * [Known bugs](#known-bugs) * [Troubleshooting](#troubleshooting) * [License](#license) ## Description At the present time the `CSP.LMC` prototype implements two TANGO devices: * the `CspMaster` device: based on the `SKA Base SKAMaster` class. The `CspMaster` represents a primary point of contact for CSP Monitor and Control. It implements CSP state and mode indicators and a limited set of housekeeping commands. * the `CspSubarray` device: based on the `SKA Base SKASubarray` class, models a CSP subarray. ## Getting started The project can be found in the SKA gitlab repository. To get a local copy of the project: ```bash git clone https://gitlab.com/ska-telescope/csp-lmc-prototype.git ``` ## Prerequisities * A TANGO development environment properly configured, as described in [SKA developer portal](https://developer.skatelescope.org/en/latest/tools/tango-devenv-setup.html) * [SKA Base classes](https://gitlab.com/ska-telescope/lmc-base-classes) ## How to run on local host ### Start the devices The script `start_prototype` in the project root directory starts the `CSP.LMC` TANGO Devices, doing some preliminary controls. The script: * checks if the TANGO DB is up and running * configure the CSP.LMC devices properties,executing the python script [configureDevices.py](csplmc/configureDevices.py) * checks if the CSP.LMC prototype TANGO devices are already registered within the TANGO DB, otherwise it adds them * starts the CSP.LMC prototype devices (CspMaster and CspSubarray1). * starts the `jive` tool (if installed in the local system). The `stop_prototype` script stops the execution of the `CSP.LMC` prototype TANGO Device servers. In particular it: * checks if the `CSP.LMC` prototype TANGO Servers are running * gets the `pids` of the running servers * send them the TERM signal __NOTE__ > The `start_prototype` script starts *only* the CSP.LMC TANGO Devices. The [Mid CBF project](https://gitlab.com/ska-telescope/mid-cbf-mcs), provides a complete set of `Mid-CBF.LMC` devices that can be used to test the `CSP.LMC` monitor and control capabilities. **However, the reccommended method to run the whole CSP.LMC prototype is via the use of Docker containers** (see below). ### Configure the devices Once started, the devices need to be configured into the TANGO DB. The `jive` tool can be used to set the `polling period` and `change events` for the `healthState` and `State` attributes of both devices. For example, the procedure to configure the `CspSubarray1` device is as follow: * start `jive` * from the top of `jive` window select `Device` * drill down into the list of devices * select the device `mid_csp/elt/subarray_01` * select `Polling` entry (left window) and select the `Attributes` tab (right window) * select the check button in corrispondence of the `healthState` and `State` entries. The default polling period is set to 3000 ms, it can be changed to 1000. * select `Events` entry (left window) and select the `Change event` tab (right window) * set to 1 the `Absolute` entry for the `healthState` attribute The same sequence of operations has to be repeated for all the provided devices otherwise no TANGO client is able to subscribe and receive `events` for that devices. A dedicated script (based on the work done by the NCRA team) has been written to perform this procedure in automatic way (see [configureAttrProperties.py](csplmc/configureAttrProperties.py). Run this script *only* after the start of the CSP prototype devices. __NOTE__ > Both the [configureAttrProperties.py](csplmc/configureAttrProperties.py) and the [configureDevices.py](csplmc/configureDevices.py) scripts relies on the JSON file [devices.json](csplmc/devices.json) with the full description of the `CSP.LMC` and `Mid-CBF.LMC` TANGO Devices populating the `CSP TANGO DB`. <br/> To add a new TANGO Device to the TANGO DB, a new entry for the device has to be added to this file. Also the `start_prototype` has to be updated to run the new device. ## How to run in Docker containers The CSP.LMC prototype can run also in a containerised environment. Currently only a limitated number of CSP.LMC and Mid-CBF.LMC devices are run in Docker containers: * the CspMaster and CbfMaster * two instances of the CSP and CBF subarrays * four instances of the Very Coarse Channelizer (VCC) devices * four instance of the Frequency Slice Processor (FPS) devices * two instances of the TM TelState Simulator devices The Mid-CBF.LMC containers are created pulling the `mid-cbf-mcs` project image from the [Nexus repository](https://nexus.engageska-portugal.pt). <br/> The CSP.LMC projects provides a [Makefile](Makefile) to run automatically the system containers and the tests.<br/> The CSP.LMC containerised environment relies on three YAML configuration files: * `csplmc-tangodb.yml` * `csp-lmc.yml` * `mid-cbf-mcs.yml` Each file includes the stages to run the the `CSP.LMC TANGO DB`, `CSP.LMC` and `Mid-CBF.LMC` TANGO Devices inside separate docker containers.<br/> These YAML files are used by `docker-compose` to run both the CSP.LMC and CBF.LMC TANGO device instances, that is, to run the whole `Csp.LMC` prototype. In this way, it's possible to execute some preliminary integration tests, as for example the assignment/release of receptors to a `CSPSubarray` and its configuration to execute a scan in Imaging mode. The `CSP.LMC` and `Mid-CBF.LMC TANGO` Devices are registered with the same TANGO DB, and its configuration is performed via the `dsconfig` TANGO Device provided by the [dsconfig project](https://gitlab.com/MaxIV-KitsControls/lib-maxiv-dsconfig). <br /> This device use a JSON file to configure the TANGO DB. <br/> The `CSP.LMC` and `Mid-CBF.LMC` projects provide its own JSON file: [csplmc\_dsconfig.json](csplmc/data/csplmc_dsconfig.json) and [midcbf\_dsconfig.json](csplmc/data/midcbf_dsconfig.json) To run the `CSP.LMC` prototype inside Docker containers, issue the command: ```bash make up ``` from the project root directory. At the end of the procedure the command <pre><code>docker ps</code></pre> shows the list of the running containers: ``` csplmc-tangodb: the MariaDB database with the TANGO database tables csplmc-databaseds: the TANGO DB device server csplmc-cbf_dsconfig: the dsconfig container to configure CBF.LMC devices in the TANGO DB csplmc-cbf_dsconfig: the dsconfig container to configure CSP.LMC devices in the TANGO DB csplmc-cspmaster: the CspMaster TANGO device csplmc-cspsubarray[01-02]: two instances of the CspSubarray TANGO device csplmc-cspsubarray02: the instance 01 of the CspSubarray TANGO device csplmc-rsyslog-csplmc: the rsyslog container for the CSP.LMC devices csplmc-rsyslog-cbf : the rsyslog container for the CBF.LMC devices csplmc-cbfmaster: the CbfMaster TANGO device csplmc-cbfsubarray[01-02]: two instances of the CbfSubarray TANGO device csplmc-vcc[001-004]: four instances of the Mid-CBF VCC TANGO device csplmc-fsp[01-04]: four instances of the Mid-CBF FSP TANGO device csplmc-tmcspsubarrayleafnodetest/2: two instances of the TelState TANGO Device simulator provided by the CBF project to support scan configuration for Subarray1/2 ``` To stop and removes the Docker containers, issue the command <pre><code>make down</code></pre> from the prototype root directory. __NOTE__ >Docker containers are run with the `--network=host` option. In this case there is no isolation between the host machine and the containers. <br/> This means that the TANGO DB running in the container is available on port 10000 of the host machine. <br /> Running `jive` on the local host, the `CSP.LMC` and `Mid-CBF.LMC` TANGO Devices registered with the TANGO DB (running in a docker container) can be visualized and explored. ## Running tests The project includes a set of tests for the CspMaster and CspSubarray TANGO Devices that can be found respectively in the folders: * `csplmc/CspMaster/test` * `csplmc/CspSubarray/test` To run the test on the local host issue the command <code><pre>make test</pre></code> from the root project directory. The test are run in docker containers providing the proper environment setup and isolation. ## Known bugs * ## Troubleshooting It may happens that the TANGO attributes configured for polling and/or events via the POGO tools, are not correclty configured when the TANGO Devices start. <br/> Please check their configuration inside the TANGO DB (where the devices are registered) and follow the instructions [here](#configure-the-devices) to setup the `polling` and `change events` of the attribute. <br/> This issue is generally resolved running the [configureAttrProperties.py](csplmc/configureAttrProperties.py) (when the `start_prototype` script is used) or the `dsconfig` container (when the system run in the containerised environment) but the configuration files these mechanisms rely on, have to include the necessary information about the properties of the attribute concerned. ## License See the LICENSE file for details. <file_sep>/csplmc/configureAttrProperties.py # This script is used only when the CSP.LMC devices are run via # the start_prototype script. # Docker containers rely on dsconfig device to configure the TANGO Attribute properties. #!/usr/bin/env python import json from tango import AttributeProxy, ChangeEventInfo # Update file path to devices.json in order to test locally with open('./csplmc/devices.json', 'r') as file: jsonDevices = file.read().replace('\n', '') # Loading devices.json file and creating an object json_devices = json.loads(jsonDevices) for device in json_devices: deviceName = device["devName"] for attributeProperty in device["attributeProperties"]: if attributeProperty["attrPropName"] == "__root_att": continue attributeProxy = AttributeProxy(deviceName + "/" + attributeProperty["attributeName"]) if attributeProperty["pollingPeriod"] != "": attributeProxy.poll(attributeProperty["pollingPeriod"]) if attributeProperty["changeEventAbs"] != "": attrInfoEx = attributeProxy.get_config() absChange = ChangeEventInfo() absChange.abs_change = attributeProperty["changeEventAbs"] attrInfoEx.events.ch_event = absChange attributeProxy.set_config(attrInfoEx) <file_sep>/Makefile # # Project makefile for a Tango project. You should normally only need to modify # DOCKER_REGISTRY_USER and PROJECT below. # # # DOCKER_REGISTRY_HOST, DOCKER_REGISTRY_USER and PROJECT are combined to define # the Docker tag for this project. The definition below inherits the standard # value for DOCKER_REGISTRY_HOST (=rnexus.engageska-portugal.pt) and overwrites # DOCKER_REGISTRY_USER and PROJECT to give a final Docker tag of # nexus.engageska-portugal.pt/tango-example/csplmc # DOCKER_REGISTRY_USER:=ska-docker PROJECT = csplmc # # include makefile to pick up the standard Make targets, e.g., 'make build' # build, 'make push' docker push procedure, etc. The other Make targets # ('make interactive', 'make test', etc.) are defined in this file. # include .make/Makefile.mk # # IMAGE_TO_TEST defines the tag of the Docker image to test # IMAGE_TO_TEST = $(DOCKER_REGISTRY_HOST)/$(DOCKER_REGISTRY_USER)/$(PROJECT):latest # # CACHE_VOLUME is the name of the Docker volume used to cache eggs and wheels # used during the test procedure. The volume is not used during the build # procedure # CACHE_VOLUME = $(PROJECT)-test-cache # optional docker run-time arguments DOCKER_RUN_ARGS = # # Never use the network=host mode when running CI jobs, and add extra # distinguishing identifiers to the network name and container names to # prevent collisions with jobs from the same project running at the same # time. # ifneq ($(CI_JOB_ID),) NETWORK_MODE := tangonet-$(CI_JOB_ID) CONTAINER_NAME_PREFIX := $(PROJECT)-$(CI_JOB_ID)- else CONTAINER_NAME_PREFIX := $(PROJECT)- endif COMPOSE_FILES := $(wildcard *.yml) COMPOSE_FILE_ARGS := $(foreach yml,$(COMPOSE_FILES),-f $(yml)) ifeq ($(OS),Windows_NT) $(error Sorry, Windows is not supported yet) else UNAME_S := $(shell uname -s) ifeq ($(UNAME_S),Linux) DISPLAY ?= :0.0 NETWORK_MODE ?= host XAUTHORITY_MOUNT := /tmp/.X11-unix:/tmp/.X11-unix XAUTHORITY ?= /hosthome/.Xauthority # /bin/sh (=dash) does not evaluate 'docker network' conditionals correctly SHELL := /bin/bash endif ifeq ($(UNAME_S),Darwin) IF_INTERFACE := $(shell netstat -nr | awk '{ if ($$1 ~/default/) { print $$6} }') DISPLAY := $(shell ifconfig $(IF_INTERFACE) | awk '{ if ($$1 ~/inet$$/) { print $$2} }'):0 # network_mode = host doesn't work on MacOS, so fix to the internal network NETWORK_MODE := tangonet XAUTHORITY_MOUNT := $(HOME):/hosthome:ro XAUTHORITY := /hosthome/.Xauthority endif endif # # When running in network=host mode, point devices at a port on the host # machine rather than at the container. # ifeq ($(NETWORK_MODE),host) TANGO_HOST := $(shell hostname):10000 MYSQL_HOST := $(shell hostname):3306 else # distinguish the bridge network from others by adding the project name NETWORK_MODE := $(NETWORK_MODE)-$(PROJECT) TANGO_HOST := $(CONTAINER_NAME_PREFIX)databaseds:10000 MYSQL_HOST := $(CONTAINER_NAME_PREFIX)tangodb:3306 endif DOCKER_COMPOSE_ARGS := DISPLAY=$(DISPLAY) XAUTHORITY=$(XAUTHORITY) TANGO_HOST=$(TANGO_HOST) \ NETWORK_MODE=$(NETWORK_MODE) XAUTHORITY_MOUNT=$(XAUTHORITY_MOUNT) MYSQL_HOST=$(MYSQL_HOST) \ DOCKER_REGISTRY_HOST=$(DOCKER_REGISTRY_HOST) DOCKER_REGISTRY_USER=$(DOCKER_REGISTRY_USER) \ CONTAINER_NAME_PREFIX=$(CONTAINER_NAME_PREFIX) COMPOSE_IGNORE_ORPHANS=true # # Defines a default make target so that help is printed if make is called # without a target # .DEFAULT_GOAL := help # # defines a function to copy the ./test-harness directory into the container # and then runs the requested make target in the container. The container is: # # 1. attached to the network of the docker-compose test system # 2. uses a persistent volume to cache Python eggs and wheels so that fewer # downloads are required # 3. uses a transient volume as a working directory, in which untarred files # and test output can be written in the container and subsequently copied # to the host # make = tar -c test-harness/ | \ docker run -i --rm --network=$(NETWORK_MODE) \ -e TANGO_HOST=$(TANGO_HOST) \ -v $(CACHE_VOLUME):/home/tango/.cache \ --volumes-from=$(CONTAINER_NAME_PREFIX)rsyslog-csplmc:rw \ -v /build -w /build -u tango $(DOCKER_RUN_ARGS) $(IMAGE_TO_TEST) \ bash -c "sudo chown -R tango:tango /build && \ tar x --strip-components 1 --warning=all && \ make TANGO_HOST=$(TANGO_HOST) $1" test: DOCKER_RUN_ARGS = --volumes-from=$(BUILD) test: build up ## test the application @echo "BUILD: $(BUILD)" $(INIT_CACHE) $(call make,test); \ status=$$?; \ rm -fr build; \ #docker-compose $(COMPOSE_FILE_ARGS) logs; docker cp $(BUILD):/build .; \ docker rm -f -v $(BUILD); \ $(MAKE) down; \ exit $$status lint: DOCKER_RUN_ARGS = --volumes-from=$(BUILD) lint: build up ## lint the application (static code analysis) $(INIT_CACHE) $(call make,lint); \ status=$$?; \ docker cp $(BUILD):/build .; \ $(MAKE) down; \ exit $$status pull: ## download the application image docker pull $(IMAGE_TO_TEST) up: build ## start develop/test environment ifneq ($(NETWORK_MODE),host) docker network inspect $(NETWORK_MODE) &> /dev/null || ([ $$? -ne 0 ] && docker network create $(NETWORK_MODE)) endif #$(DOCKER_COMPOSE_ARGS) docker-compose $(COMPOSE_FILE_ARGS) pull #to pull only the mid-cbf-mcs image remove comment on row below. #docker pull $(DOCKER_REGISTRY_HOST)/$(DOCKER_REGISTRY_USER)/mid-cbf-mcs:latest $(DOCKER_COMPOSE_ARGS) docker-compose -f csp-tangodb.yml up -d # put a sleep to wait TANGO DB @sleep 10 $(DOCKER_COMPOSE_ARGS) docker-compose $(COMPOSE_FILE_ARGS) up -d piplock: build ## overwrite Pipfile.lock with the image version docker run $(IMAGE_TO_TEST) cat /app/Pipfile.lock > $(CURDIR)/Pipfile.lock interactive: up interactive: ## start an interactive session using the project image (caution: R/W mounts source directory to /app) docker run --rm -it -p 3000:3000 --name=$(CONTAINER_NAME_PREFIX)dev -e TANGO_HOST=$(TANGO_HOST) --network=$(NETWORK_MODE) \ -v $(CURDIR):/app $(IMAGE_TO_TEST) /bin/bash down: ## stop develop/test environment and any interactive session docker ps | grep $(CONTAINER_NAME_PREFIX)dev && docker stop $(PROJECT)-dev || true $(DOCKER_COMPOSE_ARGS) docker-compose $(COMPOSE_FILE_ARGS) down ifneq ($(NETWORK_MODE),host) docker network inspect $(NETWORK_MODE) &> /dev/null && ([ $$? -eq 0 ] && docker network rm $(NETWORK_MODE)) || true endif dsconfigdump: up ## dump the entire configuration to the file dsconfig.json docker exec -it $(CONTAINER_NAME_PREFIX)dsconfigdump python -m dsconfig.dump docker exec -it $(CONTAINER_NAME_PREFIX)dsconfigdump python -m dsconfig.dump > dsconfig.json dsconfigadd: up ## Add a configuration json file (environment variable DSCONFIG_JSON_FILE) to the database -docker exec -it $(CONTAINER_NAME_PREFIX)dsconfigdump json2tango -u -w -a $(DSCONFIG_JSON_FILE) dsconfigcheck: up ## check a json file (environment variable DSCONFIG_JSON_FILE) according to the project lib-maxiv-dsconfig json schema -docker exec -it $(CONTAINER_NAME_PREFIX)dsconfigdump json2tango -a $(DSCONFIG_JSON_FILE) help: ## show this help. @grep -hE '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' .PHONY: all test up down help # Creates Docker volume for use as a cache, if it doesn't exist already INIT_CACHE = \ docker volume ls | grep $(CACHE_VOLUME) || \ docker create --name $(CACHE_VOLUME) -v $(CACHE_VOLUME):/cache $(IMAGE_TO_TEST) # http://cakoose.com/wiki/gnu_make_thunks BUILD_GEN = $(shell docker create -v /build $(IMAGE_TO_TEST)) BUILD = $(eval BUILD := $(BUILD_GEN))$(BUILD) <file_sep>/csplmc/CspMaster/conftest.py """ A module defining a list of fixture functions that are shared across all the skabase tests. """ #from __future__ import absolute_import #import mock import pytest #sys.path.insert(0, "../commons") import tango #from tango.test_context import DeviceTestContext #import global_enum @pytest.fixture(scope="class") def csp_master(): """Create DeviceProxy for the CspMaster device to test the device with the TANGO DB """ database = tango.Database() instance_list = database.get_device_exported_for_class('CspMaster') for instance in instance_list.value_string: try: return tango.DeviceProxy(instance) except tango.DevFailed: continue @pytest.fixture(scope="class") def csp_subarray01(): """Create DeviceProxy for the CspMaster device to test the device with the TANGO DB """ database = tango.Database() instance_list = database.get_device_exported_for_class('CspSubarray') for instance in instance_list.value_string: try: if "subarray_01" in instance: return tango.DeviceProxy(instance) except tango.DevFailed: continue @pytest.fixture(scope="class") def cbf_subarray01(): """Create DeviceProxy for the CspMaster device to test the device with the TANGO DB """ database = tango.Database() instance_list = database.get_device_exported_for_class('CbfSubarray') for instance in instance_list.value_string: try: if "subarray_01" in instance: return tango.DeviceProxy(instance) except tango.DevFailed: continue @pytest.fixture(scope="class") def cbf_master(): """Create DeviceProxy for the CspMaster device to test the device with the TANGO DB """ database = tango.Database() instance_list = database.get_device_exported_for_class('CbfMaster') for instance in instance_list.value_string: try: return tango.DeviceProxy(instance) except tango.DevFailed: continue <file_sep>/csplmc/CspSubarray/conftest.py """ A module defining a list of fixture functions that are shared across all the skabase tests. """ #from __future__ import absolute_import #import mock import pytest import tango from tango import DeviceProxy #from tango.test_context import DeviceTestContext #import global_enum @pytest.fixture(scope="class") def csp_master(): """Create DeviceProxy for the CspMaster device to test the device with the TANGO DB """ database = tango.Database() instance_list = database.get_device_exported_for_class('CspMaster') for instance in instance_list.value_string: try: return tango.DeviceProxy(instance) except tango.DevFailed: continue @pytest.fixture(scope="class") def csp_subarray01(): """Create DeviceProxy for the CspSubarray 01 device to test the device with the TANGO DB """ database = tango.Database() instance_list = database.get_device_exported_for_class('CspSubarray') for instance in instance_list.value_string: try: if "subarray_01" in instance: return tango.DeviceProxy(instance) except tango.DevFailed: continue @pytest.fixture(scope="class") def csp_subarray02(): """Create DeviceProxy for the CspSubarray 02 device to test the device with the TANGO DB """ database = tango.Database() instance_list = database.get_device_exported_for_class('CspSubarray') for instance in instance_list.value_string: try: if "subarray_02" in instance: return tango.DeviceProxy(instance) except tango.DevFailed: continue @pytest.fixture(scope="class") def cbf_subarray01(): """Create DeviceProxy for the CbfSubarray 01 device to test the device with the TANGO DB """ database = tango.Database() instance_list = database.get_device_exported_for_class('CbfSubarray') for instance in instance_list.value_string: try: if "subarray_01" in instance: return tango.DeviceProxy(instance) except tango.DevFailed: continue @pytest.fixture(scope="class") def cbf_master(): """Create DeviceProxy for the CspMaster device to test the device with the TANGO DB """ database = tango.Database() instance_list = database.get_device_exported_for_class('CbfMaster') for instance in instance_list.value_string: try: return tango.DeviceProxy(instance) except tango.DevFailed: continue @pytest.fixture(scope="class") def tm_leafnode1(): """Create DeviceProxy for the CspMaster device to test the device with the TANGO DB """ tmleaf_proxy = DeviceProxy("ska_mid/tm_leaf_node/csp_subarray_01") return tmleaf_proxy <file_sep>/csplmc/CbfTestMaster/README.md This device is no more supported. It was implemented at the beginning of the project to test the basic CSP.LMC functionalities. The mid-csp-mcs project provides the Mid-CBF TANGO Devices that are now currently used by the CSP.LMC prototype. <file_sep>/csplmc/CspMaster/docs/src/index.rst CspMaster ************************ .. automodule:: CspMaster .. autoclass:: CspMaster :members: <file_sep>/docs/src/global_enum.rst CspMaster Class Documentation ================================ .. automodule:: global_enum :members: :undoc-members: :member-order: <file_sep>/start_prototype.sh #!/bin/bash # # Script to start CSP.LMC prototype TANGO devices. # The script: # - checks if the TANGO DB is running # - if the devices are already registered with the TANGO DB, otherwise it adds # them using the tango_admin command # - start the devices # - check if the jive tool is installed in the system # - starts jive if it's not already running # FILE=jive #check if TANGO DB is up tango_admin --ping-database if [ $? -eq 0 ]; then # configure device properties sleep 2 echo "Configuring Class/Device properties" python csplmc/configureDevices.py sleep 2 # TANGO DB is running -> check for CspMaster device existence tango_admin --check-device mid_csp/elt/master if [ $? -eq 0 ]; then echo "CspMaster device already register in the TANGO DB" else echo "Adding the CspMaster device to DB" tango_admin --add-server CspMaster/csp CspMaster mid_csp/elt/master fi echo "Starting the CspMaster device" # redirect standard error and standard output to a temporary file and on /dev/null python csplmc/CspMaster/CspMaster/CspMaster.py csp > tmp.txt 2>&1 >/dev/null & sleep 3 echo "$(<tmp.txt)" rm tmp.txt # check for CspSubarray1 device existence tango_admin --check-device mid_csp/elt/subarray_01 if [ $? -eq 0 ]; then echo "CspSubarray1 device already register in the TANGO DB" else echo "Adding the CspSubarray1 device to DB" tango_admin --add-server CspSubarray/sub1 CspSubarray mid_csp/elt/subarray_01 fi echo "Starting the CspSubarray1 device" # redirect standard error and standard output to a temporary file and on /dev/null python csplmc/CspSubarray/CspSubarray/CspSubarray.py sub1 > tmp.txt 2>&1 >/dev/null & sleep 3 echo "$(< tmp.txt)" rm tmp.txt # check for jive tool command_line="which $FILE" return=`$command_line` echo $return if [ $? -gt 0 ]; then echo "Jive tool not found" # jive tool found. Go to run it else # check if jive is already running jive=$(pgrep -a $FILE| awk '{print $3}') len=${#jive} if [ $len -eq 0 ]; then #no jive running, start it echo "Starting jive..." $return & fi fi else echo "TANGO DB not running" fi <file_sep>/csplmc/CspSubarray/setup.py #!/usr/bin/env python # -*- coding: utf-8 -*- # # This file is part of the CentralNode project # # # # Distributed under the terms of the BSD-3-Clause license. # See LICENSE.txt for more info. import os import sys from setuptools import setup setup_dir = os.path.dirname(os.path.abspath(__file__)) # make sure we use latest info from local code sys.path.insert(0, setup_dir) INFO = {} readme_filename = os.path.join(setup_dir, 'README.rst') with open(readme_filename) as file: long_description = file.read() release_filename = os.path.join(setup_dir, '..', 'release.py') exec(open(release_filename).read(), INFO) pack = ['CspSubarray'] setup( name=INFO['name'], version=INFO['version'], description='CspSubarray.', packages=pack, include_package_data=True, test_suite="test", entry_points={'console_scripts':['CspSubarray = CspSubarray:main']}, author='E.G', author_email='<EMAIL>', license='BSD-3-Clause', long_description=long_description, url='www.tango-controls.org', platforms="All Platforms", install_requires=['pytango==9.3.1', 'mock'], #test_suite='test', setup_requires=[ # dependency for `python setup.py test` 'pytest-runner', # dependencies for `python setup.py build_sphinx` 'sphinx', 'recommonmark' ], tests_require=[ 'pytest', 'pytest-cov', 'pytest-json-report', 'pycodestyle', ], extras_require={ 'dev': ['prospector[with_pyroma]', 'yapf', 'isort'] } ) <file_sep>/csplmc/CspTelState/CspTelState/CspTelState.py # -*- coding: utf-8 -*- # # This file is part of the CspTelState project # # # # Distributed under the terms of the GPL license. # See LICENSE.txt for more info. """ The CspTelState device expose CSP parameters used by other Elements, also used for information exchange between CSP Sub-elements. """ # PROTECTED REGION ID (CspMaster.standardlibray_import) ENABLED START # # Python standard library from __future__ import absolute_import import sys import os from future.utils import with_metaclass # PROTECTED REGION END# //CspMaster.standardlibray_import # tango imports import tango from tango import DebugIt, DeviceProxy, EventType from tango.server import run, Device, DeviceMeta, attribute, command, device_property # PROTECTED REGION ID(CspTelState.additional_import) ENABLED START # # add the path to import global_enum package. file_path = os.path.dirname(os.path.abspath(__file__)) commons_pkg_path = os.path.abspath(os.path.join(file_path, "../../commons")) sys.path.insert(0, commons_pkg_path) # Additional import import global_enum as const from global_enum import HealthState, AdminMode from skabase.SKATelState import SKATelState # PROTECTED REGION END # // CspTelState.additionnal_import __all__ = ["CspTelState", "main"] class CspTelState(with_metaclass(DeviceMeta, SKATelState)): """ The CspTelState device expose CSP parameters used by other Elements, also used for information exchange between CSP Sub-elements. """ __metaclass__ = DeviceMeta # PROTECTED REGION ID(CspTelState.class_variable) ENABLED START # #Class private methods def csp_subarray_change_callback(self, evt): """ *Class private method.* Retrieve the values of the sub-element sub-arrays SCM attributes subscribed for change event at device initialization. Args: evt: The event data Returns: None """ if evt.err is False: try: print("err:", evt.err) print(evt.attr_name) if "cbfoutputlink" in evt.attr_name: attr_name = evt.attr_name # get the number of the subarray pos = attr_name.find("subarray_") # pos+9 is the starting position of the subarray Id subarray_id = int(attr_name[pos + 9:pos + 11]) # store the new output link value self._cbf_output_links[subarray_id - 1] = evt.attr_value.value print(self._cbf_output_links[subarray_id - 1]) # get the subarray ID value to build the name of the CspTelState outputlink # attribute. This has the form "cbfOutputLinkN" where N is the subarray ID attr_name = "cbfOutputLinks" + str(subarray_id) # publish the outputlink self.push_change_event(attr_name, self._cbf_output_links[subarray_id - 1]) else: self.dev_logging("Attribute {} not yet handled".format(evt.attr_name), tango.LogLevel.LOG_ERROR) except tango.DevFailed as df: #self.dev_logging(str(df.args[0].desc), tango.LogLevel.LOG_ERROR) print(df) else: for item in evt.errors: # TODO handle API_EventTimeout # log_msg = item.reason + ": on attribute " + str(evt.attr_name) print(log_msg) #self.dev_logging(log_msg, tango.LogLevel.LOG_WARN) def __connect_to_master(self): """ *Class private method.* Establish connection with the CSP Element Master devices to get information about the CSP Subarray devices FQDNs. Returns: None Raises: DevFailed: when connection to the CspMaster device fails. """ try: self.dev_logging("Trying connection to {}".format(self.CspMaster), int(tango.LogLevel.LOG_INFO)) self._csp_master_proxy = tango.DeviceProxy(self.CspMaster) self._csp_master_proxy.ping() # get the list of CSP Subarray FQDNs self._csp_subarrays_fqdn = list(self._csp_master_proxy.cspSubarrayAddress) print(self._csp_subarrays_fqdn) except tango.DevFailed as df: tango.Except.throw_exception("Connection Failed", df.args[0].desc, "connect_to_master ", tango.ErrSeverity.ERR) def __connect_to_subarrays(self): """ *Class private method.* Establish connection with each CSP sub-array. If connection succeeds, the CspTelState device subscribes attributes it has to publish for that subarray Returns: None Raises: tango.DevFailed: raises an execption if connection with a CSP Subarray fails """ err_msg = '' for fqdn in self._csp_subarrays_fqdn: # initialize the list for each dictionary key-name self._csp_subarray_event_id[fqdn] = [] try: log_msg = "Trying connection to" + str(fqdn) + " device" self.dev_logging(log_msg, int(tango.LogLevel.LOG_INFO)) device_proxy = tango.DeviceProxy(fqdn) device_proxy.ping() # add to the list of subarray FQDNS only registered subarrays self._csp_subarrays_fqdn.append(fqdn) # store the sub-element proxies self._csp_subarray_proxies[fqdn] = device_proxy # Subscription of the sub-element State,healthState and adminMode ev_id = device_proxy.subscribe_event("cbfOutputLink", EventType.CHANGE_EVENT, self.csp_subarray_change_callback, stateless=True) self._csp_subarray_event_id[fqdn].append(ev_id) except tango.DevFailed as df: for item in df.args: err_msg += "Failure in connection to " + str(fqdn) + \ " device: " + str(item.reason) + " " if not err_msg == False: self.dev_logging(err_msg, int(tango.LogLevel.LOG_ERROR)) tango.Except.throw_exception("Connection failed", err_msg, "Connect to subarrays", tango.ErrSeverity.ERR) # PROTECTED REGION END # // CspTelState.class_variable # ----------------- # Device Properties # ----------------- CspMaster = device_property( dtype='str', default_value="mid_csp/elt/master" ) # ---------- # Attributes # ---------- cbfOutputLinks1 = attribute( dtype='str', label="Cbf Subarray-01 output links", doc="The output links distribution for Cbf Subarray-01.", ) cbfOutputLinks2 = attribute( dtype='str', label="Cbf Subarray-02 output links", doc="The output links distribution for Cbf Subarray-02.", ) cbfOutputLinks3 = attribute( dtype='str', label="Cbf Subarray-03 output links", doc="The output links distribution for Cbf Subarray-03.", ) cbfOutputLinks4 = attribute( dtype='str', label="Cbf Subarray-04 output links", doc="The output links distribution for Cbf Subarray-04.", ) cbfOutputLinks5 = attribute( dtype='str', label="Cbf Subarray-05 output links", doc="The output links distribution for Cbf Subarray-05.", ) cbfOutputLinks6 = attribute( dtype='str', label="Cbf Subarray-06 output links", doc="The output links distribution for Cbf Subarray-06.", ) cbfOutputLinks7 = attribute( dtype='str', label="Cbf Subarray-07 output links", doc="The output links distribution for Cbf Subarray-07.", ) cbfOutputLinks8 = attribute( dtype='str', label="Cbf Subarray-08 output links", doc="The output links distribution for Cbf Subarray-08.", ) cbfOutputLinks9 = attribute( dtype='str', label="Cbf Subarray-09 output links", doc="The output links distribution for Cbf Subarray-09.", ) cbfOutputLinks10 = attribute( dtype='str', label="Cbf Subarray-10 output links", doc="The output links distribution for Cbf Subarray-10.", ) cbfOutputLinks11 = attribute( dtype='str', label="Cbf Subarray-11 output links", doc="The output links distribution for Cbf Subarray-11.", ) cbfOutputLinks12 = attribute( dtype='str', label="Cbf Subarray-12 output links", doc="The output links distribution for Cbf Subarray-12.", ) cbfOutputLinks13 = attribute( dtype='str', label="Cbf Subarray-13 output links", doc="The output links distribution for Cbf Subarray-13.", ) cbfOutputLinks14 = attribute( dtype='str', label="Cbf Subarray-14 output links", doc="The output links distribution for Cbf Subarray-14.", ) cbfOutputLinks15 = attribute( dtype='str', label="Cbf Subarray-15 output links", doc="The output links distribution for Cbf Subarray-15.", ) cbfOutputLinks16 = attribute( dtype='str', label="Cbf Subarray-16 output links", doc="The output links distribution for Cbf Subarray-16.", ) # --------------- # General methods # --------------- def init_device(self): SKATelState.init_device(self) # PROTECTED REGION ID(CspTelState.init_device) ENABLED START # # connect to CspMaster to get the list of CspSubarray FQDNs # initialize the private class attributes self._csp_master_proxy = 0 # CspMaster DeviceProxy self._csp_subarrays_fqdn = 0 # list of CspSubarray FQDNs # NOTE: the dict keys are the CspSubarrays FQDNs self._csp_subarray_event_id = {} # dict of the events subscribed for each CspSubarray self._csp_subarray_proxies = {} # dict of CspSubarrays DeviceProxy self._cbf_output_links = ['']*16 # list with Cbf outputlinks values try: self.__connect_to_master() self.__connect_to_subarrays() self.set_state(tango.DevState.ON) self._health_state = HealthState.OK.value except tango.DevFailed as df: print(df) msg = "Failure in connection:" + str(df.args[0].reason) self.dev_logging(msg, tango.LogLevel.LOG_ERROR) print(msg) self._health_state = HealthState.DEGRADED.value # PROTECTED REGION END # // CspTelState.init_device def always_executed_hook(self): # PROTECTED REGION ID(CspTelState.always_executed_hook) ENABLED START # pass # PROTECTED REGION END # // CspTelState.always_executed_hook def delete_device(self): # PROTECTED REGION ID(CspTelState.delete_device) ENABLED START # pass # PROTECTED REGION END # // CspTelState.delete_device # ------------------ # Attributes methods # ------------------ def read_cbfOutputLinks1(self): # PROTECTED REGION ID(CspTelState.cbfOutputLinks1_read) ENABLED START # print(self._cbf_output_links[0]) print(self._cbf_output_links[1]) print(self._cbf_output_links[2]) return self._cbf_output_links[0] # PROTECTED REGION END # // CspTelState.cbfOutputLinks1_read def read_cbfOutputLinks2(self): # PROTECTED REGION ID(CspTelState.cbfOutputLinks2_read) ENABLED START # return self._cbf_output_links[1] # PROTECTED REGION END # // CspTelState.cbfOutputLinks2_read def read_cbfOutputLinks3(self): # PROTECTED REGION ID(CspTelState.cbfOutputLinks3_read) ENABLED START # return self._cbf_output_links[2] # PROTECTED REGION END # // CspTelState.cbfOutputLinks3_read def read_cbfOutputLinks4(self): # PROTECTED REGION ID(CspTelState.cbfOutputLinks4_read) ENABLED START # return self._cbf_output_links[3] # PROTECTED REGION END # // CspTelState.cbfOutputLinks4_read def read_cbfOutputLinks5(self): # PROTECTED REGION ID(CspTelState.cbfOutputLinks5_read) ENABLED START # return self._cbf_output_links[4] # PROTECTED REGION END # // CspTelState.cbfOutputLinks5_read def read_cbfOutputLinks6(self): # PROTECTED REGION ID(CspTelState.cbfOutputLinks6_read) ENABLED START # return self._cbf_output_links[5] # PROTECTED REGION END # // CspTelState.cbfOutputLinks6_read def read_cbfOutputLinks7(self): # PROTECTED REGION ID(CspTelState.cbfOutputLinks7_read) ENABLED START # return self._cbf_output_links[6] # PROTECTED REGION END # // CspTelState.cbfOutputLinks7_read def read_cbfOutputLinks8(self): # PROTECTED REGION ID(CspTelState.cbfOutputLinks8_read) ENABLED START # return self._cbf_output_links[7] # PROTECTED REGION END # // CspTelState.cbfOutputLinks8_read def read_cbfOutputLinks9(self): # PROTECTED REGION ID(CspTelState.cbfOutputLinks9_read) ENABLED START # return self._cbf_output_links[8] # PROTECTED REGION END # // CspTelState.cbfOutputLinks9_read def read_cbfOutputLinks10(self): # PROTECTED REGION ID(CspTelState.cbfOutputLinks10_read) ENABLED START # return self._cbf_output_links[9] # PROTECTED REGION END # // CspTelState.cbfOutputLinks10_read def read_cbfOutputLinks11(self): # PROTECTED REGION ID(CspTelState.cbfOutputLinks11_read) ENABLED START # return self._cbf_output_links[10] # PROTECTED REGION END # // CspTelState.cbfOutputLinks11_read def read_cbfOutputLinks12(self): # PROTECTED REGION ID(CspTelState.cbfOutputLinks12_read) ENABLED START # return self._cbf_output_links[11] # PROTECTED REGION END # // CspTelState.cbfOutputLinks12_read def read_cbfOutputLinks13(self): # PROTECTED REGION ID(CspTelState.cbfOutputLinks13_read) ENABLED START # return self._cbf_output_links[12] # PROTECTED REGION END # // CspTelState.cbfOutputLinks13_read def read_cbfOutputLinks14(self): # PROTECTED REGION ID(CspTelState.cbfOutputLinks14_read) ENABLED START # return self._cbf_output_links[13] # PROTECTED REGION END # // CspTelState.cbfOutputLinks14_read def read_cbfOutputLinks15(self): # PROTECTED REGION ID(CspTelState.cbfOutputLinks15_read) ENABLED START # return self._cbf_output_links[14] # PROTECTED REGION END # // CspTelState.cbfOutputLinks15_read def read_cbfOutputLinks16(self): # PROTECTED REGION ID(CspTelState.cbfOutputLinks16_read) ENABLED START # return self._cbf_output_links[15] # PROTECTED REGION END # // CspTelState.cbfOutputLinks16_read # -------- # Commands # -------- # ---------- # Run server # ---------- def main(args=None, **kwargs): # PROTECTED REGION ID(CspTelState.main) ENABLED START # return run((CspTelState,), args=args, **kwargs) # PROTECTED REGION END # // CspTelState.main if __name__ == '__main__': main() <file_sep>/docs/src/package/guide.rst .. doctest-skip-all .. _package-guide: .. todo:: - Insert todo's here ************************** Package-name documentation ************************** This section describes requirements and guidelines. Subtitle ======== Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. <file_sep>/csplmc/CspMaster/test/CspMaster_test.py #!/usr/bin/env python # -*- coding: utf-8 -*- # # This file is part of the csp-lmc-prototype project # # # # Distributed under the terms of the BSD-3-Clause license. # See LICENSE.txt for more info. """Contain the tests for the CspMaster.""" # Standard imports import sys import os import time import numpy as np # Tango imports import tango from tango import DevState #from tango.test_context import DeviceTestContext import pytest # Path file_path = os.path.dirname(os.path.abspath(__file__)) # insert base package directory to import global_enum # module in commons folder commons_pkg_path = os.path.abspath(os.path.join(file_path, "../../commons")) sys.path.insert(0, commons_pkg_path) path = os.path.join(os.path.dirname(__file__), os.pardir) sys.path.insert(0, os.path.abspath(path)) #Local imports from CspMaster import CspMaster #from global_enum import HealthState, AdminMode from global_enum import AdminMode # Device test case @pytest.mark.usefixtures("cbf_master", "csp_master", "cbf_subarray01", "csp_subarray01") class TestCspMaster(object): def test_State(self, csp_master, cbf_master): """Test for State after initialization """ # reinitalize Csp Master and CbfMaster devices cbf_master.Init() time.sleep(2) csp_master.Init() time.sleep(2) csp_state = csp_master.state() assert csp_state in [DevState.STANDBY, DevState.INIT, DevState.DISABLE] def test_adminMode(self, csp_master): """ Test the adminMode attribute w/r""" csp_master.adminMode = AdminMode.OFFLINE time.sleep(3) assert csp_master.adminMode.value == AdminMode.OFFLINE def test_cbfAdminMode(self, csp_master): """ Test the CBF adminMode attribute w/r""" csp_master.cbfAdminMode = AdminMode.ONLINE time.sleep(3) assert csp_master.cbfAdminMode.value == AdminMode.ONLINE def test_pssAdminMode(self, csp_master): """ Test the PSS adminMode attribute w/r""" try: csp_master.pssAdminMode = AdminMode.ONLINE assert csp_master.pssAdminMode.value == AdminMode.ONLINE except tango.DevFailed as df: assert "No proxy for device" in df.args[0].desc def test_pstAdminMode(self, csp_master): """ Test the PST adminMode attribute w/r""" try: csp_master.pstAdminMode = AdminMode.ONLINE assert csp_master.pstAdminMode.value == AdminMode.ONLINE except tango.DevFailed as df: assert "No proxy for device" in df.args[0].desc def test_subelement_address(self, csp_master): """Test for report state of SearchBeam Capabilitities""" cbf_addr = csp_master.cbfMasterAddress cbf_addr_property = csp_master.get_property("CspMidCbf")["CspMidCbf"][0] assert cbf_addr == cbf_addr_property pss_addr = csp_master.pssMasterAddress pss_addr_property = csp_master.get_property("CspMidPss")["CspMidPss"][0] assert pss_addr == pss_addr_property pst_addr = csp_master.pstMasterAddress pst_addr_property = csp_master.get_property("CspMidPst")["CspMidPst"][0] assert pst_addr == pst_addr_property def test_properties(self, csp_master): """ Test the device property MaxCapability""" capability_list = ['SearchBeam:1500', 'TimingBeam:16', 'VlbiBeam:20', 'Subarray:16'] capability_list.sort() #Oss: maxCapability returns a tuple assert csp_master.maxCapabilities == tuple(capability_list) def test_forwarded_attributes(self, csp_master, cbf_master): """ Test the reportVCCState forwarded attribute""" vcc_state = csp_master.reportVCCState vcc_state_cbf = cbf_master.reportVCCState assert np.array_equal(vcc_state, vcc_state_cbf) def test_search_beams_states_at_init(self, csp_master): """ Test for the SearchBeam Capabilities State after initialization """ num_of_search_beam = 0 max_capabilities = csp_master.maxCapabilities for max_capability in max_capabilities: capability_type, max_capability_instances = max_capability.split(":") if capability_type == 'SearchBeam': num_of_search_beam = int(max_capability_instances) break search_beam_state = csp_master.reportSearchBeamState assert num_of_search_beam == len(search_beam_state) expected_search_beam = [tango.DevState.UNKNOWN for i in range(num_of_search_beam)] assert np.array_equal(expected_search_beam, search_beam_state) def test_timing_beams_states_at_init(self, csp_master): """ Test for the TimingBeam Capabilities State after initialization """ num_of_beam = 0 max_capabilities = csp_master.maxCapabilities for max_capability in max_capabilities: capability_type, max_capability_instances = max_capability.split(":") if capability_type == 'TimingBeam': num_of_beam = int(max_capability_instances) break timing_beam_state = csp_master.reportTimingBeamState assert num_of_beam == len(timing_beam_state) expected_search_beam = [tango.DevState.UNKNOWN for i in range(num_of_beam)] assert np.array_equal(expected_search_beam, timing_beam_state) def test_vlbi_beams_states_at_init(self, csp_master): """ Test for the VlbiBeam Capabilities State after initialization """ num_of_beam = 0 max_capabilities = csp_master.maxCapabilities for max_capability in max_capabilities: capability_type, max_capability_instances = max_capability.split(":") if capability_type == 'VlbiBeam': num_of_beam = int(max_capability_instances) break vlbi_beam_state = csp_master.reportVlbiBeamState assert num_of_beam == len(vlbi_beam_state) expected_search_beam = [tango.DevState.UNKNOWN for i in range(num_of_beam)] assert np.array_equal(expected_search_beam, vlbi_beam_state) def test_receptors_available_ids(self, csp_master): """ Test the reading of availableReceptorIDs attribute """ max_capabilities = csp_master.availableCapabilities num_of_receptors = 0 list_of_receptors = csp_master.availableReceptorIDs for max_capability in max_capabilities: capability_type, max_capability_instances = max_capability.split(":") if capability_type == 'Receptors': num_of_receptors = int(max_capability_instances) break if num_of_receptors > 0: assert list_of_receptors else: assert np.array_equal(list_of_receptors, [0]) def test_available_capabilities(self, csp_master): """ Test the reading of availableCapabilities attribute """ available_cap = csp_master.availableCapabilities assert available_cap def test_On_invalid_argument(self, csp_master): """Test for the execution of the On command with a wrong input argument""" # NOTE: here adminMode is OFFLINE for the previous test. To # execute command on the device It has to be set to ONLINE csp_master.adminMode = AdminMode.ONLINE time.sleep(3) assert csp_master.adminMode.value == AdminMode.ONLINE with pytest.raises(tango.DevFailed) as df: argin = ["cbf", ] csp_master.On(argin) assert "No proxy found for device" in str(df.value) def test_On_valid_state(self, csp_master, cbf_master): """ Test for execution of On command when the CbfMaster is in the right state """ #reinit CSP and CBF master devices cbf_master.Init() time.sleep(2) # sleep for a while to wait state transition # check CspMaster state csp_master.Init() assert csp_master.State() == DevState.STANDBY # issue the "On" command on CbfMaster device argin = ["mid_csp_cbf/sub_elt/master",] csp_master.On(argin) time.sleep(3) assert csp_master.state() == DevState.ON def test_On_invalid_state(self, csp_master, cbf_master): """ Test for the execution of the On command when the CbfMaster is in an invalid state """ #reinit CSP and CBF master devices cbf_master.Init() csp_master.Init() # sleep for a while to wait for state transitions time.sleep(3) assert csp_master.cspCbfState == DevState.STANDBY # issue the command to switch off the CbfMaster #argin=["",] argin = ["mid_csp_cbf/sub_elt/master",] csp_master.Off(argin) # wait for the state transition from STANDBY to OFF time.sleep(3) assert csp_master.cspCbfState == DevState.OFF # issue the command to switch on the CbfMaster device with pytest.raises(tango.DevFailed) as df: argin = ["mid_csp_cbf/sub_elt/master", ] csp_master.On(argin) assert "Command On not allowed" in str(df.value.args[0].desc) def test_Standby_invalid_argument(self, csp_master, cbf_master): """Test for the execution of the Standby command with a wrong input argument""" #reinit CSP and CBF master devices cbf_master.Init() #csp_master.Init() # sleep for a while to wait for state transitions time.sleep(3) csp_master.On("") time.sleep(3) with pytest.raises(tango.DevFailed) as df: argin = ["cbf", ] csp_master.Standby(argin) assert "No proxy found for device" in str(df.value) def test_Standby_valid_state(self, csp_master): """ Test for execution of On command when the CbfTestMaster is in the right state """ assert csp_master.State() == DevState.ON # issue the "Standby" command on CbfMaster device argin = ["mid_csp_cbf/sub_elt/master",] csp_master.Standby(argin) time.sleep(3) assert csp_master.state() == DevState.STANDBY def test_Off_invalid_argument(self, csp_master): """Test for the execution of the Off command with a wrong input argument""" csp_state = csp_master.State() argin = ["cbf", ] csp_master.Off(argin) #at present time the code does not raise any exception assert csp_state == csp_master.State() def test_Off_invalid_state(self, csp_master, cbf_master): """ Test for the execution of the Off command when the CbfMaster is in an invalid state """ cbf_master.Init() # csp_master.Init() # sleep for a while to wait for state transitions time.sleep(3) assert csp_master.State() == DevState.STANDBY csp_master.On("") time.sleep(3) assert csp_master.State() == DevState.ON # issue the command to switch off the CSP with pytest.raises(tango.DevFailed) as df: csp_master.Off("") assert "Command Off not allowed" in str(df.value.args[0].desc) def test_Off_valid_state(self, csp_master, cbf_master): """ Test for execution of On command when the CbfMaster is in the right state """ #reinit CSP and CBFTest master devices cbf_master.Init() #csp_master.Init() time.sleep(2) assert csp_master.State() == DevState.STANDBY # issue the "Off" command on CbfMaster device csp_master.Off("") time.sleep(3) assert csp_master.state() == DevState.OFF def test_reinit_csp_master(self, csp_master, cbf_master): """ Test CspMaster reinitialization """ #reinit CSP and CBFTest master devices cbf_master.Init() time.sleep(2) csp_master.Init() time.sleep(2) assert csp_master.State() == DevState.STANDBY <file_sep>/csplmc/CspMaster/CspMaster/CspMaster.py # -*- coding: utf-8 -*- # # This file is part of the CspMaster project # # # # Distributed under the terms of the GPL license. # See LICENSE.txt for more info. """ CspMaster Tango device prototype CSPMaster TANGO device class for the CSPMaster prototype """ # PROTECTED REGION ID (CspMaster.standardlibray_import) ENABLED START # # Python standard library from __future__ import absolute_import import sys import os from future.utils import with_metaclass from collections import defaultdict # PROTECTED REGION END# //CspMaster.standardlibray_import # tango imports import tango from tango import DebugIt, EventType, DeviceProxy, AttrWriteType from tango.server import run, DeviceMeta, attribute, command, device_property # Additional import # PROTECTED REGION ID(CspMaster.additionnal_import) ENABLED START # # from skabase.SKAMaster import SKAMaster from skabase.auxiliary import utils # PROTECTED REGION END # // CspMaster.additionnal_import # PROTECTED REGION ID (CspMaster.add_path) ENABLED START # # add the path to import global_enum package. file_path = os.path.dirname(os.path.abspath(__file__)) commons_pkg_path = os.path.abspath(os.path.join(file_path, "../../commons")) sys.path.insert(0, commons_pkg_path) import global_enum as const from global_enum import HealthState, AdminMode #add the path to import release file (!!) csplmc_path = os.path.abspath(os.path.join(file_path, "../../")) sys.path.insert(0, csplmc_path) import release # PROTECTED REGION END# //CspMaster.add_path __all__ = ["CspMaster", "main"] class CspMaster(with_metaclass(DeviceMeta, SKAMaster)): """ CSPMaster TANGO device class for the CSPMaster prototype """ # PROTECTED REGION ID(CspMaster.class_variable) ENABLED START # # --------------- # Event Callback functions # --------------- def __seSCMCallback(self, evt): """ Class private method. Retrieve the values of the sub-element SCM attributes subscribed for change event at device initialization. :param evt: The event data :return: None """ if not evt.err: dev_name = evt.device.dev_name() try: if dev_name in self._se_fqdn: if evt.attr_value.name.lower() == "state": self._se_state[dev_name] = evt.attr_value.value elif evt.attr_value.name.lower() == "healthstate": self._se_healthstate[dev_name] = evt.attr_value.value elif evt.attr_value.name.lower() == "adminmode": self._se_adminmode[dev_name] = evt.attr_value.value else: log_msg = ("Attribute {} not still " "handled".format(evt.attr_name)) self.dev_logging(log_msg, tango.LogLevel.LOG_WARN) else: log_msg = ("Unexpected change event for" " attribute: {}".format(str(evt.attr_name))) self.dev_logging(log_msg, tango.LogLevel.LOG_WARN) return log_msg = "New value for {} is {}".format(str(evt.attr_name), str(evt.attr_value.value)) self.dev_logging(log_msg, tango.LogLevel.LOG_INFO) # update CSP global state if evt.attr_value.name.lower() in ["state", "healthstate"]: self.__set_csp_state() except tango.DevFailed as df: self.dev_logging(str(df.args[0].desc), tango.LogLevel.LOG_ERROR) except Exception as except_occurred: self.dev_logging(str(except_occurred), tango.LogLevel.LOG_ERROR) else: for item in evt.errors: # API_EventTimeout: if sub-element device not reachable it transitions # to UNKNOWN state. if item.reason == "API_EventTimeout": if evt.attr_name.find(dev_name) > 0: self._se_state[dev_name] = tango.DevState.UNKNOWN self._se_healthstate[dev_name] = HealthState.UNKNOWN if self._se_to_switch_off[dev_name]: self._se_state[dev_name] = tango.DevState.OFF # update the State and healthState of the CSP Element self.__set_csp_state() log_msg = item.reason + ": on attribute " + str(evt.attr_name) self.dev_logging(log_msg, tango.LogLevel.LOG_WARN) # --------------- # Class private methods # --------------- def __set_csp_state(self): """ Class private method. Retrieve the State attribute of the CSP sub-elements and aggregate them to build up the CSP global state. :param: None :return: None """ self.__set_csp_health_state() # CSP state reflects the status of CBF. Only if CBF is present # CSP can work. The state of PSS and PST sub-elements only contributes # to determine the CSP health state. self.set_state(self._se_state[self.CspMidCbf]) def __set_csp_health_state(self): """ Class private method. Retrieve the healthState attribute of the CSP sub-elements and aggregate them to build up the CSP health state :param: None :return: None """ # The whole CSP HealthState is OK only if: # - all sub-elements are available # - each sub-element HealthState is OK if (len(self._se_healthstate.values()) == 3 and \ list(self._se_healthstate.values()) == [HealthState.OK, HealthState.OK, HealthState.OK ]): self._se_healthstate = HealthState.OK # in all other case the HealthState depends on the CBF # sub-element HealthState if self._se_healthstate[self.CspMidCbf] == HealthState.UNKNOWN: self._health_state = HealthState.UNKNOWN elif self._se_healthstate[self.CspMidCbf] == HealthState.FAILED: self._health_state = HealthState.FAILED else: self._health_state = HealthState.DEGRADED def __get_maxnum_of_beams_capabilities(self): """ Class private method. Retrieve the max number of CSP Capabilities for each capability type.\n The couple [CapabilityType: num] is specified as TANGO Device Property. Default values for Mid CSP are:\n - Subarray 16 \n - SearchBeam 1500 \n - TimingBeam 16 \n - VlbiBeam 20 \n :param: None :return: None """ self._search_beams_maxnum = const.NUM_OF_SEARCH_BEAMS self._timing_beams_maxnum = const.NUM_OF_TIMING_BEAMS self._vlbi_beams_maxnum = const.NUM_OF_VLBI_BEAMS self._subarrays_maxnum = const.NUM_OF_SUBARRAYS self._available_search_beams_num = const.NUM_OF_SEARCH_BEAMS self._available_timing_beams_num = const.NUM_OF_TIMING_BEAMS self._available_vlbi_beams_num = const.NUM_OF_VLBI_BEAMS self._available_subarrays_num = const.NUM_OF_SUBARRAYS if self._max_capabilities: try: self._search_beams_maxnum = self._max_capabilities["SearchBeam"] except KeyError: # not found in DB self._search_beams_maxnum = const.NUM_OF_SEARCH_BEAMS try: self._timing_beams_maxnum = self._max_capabilities["TimingBeam"] except KeyError: # not found in DB self._timing_beams_maxnum = const.NUM_OF_TIMING_BEAMS try: self._vlbi_beams_maxnum = self._max_capabilities["VlbiBeam"] except KeyError: # not found in DB self._vlbi_beams_maxnum = const.NUM_OF_VLBI_BEAMS try: self._subarrays_maxnum = self._max_capabilities["Subarray"] except KeyError: # not found in DB self._subarrays_maxnum = const.NUM_OF_SUBARRAYS else: self.dev_logging(("MaxCapabilities device property not defined." "Use defaul values"), tango.LogLevel.LOG_WARN) def __get_maxnum_of_receptors(self): """ Get the maximum number of receptors that can be used for observations. This number can be less than 197. """ self._receptors_maxnum = const.NUM_OF_RECEPTORS capability_dict = {} try: proxy = self._se_proxies[self.CspMidCbf] proxy.ping() vcc_to_receptor = proxy.vccToReceptor self._vcc_to_receptor_map = dict([int(ID) for ID in pair.split(":")] for pair in vcc_to_receptor) # get the number of each Capability type allocated by CBF cbf_max_capabilities = proxy.maxCapabilities for capability in cbf_max_capabilities: cap_type, cap_num = capability.split(':') capability_dict[cap_type] = int(cap_num) self._receptors_maxnum = capability_dict["VCC"] self._receptorsMembership = [0]* self._receptors_maxnum except KeyError as key_err: log_msg = "Error: no key found for {}".format(str(key_err)) self.dev_logging(log_msg, int(tango.LogLevel.LOG_ERROR)) except AttributeError as attr_err: log_msg = "Error reading{}: {}".format(str(attr_err.args[0]), attr_err.__doc__) self.dev_logging(log_msg, int(tango.LogLevel.LOG_ERROR)) except tango.DevFailed as df: log_msg = "Error: " + str(df.args[0].reason) self.dev_logging(log_msg, int(tango.LogLevel.LOG_ERROR)) def __init_beams_capabilities(self): """ Class private method. Initialize the CSP capabilities State and Modes attributes. """ # get the max number of CSP Capabilities for each Csp capability type self.__get_maxnum_of_beams_capabilities() # set init values for SCM states of each beam capability type self._search_beams_state = [tango.DevState.UNKNOWN for i in range(self._search_beams_maxnum)] self._timing_beams_state = [tango.DevState.UNKNOWN for i in range(self._timing_beams_maxnum) ] self._vlbi_beams_state = [tango.DevState.UNKNOWN for i in range(self._vlbi_beams_maxnum) ] self._search_beams_health_state = [HealthState.UNKNOWN for i in range(self._search_beams_maxnum) ] self._timing_beams_health_state = [HealthState.UNKNOWN for i in range(self._timing_beams_maxnum) ] self._vlbi_beams_health_state = [HealthState.UNKNOWN for i in range(self._vlbi_beams_maxnum) ] self._search_beams_admin = [AdminMode.ONLINE for i in range(self._search_beams_maxnum) ] self._timing_beams_admin = [AdminMode.ONLINE for i in range(self._timing_beams_maxnum) ] self._vlbi_beams_admin = [AdminMode.ONLINE for i in range(self._vlbi_beams_maxnum) ] def __connect_to_subelements(self): """ Class private method. Establish connection with each CSP sub-element. If connection succeeds, the CspMaster device subscribes the State, healthState and adminMode attributes of each CSP Sub-element and registers a callback function to handle the events (see __seSCMCallback()). Exceptions are logged. Returns: None """ for fqdn in self._se_fqdn: # initialize the list for each dictionary key-name self._se_event_id[fqdn] = [] try: self._se_to_switch_off[fqdn] = False log_msg = "Trying connection to" + str(fqdn) + " device" self.dev_logging(log_msg, int(tango.LogLevel.LOG_INFO)) device_proxy = DeviceProxy(fqdn) device_proxy.ping() # store the sub-element proxies self._se_proxies[fqdn] = device_proxy # Subscription of the sub-element State,healthState and adminMode ev_id = device_proxy.subscribe_event("State", EventType.CHANGE_EVENT, self.__seSCMCallback, stateless=True) self._se_event_id[fqdn].append(ev_id) ev_id = device_proxy.subscribe_event("healthState", EventType.CHANGE_EVENT, self.__seSCMCallback, stateless=True) self._se_event_id[fqdn].append(ev_id) ev_id = device_proxy.subscribe_event("adminMode", EventType.CHANGE_EVENT, self.__seSCMCallback, stateless=True) self._se_event_id[fqdn].append(ev_id) except tango.DevFailed as df: #for item in df.args: log_msg = ("Failure in connection to {}" " device: {}".format(str(fqdn), str(df.args[0].desc))) self.dev_logging(log_msg, tango.LogLevel.LOG_ERROR) # NOTE: if the exception is thrown, the Device server fails # and exit. In this case we rely on K8s/Docker restart policy # to restart the Device Server. def __is_subelement_available(self, subelement_name): """ *Class private method.* Check if the sub-element is exported in the TANGO DB. If the device is not present in the list of the connected sub-elements, a connection with the device is performed. Args: subelement_name : the FQDN of the sub-element Returns: True if the connection with the subarray is established, False otherwise """ try: proxy = self._se_proxies[subelement_name] proxy.ping() except KeyError as key_err: # Raised when a mapping (dictionary) key is not found in the set # of existing keys. # no proxy registered for the subelement device msg = "Can't retrieve the information of key {}".format(key_err) self.dev_logging(msg, tango.LogLevel.LOG_ERROR) proxy = tango.DeviceProxy(subelement_name) proxy.ping() self._se_proxies[subelement_name] = proxy except tango.DevFailed as df: msg = "Failure reason: {} Desc: {}".format(str(df.args[0].reason), str(df.args[0].desc)) self.dev_logging(msg, tango.LogLevel.LOG_ERROR) return False return True def __create_search_beam_group(self): """ Class private method. Create a TANGO GROUP to get CSP SearchBeams Capabilities information """ return def __create_timing_beam_group(self): """ Class private method. Create a TANGO GROUP to get CSP TimingBeams Capabilities information """ return def __create_vlbi_beam_group(self): """ Class private method. Create a TANGO GROUP to get CSP Vlbi Beams Capabilities information """ return # PROTECTED REGION END # // CspMaster.class_variable # ----------------- # Device Properties # ----------------- CspMidCbf = device_property( dtype='str', default_value="mid_csp_cbf/sub_elt/master", doc="TANGO Device property.\n\n The Mid CBF sub-element address\n\n *type*: string", ) """ *Device property* The CspMidCbf FQDN. *Type*: DevString """ CspMidPss = device_property( dtype='str', default_value="mid_csp_pss/sub_elt/master", doc="TANGO Device property.\n\n The Mid Pss sub-element address\n\n *type*: string", ) """ *Device property* The CspMidPss FQDN. *Type*: DevString """ CspMidPst = device_property( dtype='str', default_value="mid_csp_pst/sub_elt/master", doc="TANGO Device property.\n\n The Mid Pst sub-element address\n\n *type*: string", ) """ *Device property* The CspMidPst FQDN. *Type*: DevString """ CspSubarrays = device_property( dtype=('str',), doc="TANGO Device property.\n\n The Mid Subarrays addresses\n\n *type*: array of string", ) """ *Device property* The CspSubarrays FQDN. *Type*: array of DevString """ SearchBeams = device_property( dtype=('str',), doc="TANGO Device property.\n\n The Mid SearchBeams Capabilities \ addresses\n\n *type*: array of string", ) """ *Device property* The CSP Search Beam Capabilities FQDNs. *Type*: array of DevString """ TimingBeams = device_property( dtype=('str',), doc="TANGO Device property.\n\n The Mid TiminingBeam Capabilities\ addresses\n\n *type*: array of string", ) """ *Device property* The CSP Timing Beam Capabilities FQDNs. *Type*: array DevString """ VlbiBeams = device_property( dtype=('str',), doc="TANGO Device property.\n\n The Mid VlbiBeam Capabilities \ addresses\n\n *type*: array of string", ) """ *Device property* The CSP Vlbi Beam Capabilities FQDNs. *Type*: array of DevString """ CspTelState = device_property( dtype='str', default_value="mid_csp/elt/telstate" ) """ *Device property* The CSP TelStatem FQDN. *Type*: DevString """ # ---------- # Attributes # ---------- # NB: To overide the write method of the adminMode attribute, we need to enable the # "overload attribute" check button in POGO. adminMode = attribute( dtype='DevEnum', access=AttrWriteType.READ_WRITE, memorized=True, doc="The admin mode reported for this device. It may interpret the current device \n\ condition of all managed devices to set this. Most possibly an aggregate attribute.", enum_labels=["ON-LINE", "OFF-LINE", "MAINTENANCE", "NOT-FITTED", "RESERVED", ], ) """ *Class attribute* The device admininistrative mode. Note: This attribute is defined in SKABaseDevice Class from which CspMaster class inherits.\ To override the attribute *write* method, the *adminMode* attribute is added again\ ("overload" button enabled in POGO). """ commandProgress = attribute( dtype='uint16', label="Command progress percentage", max_value=100, min_value=0, polling_period=3000, abs_change=5, rel_change=2, doc="Tango Device attribute.\n\nPercentage progress implemented for commands that\ result in state/mode \ transitions for a large number of components and/or are executed in \ stages (e.g power up, power down)\n\ntype: uint16", ) """ *Class attribute* Percentage progress implemented for commands that result in state/mode transitions for\ a large number of components and/or are executed in stages (e.g power up, power down)\n *Type*: DevUShort """ cspCbfState = attribute( dtype='DevState', label="CBF status", polling_period=3000, doc="The CBF sub-element State.", ) """ *Class attribute* The CbfMaster *State* attribute value.\n *Type*: DevState """ cspPssState = attribute( dtype='DevState', label="PSS status", polling_period=3000, doc="The PSS sub-element State.", ) """ *Class attribute* The PssMaster *State* attribute value.\n *Type*: DevState """ cspPstState = attribute( dtype='DevState', label="PST status", polling_period=3000, doc="The PST sub-element State", ) """ *Class attribute* The PstMaster *State* attribute value.\n *Type*: DevState """ cspCbfHealthState = attribute( dtype='DevEnum', label="CBF Health status", enum_labels=["OK", "DEGRADED", "FAILED", "UNKNOWN",], polling_period=3000, abs_change=1, doc="The CBF sub-element health status.", ) """ *Class attribute* The CbfMaster *healthState* attribute value.\n *Type*: DevUShort """ cspPssHealthState = attribute( dtype='DevEnum', label="PSS Health status", enum_labels=["OK", "DEGRADED", "FAILED", "UNKNOWN",], polling_period=3000, abs_change=1, doc="The PSS sub-element health status", ) """ *Class attribute* The PssMaster *healthState* attribute value.\n *Type*: DevUShort """ cspPstHealthState = attribute( dtype='DevEnum', label="PST health status", enum_labels=["OK", "DEGRADED", "FAILED", "UNKNOWN",], polling_period=3000, abs_change=1, doc="The PST sub-element health status.", ) """ *Class attribute* The PstMaster *healthState* attribute value.\n *Type*: DevUShort """ cbfMasterAddress = attribute( dtype='str', doc="The Mid CbfMaster TANGO device FQDN", ) """ *Class attribute* The CbfMaster FQDN.\n *Type*: DevString """ pssMasterAddress = attribute( dtype='str', doc="The Mid PssMaster TANGO device FQDN", ) """ *Class attribute* The PssMaster FQDN.\n *Type*: DevString """ pstMasterAddress = attribute( dtype='str', doc="The Mid PstMaster TANGO device FQDN", ) """ *Class attribute* The PstMaster FQDN.\n *Type*: DevString """ cbfAdminMode = attribute( dtype='DevEnum', access=AttrWriteType.READ_WRITE, label="CBF administrative Mode", polling_period=3000, abs_change=1, enum_labels=["ON-LINE", "OFF-LINE", "MAINTENANCE", "NOT-FITTED", "RESERVED", ], doc="The CbfMaster TANGO Device administration mode", ) """ *Class attribute* The CbfMaster *adminMode* attribute value.\n *Type*: DevUShort """ pssAdminMode = attribute( dtype='DevEnum', access=AttrWriteType.READ_WRITE, label="PSS administrative mode", polling_period=3000, abs_change=1, enum_labels=["ON-LINE", "OFF-LINE", "MAINTENANCE", "NOT-FITTED", "RESERVED", ], doc="The PssMaster TANGO Device administration mode", ) """ *Class attribute* The PssMaster *adminMode* attribute value.\n *Type*: DevUShort """ pstAdminMode = attribute( dtype='DevEnum', access=AttrWriteType.READ_WRITE, label="PST administrative mode", polling_period=3000, abs_change=1, enum_labels=["ON-LINE", "OFF-LINE", "MAINTENANCE", "NOT-FITTED", "RESERVED", ], doc="The PstMaster TANGO Device administration mode", ) """ *Class attribute* The PstMaster *adminMode* attribute value.\n *Type*: DevUShort """ availableCapabilities = attribute( dtype=('str',), max_dim_x=20, doc="A list of available number of instances of each capability \ type, e.g. `CORRELATOR:512`, `PSS-BEAMS:4`.", ) """ *Class attribute* The list of available instances of each capability type. Note: This attribute is defined in SKAMaster Class from which CspMaster class inherits.\ To override the attribute *read* method, the *availableCapabilities* attribute \ is added again\ ("overload" button enabled in POGO). """ reportSearchBeamState = attribute( dtype=('DevState',), max_dim_x=1500, label="Search Beams state", doc="The State value of CSP SearchBeam Capabilities. Reported as an array of DevState.", ) """ *Class attribute* The *State* attribute value of the CSP SearchBeam Capabilities.\n *Type*: array of DevState. """ reportSearchBeamHealthState = attribute( dtype=('uint16',), max_dim_x=1500, label="Search Beams health status", doc="The healthState of the CSP SearchBeam Capabilities. Reported as an array \ of ushort. For ex:\n[0,0,...,1..]", ) """ *Class attribute* The *healthState* attribute value of the CSP SearchBeam Capabilities.\n *Type*: array of DevUShort. """ reportSearchBeamAdminMode = attribute( dtype=('uint16',), max_dim_x=1500, label="Search beams admin mode", doc="Report the administration mode of the search beams as an array \ of unisgned short. Fo ex:\n[0,0,0,...2..]", ) """ *Class attribute* The *adminMode* attribute value of the CSP SearchBeam Capabilities.\n *Type*: array of DevUShort. """ reportTimingBeamState = attribute( dtype=('DevState',), max_dim_x=16, label="Timing Beams state", doc="Report the state of the timing beams as an array of DevState.", ) """ *Class attribute* The *State* attribute value of the CSP TimingBeam Capabilities.\n *Type*: array of DevState. """ reportTimingBeamHealthState = attribute( dtype=('uint16',), max_dim_x=16, label="Timing Beams health status", doc="*TANGO Attribute*: healhState of the TimingBeam Capabilities as an array \ of UShort.", ) """ *Class attribute* The *healthState* attribute value of the CSP TimingBeam Capabilities.\n *Type*: array of DevUShort. """ reportTimingBeamAdminMode = attribute( dtype=('uint16',), max_dim_x=16, label="Timing beams admin mode", doc="Report the administration mode of the timing beams as an array \ of unisgned short. For ex:\n[0,0,0,...2..]", ) """ *Class attribute* The *adminMode* attribute value of the CSP TimingBeam Capabilities.\n *Type*: array of DevUShort. """ reportVlbiBeamState = attribute( dtype=('DevState',), max_dim_x=20, label="VLBI Beams state", doc="Report the state of the VLBI beams as an array of DevState.", ) """ *Class attribute* The *State* attribute value of the CSP VlbiBeam Capabilities.\n *Type*: array of DevState. """ reportVlbiBeamHealthState = attribute( dtype=('uint16',), max_dim_x=20, label="VLBI Beams health status", doc="Report the health status of the VLBI beams as an array \ of unsigned short. For ex:\n[0,0,...,1..]", ) """ *Class attribute* The *healthState* attribute value of the CSP VlbiBeam Capabilities.\n *Type*: array of DevUShort. """ reportVlbiBeamAdminMode = attribute( dtype=('uint16',), max_dim_x=20, label="VLBI beams admin mode", doc="Report the administration mode of the VLBI beams as an array \ of unisgned short. For ex:\n[0,0,0,...2..]", ) """ *Class attribute* The *adminMode* attribute value of the CSP VlbiBeam Capabilities.\n *Type*: array of DevUShort. """ cspSubarrayAddress = attribute( dtype=('str',), max_dim_x=16, doc="CSPSubarrays FQDN", ) """ *Class attribute* The CSPSubarray FQDNs.\n *Type*: Array of DevString """ searchBeamCapAddress = attribute( dtype=('str',), max_dim_x=1500, label="SearchBeamCapabilities FQDNs", doc="SearchBeam Capabilities FQDNs", ) """ *Class attribute* The CSP SearchBeam Cpabailities FQDNs.\n *Type*: Array of DevString """ timingBeamCapAddress = attribute( dtype=('str',), max_dim_x=16, label="TimingBeam Caapbilities FQDN", doc="TimingBeam Capabilities FQDNs.", ) """ *Class attribute* The CSP TimingBeam Cpabailities FQDNs.\n *Type*: Array of DevString """ vlbiCapAddress = attribute( dtype=('str',), max_dim_x=20, label="VLBIBeam Capabilities FQDNs", doc="VLBIBeam Capablities FQDNs", ) """ *Class attribute* The CSP VlbiBeam Cpabailities FQDNs.\n *Type*: Array of DevString """ receptorMembership = attribute( dtype=('uint16',), max_dim_x=197, label="Receptor Memebership", doc="The receptors affiliation to CSPsub-arrays.", ) """ *Class attribute* The receptors subarray affiliation.\n *Type*: array of DevUShort. """ searchBeamMembership = attribute( dtype=('uint16',), max_dim_x=1500, label="SearchBeam Memebership", doc="The CSP sub-array affiliation of earch beams", ) """ *Class attribute* The SearchBeam Capabilities subarray affiliation.\n *Type*: array of DevUShort. """ timingBeamMembership = attribute( dtype=('uint16',), max_dim_x=16, label="TimingBeam Membership", doc="The CSPSubarray affiliation of timing beams.", ) """ *Class attribute* The TimingBeam Capabilities subarray affiliation.\n *Type*: array of DevUShort. """ vlbiBeamMembership = attribute( dtype=('uint16',), max_dim_x=20, label="VLBI Beam membership", doc="The CSPsub-rray affiliation of VLBI beams.", ) """ *Class attribute* The VlbiBeam Capabilities subarray affiliation.\n *Type*: array of DevUShort. """ availableReceptorIDs = attribute( dtype=('uint16',), max_dim_x=197, label="Available receptors IDs", doc="The list of available receptors IDs.", ) """ *Class attribute* The available receptor IDs.\n *Type*: array of DevUShort. """ # TODO: understand why device crashes if these forwarded attributes are declared #vccCapabilityAddress = attribute(name="vccCapabilityAddress", label="vccCapabilityAddress", # forwarded=True #) #fspCapabilityAddress = attribute(name="fspCapabilityAddress", label="fspCapabilityAddress", # forwarded=True #) reportVCCState = attribute(name="reportVCCState", label="reportVCCState", forwarded=True) """ *TANGO Forwarded attribute*. The *State* attribute value of the Mid CBF Very Coarse Channel TANGO Devices.\n *Type*: array of DevState. *__root_att*: /mid_csp_cbf/sub_elt/master/reportVCCState Note: If the *__root_att* attribute property is not specified in the \ TANGO DB or the value doesn't correspond to a valid attribute FQDN, the \ CspMaster *State* goes in ALARM. """ reportVCCHealthState = attribute(name="reportVCCHealthState", label="reportVCCHealthState", forwarded=True) """ *TANGO Forwarded attribute*. The *healthState* attribute value of the Mid CBF Very Coarse Channel TANGO Devices.\n *Type*: an array of DevUShort. *__root_att*: /mid_csp_cbf/sub_elt/master/reportVCCHealthState """ reportVCCAdminMode = attribute(name="reportVCCAdminMode", label="reportVCCAdminMode", forwarded=True) """ *TANGO Forwarded attribute*. The *adminMode* attribute value of the Mid CBF Very Coarse Channel TANGO devices.\n *Type*: array of DevUShort. *__root_att*: /mid_csp_cbf/sub_elt/master/reportVccAdminMode """ reportFSPState = attribute(name="reportFSPState", label="reportFSPState", forwarded=True) """ *TANGO Forwarded attribute*. The *State* attribute value of the Mid CBF Frequency Slice Processor TANGO devices.\n *Type*: array of DevState. *__root_att*: /mid_csp_cbf/sub_elt/master/reportFSPHealthState """ reportFSPHealthState = attribute(name="reportFSPHealthState", label="reportFSPHealthState", forwarded=True) """ *TANGO Forwarded attribute*. The *healthState* attribute value of the Mid CBF Frequency SLice Processor TANGO Devices.\n *Type*: an array of DevUShort. *__root_att*: /mid_csp_cbf/sub_elt/master/reportFSPHealthState """ reportFSPAdminMode = attribute(name="reportFSPAdminMode", label="reportFSPAdminMode", forwarded=True) """ *TANGO Forwarded attribute*. The *adminMode* attribute value of the Mid CBF Frequency SLice Processor TANGO Devices.\n *Type*: an array of DevUShort. *__root_att*: /mid_csp_cbf/sub_elt/master/reportFSPAdminMode """ fspMembership = attribute(name="fspMembership", label="fspMembership", forwarded=True) """ *TANGO Forwarded attribute*. The subarray affiliation of the Mid CBF Frequency SLice Processor TANGO Devices.\n *Type*: an array of DevUShort. *__root_att*: /mid_csp_cbf/sub_elt/master/fspMembership """ vccMembership = attribute(name="vccMembership", label="vccMembership", forwarded=True) """ *TANGO Forwarded attribute*. The subarray affiliation of the Mid CBF VCC TANGO Devices.\n *Type*: an array of DevUShort. *__root_att*: /mid_csp_cbf/sub_elt/master/reportVCCSubarrayMembership """ # --------------- # General methods # --------------- def init_device(self): SKAMaster.init_device(self) self._build_state = '{}, {}, {}'.format(release.name, release.version, release.description) self._version_id = release.version # PROTECTED REGION ID(CspMaster.init_device) ENABLED START # # set storage and element logging level self._storage_logging_level = int(tango.LogLevel.LOG_INFO) self._element_logging_level = int(tango.LogLevel.LOG_INFO) # set init values for the CSP Element and Sub-element SCM states self.set_state(tango.DevState.INIT) self._health_state = HealthState.UNKNOWN self._admin_mode = AdminMode.ONLINE # use defaultdict to initialize the sub-element State,healthState # and adminMode. The dictionary uses as keys the sub-element # fqdn, for example # self._se_state[self.CspMidCbf] # return the State value of the Mid Cbf sub-element. self._se_state = defaultdict(lambda: tango.DevState.UNKNOWN) self._se_healthstate = defaultdict(lambda: HealthState.UNKNOWN) self._se_adminmode = defaultdict(lambda: AdminMode.OFFLINE) # initialize attribute values self._available_receptorIDs = [] self._progress_command = 0 #initialize the SCM states for CSP Search/Timing/Vlbi beams Capabilities self.__init_beams_capabilities() #initialize Csp capabilities subarray membership self._searchBeamsMembership = [0] * self._search_beams_maxnum self._timingBeamsMembership = [0] * self._timing_beams_maxnum self._vlbiBeamsMembership = [0] * self._vlbi_beams_maxnum # initialize list with CSP sub-element FQDNs self._se_fqdn = [] #NOTE: # The normal behavior when a Device Property is created is: # - a self.Property attribute is created in the Dev_Impl object # - it takes a value from the Database if it has been defined. # - if not, it takes the default value assigned in Pogo. # - if no value is specified nowhere, the attribute is created # with [] value. self._se_fqdn.append(self.CspMidCbf) self._se_fqdn.append(self.CspMidPss) self._se_fqdn.append(self.CspMidPst) # flag to signal sub-element switch-off request self._se_to_switch_off = {} for device_name in self._se_fqdn: self._se_to_switch_off[device_name] = False # initialize the dictionary with sub-element proxies self._se_proxies = {} # dictionary with list of event ids/sub-element. Need to # store the event ids for each sub-element to un-subscribe # them at sub-element disconnection. self._se_event_id = {} # Try connection with sub-elements self.__connect_to_subelements() # initialize class attributes related to CBF receptors capabilities self._vcc_to_receptor_map = {} self._receptorsMembership = [] # NOTE: VCC (Receptors) and FSP capabilities are implemented at # CBF sub-element level. Need to evaluate if these capabilities # have to be implemented also at CSP level. # To retieve the information on the number of instances provided # by CBF the CSP master has to connect to the Cbf Master. For this # reason the __get_maxnum_of_receptors() method gas to be called # after connection. self.__get_maxnum_of_receptors() # TODO: # report FSP number/availability # for each FSP Master should report the resources for each # Processing Mode # self.__get_maxnum_of_fsp() # TODO : # Create TANGO Groups to handle SearchBeams, TimingBeams and VlbiBeams. # Master connects to the Beams Capabilities to retieve the information # about the SCM values of each capability self.__create_search_beam_group() self.__create_timing_beam_group() self.__create_vlbi_beam_group() # PROTECTED REGION END # // CspMaster.init_device def always_executed_hook(self): # PROTECTED REGION ID(CspMaster.always_executed_hook) ENABLED START # pass # PROTECTED REGION END # // CspMaster.always_executed_hook def delete_device(self): """ Method called on stop/reinit of the device. Release all the allocated resources. """ # PROTECTED REGION ID(CspMaster.delete_device) ENABLED START # for fqdn in self._se_fqdn: try: event_to_remove = [] for event_id in self._se_event_id[fqdn]: try: self._se_proxies[fqdn].unsubscribe_event(event_id) event_to_remove.append(event_id) # NOTE: in PyTango unsubscription of not-existing event # id raises a KeyError exception not a DevFailed !! except KeyError as key_err: msg = "Can't retrieve the information of key {}".format(key_err) self.dev_logging(msg, tango.LogLevel.LOG_ERROR) except tango.DevFailed as df: msg = ("Failure reason: {} Desc: {}".format(str(df.args[0].reason), str(df.args[0].desc))) self.dev_logging(msg, tango.LogLevel.LOG_ERROR) # remove the events id from the list for k in event_to_remove: self._se_event_id[fqdn].remove(k) # check if there are still some registered events. # What to do in this case?? if self._se_event_id[fqdn]: msg = "Still subscribed events: {}".format(self._se_event_id) self.dev_logging(msg, tango.LogLevel.LOG_WARN) else: # remove the dictionary element self._se_event_id.pop(fqdn) except KeyError as key_err: msg = " Can't retrieve the information of key {}".format(key_err) self.dev_logging(msg, tango.LogLevel.LOG_ERROR) # clear any list and dict self._se_fqdn.clear() self._se_proxies.clear() self._vcc_to_receptor_map.clear() self._receptorsMembership.clear() self._searchBeamsMembership.clear() self._timingBeamsMembership.clear() self._vlbiBeamsMembership.clear() self._se_to_switch_off.clear() # PROTECTED REGION END # // CspMaster.delete_device # PROTECTED REGION ID# // CspMaster private methods # PROTECTED REGION END # //CspMaster private methods # ------------------ # Attributes methods # ------------------ def write_adminMode(self, value): """ Write attribute method. Set the administration mode for the whole CSP element. Args: value: one of the administration mode value (ON-LINE,\ OFF-LINE, MAINTENANCE, NOT-FITTED, RESERVED). Returns: None """ # PROTECTED REGION ID(CspMaster.adminMode_write) ENABLED START # for fqdn in self._se_fqdn: try: device_proxy = self._se_proxies[fqdn] device_proxy.adminMode = value except KeyError as kerr: log_msg = "No proxy to device {}".format(str(kerr)) self.dev_logging(log_msg, int(tango.LogLevel.LOG_ERROR)) except tango.DevFailed as df: log_msg = (("Failure in setting adminMode " "for device {}: {}".format(str(fqdn), str(df.args[0].reason)))) self.dev_logging(log_msg, int(tango.LogLevel.LOG_ERROR)) #TODO: what happens if one sub-element fails? self._admin_mode = value # PROTECTED REGION END # // CspMaster.adminMode_write def read_commandProgress(self): """ Read attribute method. Returns: The commandProgress attribute value. """ # PROTECTED REGION ID(CspMaster.commandProgress_read) ENABLED START # return self._progress_command # PROTECTED REGION END # // CspMaster.commandProgress_read def read_cspCbfState(self): """ Read attribute method. Returns: The CBF Sub-element *State* attribute value. """ # PROTECTED REGION ID(CspMaster.cspCbfState_read) ENABLED START # return self._se_state[self.CspMidCbf] # PROTECTED REGION END # // CspMaster.cspCbfState_read def read_cspPssState(self): """ Read attribute method. Returns: The PSS Sub-element *State* attribute value. """ # PROTECTED REGION ID(CspMaster.cspPssState_read) ENABLED START # return self._se_state[self.CspMidPss] # PROTECTED REGION END # // CspMaster.cspPssState_read def read_cspPstState(self): """ Read attribute method. Returns: The PST Sub-element *State* attribute value. """ # PROTECTED REGION ID(CspMaster.cspPstState_read) ENABLED START # return self._se_state[self.CspMidPst] # PROTECTED REGION END # // CspMaster.cspPstState_read def read_cspCbfHealthState(self): """ Read attribute method. Returns: The CBF Sub-element *healthState* attribute value. """ # PROTECTED REGION ID(CspMaster.cspCbfHealthState_read) ENABLED START # return self._se_healthstate[self.CspMidCbf] # PROTECTED REGION END # // CspMaster.cspCbfHealthState_read def read_cspPssHealthState(self): """ Read attribute method. Returns: The PSS Sub-element *healthState* attribute value. """ # PROTECTED REGION ID(CspMaster.cspPssHealthState_read) ENABLED START # return self._se_healthstate[self.CspMidPss] # PROTECTED REGION END # // CspMaster.cspPssHealthState_read def read_cspPstHealthState(self): """ Read attribute method. Returns: The PST Sub-element *healthState* attribute value. """ # PROTECTED REGION ID(CspMaster.cspPstHealthState_read) ENABLED START # return self._se_healthstate[self.CspMidPst] # PROTECTED REGION END # // CspMaster.cspPstHealthState_read def read_cbfMasterAddress(self): """ Read attribute method. Returns: Return the CBS sub-element Master TANGO Device address. """ # PROTECTED REGION ID(CspMaster.cbfMasterAddress_read) ENABLED START # return self.CspMidCbf # PROTECTED REGION END # // CspMaster.cbfMasterAddress_read def read_pssMasterAddress(self): """ Read attribute method. Returns: The PSS sub-element Master TANGO Device address. """ # PROTECTED REGION ID(CspMaster.pssMasterAddress_read) ENABLED START # return self.CspMidPss # PROTECTED REGION END # // CspMaster.pssMasterAddress_read def read_pstMasterAddress(self): """ Read attribute method. Returns: The PST sub-element Master TANGO Device address. """ # PROTECTED REGION ID(CspMaster.pstMasterAddress_read) ENABLED START # return self.CspMidPst # PROTECTED REGION END # // CspMaster.pstMasterAddress_read def read_cbfAdminMode(self): """ Read attribute method. Returns: The CBF sub-element *adminMode* attribute value. """ # PROTECTED REGION ID(CspMaster.pssAdminMode_read) ENABLED START # return self._se_adminmode[self.CspMidCbf] # PROTECTED REGION END # // CspMaster.cbfAdminMode_read def write_cbfAdminMode(self, value): # PROTECTED REGION ID(CspMaster.cbfAdminMode_write) ENABLED START # """ Write attribute method. Set the CBF sub-element *adminMode* attribute value. Args: value: one of the administration mode value (ON-LINE,\ OFF-LINE, MAINTENANCE, NOT-FITTED, RESERVED). Returns: None Raises: tango.DevFailed: raised when there is no DeviceProxy providing interface \ to the CBF sub-element Master, or an exception is caught in command execution. """ if self.__is_subelement_available(self.CspMidCbf): try: cbf_proxy = self._se_proxies[self.CspMidCbf] cbf_proxy.adminMode = value except tango.DevFailed as df: tango.Except.throw_exception("Command failed", str(df.args[0].desc), "Set cbf admin mode", tango.ErrSeverity.ERR) except KeyError as key_err: msg = "Can't retrieve the information of key {}".format(key_err) self.dev_logging(msg, tango.LogLevel.LOG_ERROR) tango.Except.throw_exception("Command failed", msg, "Set cbf admin mode", tango.ErrSeverity.ERR) # PROTECTED REGION END # // CspMaster.cbfAdminMode_write def read_pssAdminMode(self): """ Read attribute method. Returns: The PSS sub-element *adminMode* attribute value. """ # PROTECTED REGION ID(CspMaster.pssAdminMode_read) ENABLED START # return self._se_adminmode[self.CspMidPss] # PROTECTED REGION END # // CspMaster.pssAdminMode_read def write_pssAdminMode(self, value): """ Write attribute method. Set the PSS sub-element *adminMode* attribute value. Args: value: one of the administration mode value (ON-LINE, \ OFF-LINE, MAINTENANCE, NOT-FITTED, RESERVED). Returns: None Raises: tango.DevFailed: raised when there is no DeviceProxy providing interface to the PSS sub-element Master, or an exception is caught in command execution. """ # PROTECTED REGION ID(CspMaster.pssAdminMode_write) ENABLED START # try: pss_proxy = self._se_proxies[self.CspMidPss] pss_proxy.adminMode = value except KeyError as key_err: err_msg = "No proxy for device" + str(key_err) self.dev_logging(err_msg, int(tango.LogLevel.LOG_ERROR)) tango.Except.throw_exception("Command failed", err_msg, "Set pss admin mode", tango.ErrSeverity.ERR) except tango.DevFailed as df: tango.Except.throw_exception("Command failed", str(df.args[0].desc), "Set pss admin mode", tango.ErrSeverity.ERR) # PROTECTED REGION END # // CspMaster.pssAdminMode_write def read_pstAdminMode(self): """ Read attribute method. Returns: The PST sub-element *adminMode* attribute value. """ # PROTECTED REGION ID(CspMaster.pstAdminMode_read) ENABLED START # return self._se_adminmode[self.CspMidPst] # PROTECTED REGION END # // CspMaster.pstAdminMode_read def write_pstAdminMode(self, value): """ Write attribute method. Set the PST sub-element *adminMode* attribute value. Args: value: one of the administration mode value (ON-LINE,\ OFF-LINE, MAINTENANCE, NOT-FITTED, RESERVED). Returns: None Raises: tango.DevFailed: raised when there is no DeviceProxy providing interface to the PST sub-element\ Master, or an exception is caught in command execution. """ # PROTECTED REGION ID(CspMaster.pstAdminMode_write) ENABLED START # try: pst_proxy = self._se_proxies[self.CspMidPst] pst_proxy.adminMode = value except KeyError as key_err: err_msg = "No proxy for device" + str(key_err) self.dev_logging(err_msg, int(tango.LogLevel.LOG_ERROR)) tango.Except.throw_exception("Command failed", err_msg, "Set pst admin mode", tango.ErrSeverity.ERR) except tango.DevFailed as df: tango.Except.throw_exception("Command failed", str(df.args[0].desc), "Set pst admin mode", tango.ErrSeverity.ERR) # PROTECTED REGION END # // CspMaster.pstAdminMode_write def read_availableCapabilities(self): """ Override read attribute method. Returns: A list of strings with the number of available resources for each capability/resource type. Example: ["Receptors:95", "SearchBeam:1000", "TimingBeam:16", "VlbiBeam:20"] Raises: tango.DevFailed """ # PROTECTED REGION ID(CspMaster.availableCapabilities_read) ENABLED START # self._available_capabilities = {} try: #proxy = tango.DeviceProxy(self.get_name()) available_receptors = self.read_availableReceptorIDs() #NOTE: if there is no available receptor, this call returns an array # [0] whose length is 1 (not 0) if len(available_receptors) >= 1: if available_receptors[0] == 0: self._available_capabilities["Receptors"] = 0 else: self._available_capabilities["Receptors"] = len(available_receptors) #TODO:update when also PSS and PST will be available self._available_capabilities["SearchBeam"] = 0 self._available_capabilities["TimingBeam"] = 0 self._available_capabilities["VlbiBeam"] = 0 except tango.DevFailed as df: msg = "Attribute reading failure: {}".format(df.args[0].desc) self.dev_loggig(msg, tango.LogLevel.LOG_ERROR) tango.Except.throw_exception("Attribute reading failure", df.args[0].desc, "read_availableCapabilities", tango.ErrSeverity.ERR) except AttributeError as attr_err: msg = "Error in reading {}: {} ".format(str(attr_err.args[0]), attr_err.__doc__) tango.Except.throw_exception("Attribute reading failure", msg, "read_availableCapabilities", tango.ErrSeverity.ERR) return utils.convert_dict_to_list(self._available_capabilities) # PROTECTED REGION END # // CspMaster.availableCapabilities_read def read_reportSearchBeamState(self): """ Class attribute method. Returns: The *State* value of the CSP SearchBeam Capabilities.\n *Type*: array of DevState. """ # PROTECTED REGION ID(CspMaster.reportSearchBeamState_read) ENABLED START # return self._search_beams_state # PROTECTED REGION END # // CspMaster.reportSearchBeamState_read def read_reportSearchBeamHealthState(self): """ Class attribute method. Returns: The *healthState* attribute value of the CSP SearchBeam Capabilities.\n *Type*: array of DevUShort """ # PROTECTED REGION ID(CspMaster.reportSearchBeamHealthState_read) ENABLED START # return self._search_beams_health_state # PROTECTED REGION END # // CspMaster.reportSearchBeamHealthState_read def read_reportSearchBeamAdminMode(self): """ Class attribute method. Returns: The *adminMode* of the CSP SearchBeam Capabilities.\n *Type*: array of DevUShort """ # PROTECTED REGION ID(CspMaster.reportSearchBeamAdminMode_read) ENABLED START # return self._search_beams_admin # PROTECTED REGION END # // CspMaster.reportSearchBeamAdminMode_read def read_reportTimingBeamState(self): """ Class attribute method. Returns: The *State* value of the CSP TimingBeam Capabilities.\n *Type*: array of DevState. """ # PROTECTED REGION ID(CspMaster.reportTimingBeamState_read) ENABLED START # return self._timing_beams_state # PROTECTED REGION END # // CspMaster.reportTimingBeamState_read def read_reportTimingBeamHealthState(self): """ Class attribute method. Returns: The *healthState* value of the CSP TimingBeam Capabilities.\n *Type*: array of DevUShort. """ # PROTECTED REGION ID(CspMaster.reportTimingBeamHealthState_read) ENABLED START # return self._timing_beams_health_state # PROTECTED REGION END # // CspMaster.reportTimingBeamHealthState_read def read_reportTimingBeamAdminMode(self): """ Class attribute method. Returns: The *adminMode* value of the CSP TimingBeam Capabilities.\n *Type*: array of DevUShort. """ # PROTECTED REGION ID(CspMaster.reportTimingBeamAdminMode_read) ENABLED START # return self._timing_beams_admin # PROTECTED REGION END # // CspMaster.reportTimingBeamAdminMode_read def read_reportVlbiBeamState(self): """ Class attribute method. Returns: The *State* value of the CSP VlbiBeam Capabilities.\n *Type*: array of DevState. """ # PROTECTED REGION ID(CspMaster.reportVlbiBeamState_read) ENABLED START # return self._vlbi_beams_state # PROTECTED REGION END # // CspMaster.reportVlbiBeamState_read def read_reportVlbiBeamHealthState(self): """ Class attribute method. Returns: The *healthState* value of the CSP VlbiBeam Capabilities.\n *Type*: array of DevUShort. """ # PROTECTED REGION ID(CspMaster.reportVlbiBeamHealthState_read) ENABLED START # return self._vlbi_beams_health_state # PROTECTED REGION END # // CspMaster.reportVlbiBeamHealthState_read def read_reportVlbiBeamAdminMode(self): """ Read attribute method. Returns: The *adminMode* value of the CSP VlbiBeam Capabilities.\n *Type*: array of DevUShort. """ # PROTECTED REGION ID(CspMaster.reportVlbiBeamAdminMode_read) ENABLED START # return self._vlbi_beams_admin # PROTECTED REGION END # // CspMaster.reportVlbiBeamAdminMode_read def read_cspSubarrayAddress(self): """ Class attribute method. Returns: The CSP Subarrays FQDNs if the associated Device Property is defined, otherwise None.\n *Type*: array of DevString """ # PROTECTED REGION ID(CspMaster.cspSubarrayAddress_read) ENABLED START # if not self.CspSubarrays: self.CspSubarrays = [] return self.CspSubarrays # PROTECTED REGION END # // CspMaster.cspSubarrayAddress_read def read_searchBeamCapAddress(self): """ Class attribute method. Returns: The CSP SearchBeam Capabilities FQDNs if the associated Device Property is defined, otherwise None.\n *Type*: array of DevString """ # PROTECTED REGION ID(CspMaster.searchBeamCapAddress_read) ENABLED START # if not self.SearchBeams: self.SearchBeams = [] return self.SearchBeams # PROTECTED REGION END # // CspMaster.searchBeamCapAddress_read def read_timingBeamCapAddress(self): """ Class attribute method. Returns: The CSP TimingBeam Capabilities FQDNs if the associated Device Property is defined, otherwise None.\n *Type*: array of DevString """ # PROTECTED REGION ID(CspMaster.timingBeamCapAddress_read) ENABLED START # if not self.TimingBeams: self.TimingBeams = [] return self.TimingBeams # PROTECTED REGION END # // CspMaster.timingBeamCapAddress_read def read_vlbiCapAddress(self): """ Class attribute method. Returns: The CSP VlbiBeam Capabilities FQDNs if the associated Device Property is defined, otherwise None.\n *Type*: array of DevString """ # PROTECTED REGION ID(CspMaster.vlbiCapAddress_read) ENABLED START # if not self.VlbiBeams: self.VlbiBeams = [] return self.VlbiBeams # PROTECTED REGION END # // CspMaster.vlbiCapAddress_read def read_receptorMembership(self): """ Class attribute method. Returns: The subarray affiliation of the receptors. """ # PROTECTED REGION ID(CspMaster.receptorMembership_read) ENABLED START # if self.__is_subelement_available(self.CspMidCbf): try: proxy = self._se_proxies[self.CspMidCbf] proxy.ping() vcc_membership = proxy.reportVccSubarrayMembership for vcc_id, receptorID in self._vcc_to_receptor_map.items(): self._receptorsMembership[receptorID - 1] = vcc_membership[vcc_id - 1] except tango.DevFailed as df: tango.Except.re_throw_exception(df, "CommandFailed", "read_receptorsMembership failed", "Command()") except KeyError as key_err: msg = "Can't retrieve the information of key {}".format(key_err) self.dev_logging(msg, tango.LogLevel.LOG_ERROR) tango.Except.throw_exception("Attribute reading failure", msg, "read_receptorMembership", tango.ErrSeverity.ERR) except AttributeError as attr_err: msg = "Error in reading {}: {} ".format(str(attr_err.args[0]), attr_err.__doc__) tango.Except.throw_exception("Attribute reading failure", msg, "read_receptorMembership", tango.ErrSeverity.ERR) return self._receptorsMembership # PROTECTED REGION END # // CspMaster.receptorMembership_read def read_searchBeamMembership(self): """ Class attribute method. Returns: The subarray affilitiaion of the Search Beams. """ # PROTECTED REGION ID(CspMaster.searchBeamMembership_read) ENABLED START # return self._searchBeamsMembership # PROTECTED REGION END # // CspMaster.searchBeamMembership_read def read_timingBeamMembership(self): """ Class attribute method. Returns: The subarray affilitiaion of the Timing Beams. """ # PROTECTED REGION ID(CspMaster.timingBeamMembership_read) ENABLED START # return self._timingBeamsMembership # PROTECTED REGION END # // CspMaster.timingBeamMembership_read def read_vlbiBeamMembership(self): """ Class attribute method. Returns: The subarray affilitiaion of the Vlbi Beams. """ # PROTECTED REGION ID(CspMaster.vlbiBeamMembership_read) ENABLED START # return self._vlbiBeamsMembership # PROTECTED REGION END # // CspMaster.vlbiBeamMembership_read def read_availableReceptorIDs(self): """ Class attribute method. Returns: The list of the available receptors IDs. The list includes all the receptors that are not assigned to any subarray and, from the side of CSP, are considered "full working". This means:\n * a valid link connection receptor-VCC\n * the connected VCC healthState OK *Type*: array of DevUShort Raises: tango.DevFailed: if there is no DeviceProxy providing interface to the\ CBF sub-element Master Device or an error is caught during\ command execution. """ # PROTECTED REGION ID(CspMaster.availableReceptorIDs_read) ENABLED START # self._available_receptorIDs = [] try: proxy = self._se_proxies[self.CspMidCbf] proxy.ping() vcc_state = proxy.reportVCCState vcc_membership = proxy.reportVccSubarrayMembership # get the list with the IDs of the available VCC for vcc_id, receptorID in self._vcc_to_receptor_map.items(): try: if vcc_state[vcc_id - 1] not in [tango.DevState.UNKNOWN]: # skip the vcc already assigned to a sub-array if vcc_membership[vcc_id - 1] != 0: continue # OSS: valid receptorIDs are in [1,197] range # receptorID = 0 means the link connection between # the receptor and the VCC is off if receptorID > 0: self._available_receptorIDs.append(receptorID) else: log_msg = ("Link problem with receptor connected" " to Vcc {}".format(vcc_id + 1)) self.dev_logging(log_msg, tango.LogLevel.LOG_WARN) except KeyError as key_err: log_msg = ("No key {} found while accessing VCC {}".format(str(key_err), vcc_id)) self.dev_logging(log_msg, tango.LogLevel.LOG_WARN) except IndexError as idx_error: log_msg = ("Error accessing VCC" " element {}: {}".format(vcc_id, str(idx_error))) self.dev_logging(log_msg, tango.LogLevel.LOG_WARN) except KeyError as key_err: log_msg = "Can't retrieve the information of key {}".format(key_err) tango.Except.throw_exception("Attribute reading failure", log_msg, "read_availableReceptorIDs", tango.ErrSeverity.ERR) except tango.DevFailed as df: log_msg = "Error in read_availableReceptorIDs: {}".format(df.args[0].reason) self.dev_logging(log_msg, int(tango.LogLevel.LOG_ERROR)) tango.Except.throw_exception("Attribute reading failure", log_msg, "read_availableReceptorIDs", tango.ErrSeverity.ERR) except AttributeError as attr_err: msg = "Error in reading {}: {} ".format(str(attr_err.args[0]), attr_err.__doc__) tango.Except.throw_exception("Attribute reading failure", msg, "read_availableReceptorIDs", tango.ErrSeverity.ERR) # !!! # 2019-10-18 # NOTE: with the new TANGO/PyTango images release (PyTango 9.3.1, TANGO 9.3.3, numpy 1.17.2) # the issue of "DeviceAttribute object has no attribute 'value'" has been resolved. Now # a TANGO RO attribute initializaed to an empty list (see self._available_receptorIDs), # returns a NoneType object, as happed before with PyTango 9.2.5, TANGO 9.2.5 images. # The beavior now is coherent, but I don't revert to the old code: this methods # keep returning an array with one element = 0 when no receptors are available. if len(self._available_receptorIDs) == 0: return [0] return self._available_receptorIDs # PROTECTED REGION END # // CspMaster.vlbiBeamMembership_read # -------- # Commands # -------- def is_On_allowed(self): """ *TANGO is_allowed method* Command *On* is allowed when:\n * state is STANDBY and adminMode = MAINTENACE or ONLINE (end state = ON)\n * state is DISABLE and adminMode = MAINTENACE or ONLINE (end state = ON) Returns: True if the method is allowed, otherwise False. """ # PROTECTED REGION ID(CspMaster.is_On_allowed) ENABLED START # if self.get_state() not in [tango.DevState.STANDBY, tango.DevState.DISABLE]: return False return True # PROTECTED REGION END # // CspMaster.is_On_allowed @command( dtype_in=('str',), doc_in="If the array length is 0, the command applies to the whole CSP Element.\ If the array length is > 1, each array element specifies the FQDN of the\ CSP SubElement to switch ON.", ) @DebugIt() def On(self, argin): """ *Class method* Switch-on the CSP sub-elements specified by the input argument. If no argument is\ specified, the command is issued on all the CSP sub-elements.\n The command is executed if the *AdminMode* is ONLINE or *MAINTENANCE*.\n If the AdminMode is *OFFLINE*, *NOT-FITTED* or *RESERVED*, the method throws an exception. Args: argin: the list of sub-element FQDNs to switch-on or an empty list to switch-on\ the whole CSP Element. Type: DevVarStringArray Returns: None Raises: tango.DevFailed: an exception is caught processing the On command for\ the CBF sub-element or there are no DeviceProxy providing interface\ to the CSP sub-elements or the AdminMode is not correct. """ # PROTECTED REGION ID(CspMaster.On) ENABLED START # # Check the AdminMode value: only if it's ONLINE or MAINTENACE # the command is callable. if self._admin_mode in [AdminMode.OFFLINE, AdminMode.NOTFITTED, AdminMode.RESERVED]: # NOTE: when adminMode is NOT_FITTED, OFFLINE or RESERVED device itself # sets the TANGO state to DISABLE # Add only a check on State value to log a warning message if it # is different from DISABLE msg_args = (self.get_state(), self._admin_mode) if self.get_state() != tango.DevState.DISABLE: self.dev_logging("is_On_allowed: incoherent device State {} " " with adminMode {}".format(*msg_args), tango.LogLevel.LOG_WARN) err_msg = ("On() command can't be issued when State is {} and" " adminMode is {} ".format(*msg_args)) tango.Except.throw_exception("Command not executable", err_msg, "On command execution", tango.ErrSeverity.ERR) device_list = [] num_of_devices = len(argin) if num_of_devices == 0: # no input argument -> switch on all sub-elements num_of_devices = len(self._se_fqdn) device_list = self._se_fqdn else: if num_of_devices > len(self._se_fqdn): # too many devices specified-> log the warning but go on # with command execution self.dev_logging("Too many input parameters", tango.LogLevel.LOG_WARN) device_list = argin nkey_err = 0 for device_name in device_list: try: self.dev_logging("device_name:{}".format(device_name), tango.LogLevel.LOG_WARN) self.dev_logging("device_list:{}".format(device_list), tango.LogLevel.LOG_WARN) device_proxy = self._se_proxies[device_name] device_proxy.command_inout("On") except KeyError as error: # throw an exception only if: # - no proxy found for the only specified input device # - or no proxy found for CBF. # In all other cases log the error message err_msg = "No proxy for device: {}".format(str(error)) self.dev_logging(err_msg, int(tango.LogLevel.LOG_ERROR)) nkey_err += 1 except tango.DevFailed as df: # the command fails if: # - cbf command fails # - or the only specified device fails executing the command. # In all other cases the error messages are logged. self.dev_logging("df:{}".format(df.args[0].desc), tango.LogLevel.LOG_WARN) if ("cbf" in device_name) or num_of_devices == 1: tango.Except.throw_exception("Command failed", str(df.args[0].desc), "On command execution", tango.ErrSeverity.ERR) else: self.dev_logging(str(df.args[0].desc), tango.LogLevel.LOG_ERROR) # throw an exception if ALL the specified devices have no # associated proxy if nkey_err == num_of_devices: err_msg = 'No proxy found for devices:' for item in device_list: err_msg += item + ' ' tango.Except.throw_exception("Command failed", err_msg, "On command execution", tango.ErrSeverity.ERR) # PROTECTED REGION END # // CspMaster.On def is_Off_allowed(self): """ *TANGO is_allowed method* Command *Off* is allowed when the device *State* is STANDBY. Returns: True if the method is allowed, otherwise False. """ # PROTECTED REGION ID(CspMaster.is_On_allowed) ENABLED START # if self.get_state() not in [tango.DevState.STANDBY]: return False return True @command( dtype_in=('str',), doc_in="If the array length is 0, the command applies to the whole CSP Element.\ If the array length is > 1, each array element specifies the FQDN of the\ CSP SubElement to switch OFF." ) @DebugIt() def Off(self, argin): """ Switch-off the CSP sub-elements specified by the input argument. \ If no argument is specified, the command is issued to all the CSP \ sub-elements. Args: argin: The list of sub-elements to switch-off. If the array\ length is 0, the command applies to the whole CSP Element.\ If the array length is > 1, each array element specifies the FQDN of the\ CSP SubElement to switch OFF Type: DevVarStringArray Returns: None """ # PROTECTED REGION ID(CspMaster.Off) ENABLED START # device_list = [] num_of_devices = len(argin) if num_of_devices == 0: # no input argument -> switch on all sub-elements num_of_devices = len(self._se_fqdn) device_list = self._se_fqdn else: if num_of_devices > len(self._se_fqdn): # too many devices specified-> log the warning but go on # with command execution self.dev_logging("Too many input parameters", tango.LogLevel.LOG_WARN) device_list = argin for device_name in device_list: try: device_proxy = self._se_proxies[device_name] device_proxy.command_inout("Off") self._se_to_switch_off[device_name] = True except KeyError as error: err_msg = "No proxy for device {}".format(str(error)) self.dev_logging(err_msg, int(tango.LogLevel.LOG_ERROR)) except tango.DevFailed as df: self.dev_logging(str(df.args[0].desc), tango.LogLevel.LOG_ERROR) # PROTECTED REGION END # // CspMaster.Off def is_Standby_allowed(self): """ *TANGO is_allowed method* Command *Standby* is allowed when the device *State* is ON, DISABLE or ALARM. Returns: True if the method is allowed, otherwise False. """ # PROTECTED REGION ID(CspMaster.is_On_allowed) ENABLED START # if self.get_state() not in [tango.DevState.ON, tango.DevState.DISABLE, tango.DevState.ALARM]: return False return True @command( dtype_in=('str',), doc_in="If the array length is 0, the command applies to the whole\nCSP Element.\n\ If the array length is > 1, each array element specifies the FQDN of the\n\ CSP SubElement to switch OFF.", ) @DebugIt() def Standby(self, argin): # PROTECTED REGION ID(CspMaster.Standby) ENABLED START # """ Transit to STANDBY the CSP sub-elements specified by the input argument. \ If no argument is specified, the command is issued to all the CSP sub-elements. Args: argin: The list of the Sub-element devices FQDNs Type: DevVarStringArray Returns: None Raises: tango.DevFailed: if command fails or if no DeviceProxy associated to the FQDNs. """ device_list = [] num_of_devices = len(argin) if num_of_devices == 0: # no input argument -> switch on all sub-elements num_of_devices = len(self._se_fqdn) device_list = self._se_fqdn else: if num_of_devices > len(self._se_fqdn): # too many devices specified-> log the warning but go on # with command execution self.dev_logging("Too many input parameters", tango.LogLevel.LOG_WARN) device_list = argin nkey_err = 0 for device_name in device_list: try: device_proxy = self._se_proxies[device_name] device_proxy.command_inout("Standby") except KeyError as error: # throw an exception only if: # - no proxy found for the only specified input device # - or no proxy found for CBF. # In all other cases log the error message err_msg = "No proxy for device {}".format(str(error)) self.dev_logging(err_msg, tango.LogLevel.LOG_ERROR) nkey_err += 1 except tango.DevFailed as df: # the command fails if: # - cbf command fails # - or the only specified device fails executing the command. # In all other cases the error messages are logged. if ("cbf" in device_name) or num_of_devices == 1: tango.Except.throw_exception("Command failed", str(df.args[0].desc), "Standby command execution", tango.ErrSeverity.ERR) else: self.dev_logging(str(df.args[0].desc), tango.LogLevel.LOG_ERROR ) # throw an exception if ALL the specified devices have no associated proxy if nkey_err == num_of_devices: err_msg = 'No proxy found for devices:' for item in device_list: err_msg += item + ' ' tango.Except.throw_exception("Command failed", err_msg, "Standby command execution", tango.ErrSeverity.ERR) # PROTECTED REGION END # // CspMaster.Standby # ---------- # Run server # ---------- def main(args=None, **kwargs): # PROTECTED REGION ID(CspMaster.main) ENABLED START # return run((CspMaster,), args=args, **kwargs) # PROTECTED REGION END # // CspMaster.main if __name__ == '__main__': main() <file_sep>/docs/src/CspSubarray.rst ############## CSP Subarrays ############## The core CSP functionality, configuration and execution of signal processing, is configured, controlled and monitored via subarrays. CSP Subarray makes provision to TM to configure a subarray, select Processing Mode and related parameters, specify when to start/stop signal processing and/or generation of output products. TM accesses directly a CSP Subarray to: * Assign resources * Configure a scan * Control and monitor states/operations Resources assignment ===================== The assignment of Capabilities to a subarray (*subarray composition*) is performed in advance of a scan configuration. Assignable Capabilities for CSP Mid subarrays are: * receptors and the associated CBF Very Coarse Channelizers:each VCC processes the input from one receptor. * CBF Frequency Slice Processors performing one of the available Processing Mode Functions: Correlation, Pulsar Timing Beamforming, Pulsar Search Beamforming, VLBI Beamforming. * tied-array beams: Search Beams, Timing Beams and Vlbi Beams. In general resource assignment to a subarray is exclusive, but in some cases (FSPs) the same Capability instance may be used in shared manner by more then one subarray. *Note: of all the listed Capabilities, only FSPs are assigned to subarrays via a scan configuration.* Inherent Capabilities --------------------- Each CSP subarray has also four permanently assigned *inherent Capabilities*: * Correlation * PSS * PST * VLBI An inherent Capability can be enabled or disabled, but cannot assigned or removed to/from a subarray. They correspond to the CSP Mid Processing Modes and are configured via a scan configuration. Scan configuration ==================== TM provides a complete scan configuration to a subarray via an ASCII JSON encoded string. Parameters specified via a JSON string are implemented as TANGO Device attributes and can be accessed and modified directly using the buil-in TANGO method *write_attribute*. When a complete and coherent scan configuration is received and the subarray configuration (or re-configuration) completed, the subarray it's ready to observe. Control and Monitoring ====================== Each CSP Subarray maintains and report the status and state transitions for the CSP subarray as a whole and for the individual assigned resources. In addition to pre-configured status reporting, a CSP Subarray makes provision for the TM and any authorized client, to obtain the value of any subarray attribute. Class Documentation =============================== .. automodule:: CspSubarray :members: :undoc-members: <file_sep>/docs/src/CspMaster.rst .. Documentation CspMaster Class Documentation ================================ .. automodule:: CspMaster :members: :undoc-members: :show-inheritance: :member-order: <file_sep>/test-harness/README.md This directory is uploaded to the container when 'make test' is executed. Files in this directory will be found inside /build once uploaded to the container. <file_sep>/docs/src/index.rst .. CSP LMC Prototype documentation master file, created by sphinx-quickstart on Thu Jun 13 16:15:47 2019. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. CSP LMC Prototype's documentation ============================================= .. toctree:: :maxdepth: 1 :caption: Contents: CspMaster<CspMaster> CspSubarray<CspSubarray> Common definitions<global_enum> Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` <file_sep>/csplmc/commons/global_enum.py from enum import IntEnum, unique @unique class HealthState(IntEnum): OK = 0 DEGRADED = 1 FAILED = 2 UNKNOWN = 3 @unique class AdminMode(IntEnum): ONLINE = 0 OFFLINE = 1 MAINTENANCE = 2 NOTFITTED = 3 RESERVED = 4 @unique class ControlMode(IntEnum): REMOTE = 0 LOCAL = 1 @unique class ObsMode(IntEnum): IDLE = 0 IMAGING = 1 PULSARSEARCH = 2 PULSARTIMING = 3 DYNAMICSPECTRUM = 4 TRANSIENTSEARCH = 5 VLBI = 6 CALIBRATION = 7 @unique class ObsState(IntEnum): IDLE = 0 CONFIGURING = 1 READY = 2 SCANNING = 3 PAUSED = 4 ABORTED = 5 FAULT = 6 #define some SKA1 MID constant NUM_OF_RECEPTORS = 197 NUM_OF_SEARCH_BEAMS = 1500 NUM_OF_TIMING_BEAMS = 16 NUM_OF_VLBI_BEAMS = 20 NUM_OF_SUBARRAYS = 16 <file_sep>/csplmc/configureDevices.py # This script is used only by the start_prototype script. # Docker containers rely on dsconfig device to configure the TANGO DB #!/usr/bin/env python import json import tango from tango import Database, DbDevInfo from time import sleep timeSleep = 30 for x in range(10): try: # Connecting to the databaseds db = Database() except tango.DevFailed as df: # Could not connect to the databaseds. Retry after: str(timeSleep) seconds. print("Connection to Database failure: {}".format(str(df.args[0].desc))) sleep(timeSleep) # Connected to the databaseds # Update file path to devices.json in order to test locally # To test on docker environment use path : /app/csplmc/devices.json with open('./csplmc/devices.json', 'r') as file: jsonDevices = file.read().replace('\n', '') # Loading devices.json file and creating an object json_devices = json.loads(jsonDevices) for device in json_devices: dev_info = DbDevInfo() dev_info._class = device["class"] dev_info.server = device["serverName"] dev_info.name = device["devName"] # Adding device db.add_device(dev_info) # Adding device properties for classProperty in device["classProperties"]: # Adding class property: classProperty["classPropValue"] # with value: classProperty["classPropValue"] if (classProperty["classPropName"]) != "" and (classProperty["classPropValue"] != ""): db.put_class_property(dev_info._class, {classProperty["classPropName"]:classProperty["classPropValue"]}) # Adding device properties for deviceProperty in device["deviceProperties"]: # Adding device property: deviceProperty["devPropValue"] # with value: deviceProperty["devPropValue"] if (deviceProperty["devPropName"]) != "" and (deviceProperty["devPropValue"] != ""): db.put_device_property(dev_info.name, {deviceProperty["devPropName"]: deviceProperty["devPropValue"]}) # Adding attribute properties for attributeProperty in device["attributeProperties"]: # Adding attribute property: attributeProperty["attrPropName"] # for attribute: attributeProperty["attributeName"] # with value: " + attributeProperty["attrPropValue"] if(attributeProperty["attrPropName"]) != "" and (attributeProperty["attrPropValue"] != ""): db.put_device_attribute_property(dev_info.name, {attributeProperty["attributeName"]: {attributeProperty["attrPropName"]: attributeProperty["attrPropValue"]}})
ace97594ef4fe038a7787e46d2cff7350a5b68e6
[ "reStructuredText", "Markdown", "Makefile", "Python", "Dockerfile", "Shell" ]
31
Dockerfile
ska-telescope/csp-lmc-prototype
36f35d7a0b4385d8e139a0a055cfa219d6c13a9a
574be5aa8f3c8e6a70ac058b3cd9dc5dd5ced96b
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.StructuralPatterns.Decorator { public class Component : ComponentBase { public override string Operation() { return "component"; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.BehaviouralPatterns.Visitor { public class Element02 : ElementBase { public int State { get; set; } public override void Accept(VisitorBase visitor) { visitor.Visit(this); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.StructuralPatterns.Bridge { public class RedefinedAbstraction: Abstraction { public override string Operation() { return base.Operation()+ " + redefined"; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.StructuralPatterns.Decorator { public abstract class DecoratorBase:ComponentBase { private ComponentBase _component; public DecoratorBase(ComponentBase component) { _component = component; } public override string Operation() { return _component.Operation(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.BehaviouralPatterns.Command { public class Receiver { public string Action(string parameter) { return string.Format("{0}-{1}", "Action:", parameter); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.CreationalPatterns.FactoryMethod { public class ProductBase { } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.StructuralPatterns.Bridge { public abstract class ImplementerBase { public abstract string OperationImplementation(); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.BehaviouralPatterns.Strategy { public abstract class StrategyBase { public abstract int Algorithm(int numA, int numB); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.BehaviouralPatterns.Command { public class Invoker { public CommandBase command { get; set; } public string ExecuteCommand() { if (command != null) return command.Execute(); return string.Empty; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.BehaviouralPatterns.Observer { public abstract class SubjectBase { public SubjectBase() { Observers = new List<ObserverBase>(); } public List<ObserverBase> Observers { get; set; } public void Notify() { if(this.Observers != null) foreach (var o in Observers) { o.Update(); } } public abstract string GetState(); public void Attach(ObserverBase observer) { Observers.Add(observer); } public void Dettach(ObserverBase observer) { Observers.Remove(observer); } } } <file_sep>using System; namespace DesignPatternsLib.StructuralPatterns.Facade { internal class ClassA { internal string MethodA() { return "ClassA"; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.BehaviouralPatterns.ChainOfResponsability { public class HandlerA : HandlerBase { public override string RequestHandler(int request) { if (request == 1) return "HandlerA = 1"; else if (_succesor != null) return _succesor.RequestHandler(request); return string.Empty; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.StructuralPatterns.Adapter { public class Client { ITarget _adapter; public Client(ITarget adapter) { _adapter = adapter; } public string GetValue() { return _adapter.MethodA(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.CreationalPatterns.Builder { public abstract class Builder { public abstract Builder BuildPart1(); public abstract Builder BuildPart2(); public abstract Product GetProduct(); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.BehaviouralPatterns.Mediator { public abstract class MediatorBase { public abstract void SendMesage(ColleagueBase caller); } } <file_sep> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.StructuralPatterns.Proxy { public abstract class SubjectBase { public abstract string PerformAction(); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.CreationalPatterns.AbstractFactory { public class ConcreteFactoryA : AbstractFactory { public override AbstractProductA CreateProductA() { return new ConcreteProductA1(); } public override AbstractProductB CreateProductB() { return new ConcreteProductB1(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.CreationalPatterns.FactoryMethod { public abstract class FactoryBase { public abstract ProductBase ProductFactoryMethod(); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.CreationalPatterns.Singleton { public sealed class Singleton { private static Singleton _instance; private static object _lookThis = new object(); public bool StateA { get; set; } public static Singleton Instance { get { lock (_lookThis) { if (_instance == null) _instance = new Singleton(); } return _instance; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.StructuralPatterns.Facade { public class Facade { ClassA classA = new ClassA(); ClassB classB = new ClassB(); ClassC classC = new ClassC(); public string PerformAction() { string resA = classA.MethodA(); string resB = classB.MethodB(); string resC = classC.MethodC(resA, resB); return resC; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.BehaviouralPatterns.Interpreter { public class NonTerminalExpression : ExpressionBase { public ExpressionBase SubExpressionA { get; set; } public ExpressionBase SubExpressionB { get; set; } public override string Interpret(Context context) { return SubExpressionA.Interpret(context) + SubExpressionB.Interpret(context); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.BehaviouralPatterns.Command { public class CommandA : CommandBase { public CommandA(Receiver receiver) : base(receiver) { } public string Parameter { get; set; } public override string Execute() { return _receiver.Action(Parameter); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.StructuralPatterns.Composite { public class Component { public virtual string Operation() { return "component"; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.StructuralPatterns.Adapter { public class Adaptee { public bool state { get; set; } public bool MethodB() { return state; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.StructuralPatterns.Proxy { public class RealSubject : SubjectBase { public override string PerformAction() { return "RealSubject"; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.StructuralPatterns.Flyweight { public class FlyweightFactory { private Dictionary<string, FlyweightBase> _flyweights = new Dictionary<string, FlyweightBase>(); public FlyweightBase GetFlyweight(string key) { if (!_flyweights.ContainsKey(key)) _flyweights.Add(key, new FlyweightConcrete()); return _flyweights[key]; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.BehaviouralPatterns.Visitor { public class Structure { public List<ElementBase> Elements { get; set; } public Structure() { Elements = new List<ElementBase>(); } public void Accept(VisitorBase visitor) { foreach (var e in Elements) { e.Accept(visitor); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.StructuralPatterns.Decorator { public abstract class ComponentBase { public abstract string Operation(); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.CreationalPatterns.Builder { public class Product { public string Part1 { get; set; } public string Part2 { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.CreationalPatterns.AbstractFactory { public class Client { AbstractFactory _factory; public AbstractProductA ProductA { get; private set; } public AbstractProductB ProductB { get; private set; } public Client(AbstractFactory factory) { _factory = factory; ProductA = _factory.CreateProductA(); ProductB = _factory.CreateProductB(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.CreationalPatterns.Builder { public class ProductBuilder : Builder { Product _product = new Product(); public override Builder BuildPart1() { _product.Part1 = "parte 1"; return this; } public override Builder BuildPart2() { _product.Part2 = "parte 2"; return this; } public override Product GetProduct() { return _product; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.BehaviouralPatterns.Mediator { public class Mediator:MediatorBase { public ColleagueBase colleagueA { get; set; } public ColleagueBase colleagueB { get; set; } public override void SendMesage(ColleagueBase caller) { if (caller == colleagueA) colleagueB.Recv("mesage for B: "+caller.Message); else colleagueA.Recv("mesage for A: " + caller.Message); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.StructuralPatterns.Bridge { public class Abstraction { public ImplementerBase Implementer{ get; set; } public virtual string Operation() { return Implementer.OperationImplementation(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.BehaviouralPatterns.ChainOfResponsability { public abstract class HandlerBase { protected HandlerBase _succesor; public void SetSucessor(HandlerBase handler) { _succesor = handler; } public abstract string RequestHandler(int request); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.BehaviouralPatterns.Visitor { public class VisitorB : VisitorBase { public override void Visit(Element02 element) { element.State += 10; } public override void Visit(Element01 element) { element.State += 10; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.BehaviouralPatterns.Visitor { public class VisitorA : VisitorBase { public override void Visit(Element02 element) { element.State += 2; } public override void Visit(Element01 element) { element.State += 2; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.StructuralPatterns.Proxy { public class Proxy : SubjectBase { private RealSubject subject; public override string PerformAction() { if (subject == null) subject = new RealSubject(); return subject.PerformAction(); } } } <file_sep>using System; namespace DesignPatternsLib.StructuralPatterns.Facade { internal class ClassC { internal string MethodC(string resA, string resB) { return resA + "_" + resB; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.BehaviouralPatterns.Mediator { public abstract class ColleagueBase { public string Message { get; set; } protected MediatorBase _mediator; public ColleagueBase(MediatorBase mediator) { _mediator = mediator; } public abstract void Send(); public abstract string Recv(string msg); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.StructuralPatterns.Flyweight { public abstract class FlyweightBase { public abstract string StateFulOperation(); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.StructuralPatterns.Flyweight { public class FlyweightConcrete : FlyweightBase { public override string StateFulOperation() { return "FlyweightConcrete"; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.BehaviouralPatterns.TemplateMethod { public abstract class AlgorithmBase { protected int _numA; protected int _numB; protected int _result = 0; public AlgorithmBase(int numA, int numB) { _numA = numA; _numB = numB; } public int TemplateMethod() { Step1(); Step2(); Step3(); return _result; } public abstract void Step3(); public abstract void Step2(); public abstract void Step1(); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.BehaviouralPatterns.Observer { public class ObserverA : ObserverBase { public ObserverA(SubjectBase subject) : base(subject) { } public string State { get; set; } public override void Update() { State = this._subject.GetState() + "+A"; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.StructuralPatterns.Composite { public class Leaf: Component { public override string Operation() { return "leaf"; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.BehaviouralPatterns.TemplateMethod { public class AlgorithmA : AlgorithmBase { public AlgorithmA(int numA, int numB):base(numA, numB) { } public override void Step1() { _result = _numA + _numB; } public override void Step2() { _result = _result - 1; } public override void Step3() { _result = _result * 2; } } } <file_sep>using DesignPatternsLib.StructuralPatterns.Adapter; using DesignPatternsLib.StructuralPatterns.Bridge; using DesignPatternsLib.StructuralPatterns.Composite; using DesignPatternsLib.StructuralPatterns.Decorator; using DesignPatternsLib.StructuralPatterns.Proxy; using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLibTest { [TestClass] public class StructuralPatternsTest { [TestMethod] public void Adapter_Test() { var adaptee = new Adaptee() { state = true }; var client = new Client(new Adapter(adaptee)); var result = client.GetValue(); Assert.AreEqual(adaptee.state.ToString(), result); } [TestMethod] public void Bridge_Test() { var abs = new Abstraction(); var implementer = new ImplementerA(); var absRedefined = new RedefinedAbstraction(); abs.Implementer = implementer; absRedefined.Implementer = implementer; Assert.AreNotEqual(abs.Operation(), absRedefined.Operation()); } [TestMethod] public void Composite_Test() { var composite = new Composite(); composite.AddChild(new DesignPatternsLib.StructuralPatterns.Composite.Component()); var subcomposite = new Composite(); subcomposite.AddChild(new DesignPatternsLib.StructuralPatterns.Composite.Component()); subcomposite.AddChild(new Leaf()); composite.AddChild(subcomposite); composite.AddChild(new Composite()); composite.AddChild(new Leaf()); int countChild = 0; int countSubChild = 0; foreach (var item in composite) { if (item as Composite != null) { foreach (var item2 in item as Composite) { countSubChild++; } } countChild++; } Assert.AreEqual(countChild, 4); Assert.AreEqual(countSubChild, 2); } [TestMethod] public void Decorator_Test() { var comp = new DesignPatternsLib.StructuralPatterns.Decorator.Component(); var resA = comp.Operation(); var decorator = new Decorator(comp); var resB = decorator.Operation(); Assert.AreEqual(resA + "_decorated", resB); } [TestMethod] public void Proxy_Test() { var proxy = new Proxy(); RealSubject realSubject = new RealSubject(); var resProxy = proxy.PerformAction(); var resRealSubject = realSubject.PerformAction(); Assert.AreEqual(resProxy, resRealSubject); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.StructuralPatterns.Bridge { public class ImplementerA : ImplementerBase { public override string OperationImplementation() { return "ImplementerA"; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.BehaviouralPatterns.Strategy { public class StrategyClient { public StrategyBase Strategy { get; set; } public int NumA { get; set; } public int NumB { get; set; } public int CallAlgorithm() { if (Strategy == null) throw new Exception("set strategy please"); return Strategy.Algorithm(NumA, NumB); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.StructuralPatterns.Decorator { public class Decorator : DecoratorBase { public Decorator(ComponentBase component) : base(component) { } public override string Operation() { return base.Operation() + "_decorated"; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.BehaviouralPatterns.Observer { public class ObserverB : ObserverBase { public ObserverB(SubjectBase subject) : base(subject) { } public string State { get; set; } public override void Update() { State = this._subject.GetState() + "+B"; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.BehaviouralPatterns.Observer { public class Subject:SubjectBase { private string _state; public string State { get { return _state; } set { _state = value; Notify(); } } public override string GetState() { return State; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.BehaviouralPatterns.Strategy { public class Suma : StrategyBase { public override int Algorithm(int numA, int numB) { return numA + numB; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.BehaviouralPatterns.State { public abstract class StateBase { public abstract void Handle(Context context); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.BehaviouralPatterns.Command { public abstract class CommandBase { protected Receiver _receiver; public CommandBase(Receiver receiver) { _receiver = receiver; } public abstract string Execute(); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.CreationalPatterns.Builder { public class Director { Builder _builder; public Director(Builder builder) { _builder = builder; } public Product BuildProduct() { _builder.BuildPart1(); _builder.BuildPart2(); return _builder.GetProduct(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.StructuralPatterns.Flyweight { public class FlyweightConcreteNotShared : FlyweightBase { public override string StateFulOperation() { return "FlyweightConcreteNotShared"; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.CreationalPatterns.AbstractFactory { abstract public class AbstractFactory { abstract public AbstractProductA CreateProductA(); abstract public AbstractProductB CreateProductB(); } } <file_sep>using System; using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using DesignPatternsLib.CreationalPatterns.AbstractFactory; using DesignPatternsLib.CreationalPatterns.Builder; using DesignPatternsLib.CreationalPatterns.FactoryMethod; using DesignPatternsLib.CreationalPatterns.Prototype; using DesignPatternsLib.CreationalPatterns.Singleton; namespace DesignPatternsLibTest { [TestClass] public class CreationalPaternsTest { [TestMethod] public void AbstractFactory_CheckCorrectInstances() { var factoryA = new ConcreteFactoryA(); var _clientA = new Client(factoryA); var factoryB = new ConcreteFactoryB(); var _clientB = new Client(factoryB); var prodA1 = _clientA.ProductA; var prodB1 = _clientA.ProductB; var prodA2 = _clientB.ProductA; var prodB2 = _clientB.ProductB; Assert.IsTrue((prodA1 as ConcreteProductA1) != null, "prodA1 incorrecto"); Assert.IsTrue((prodB1 as ConcreteProductB1) != null, "prodA1 incorrecto"); Assert.IsTrue((prodA2 as ConcreteProductA2) != null, "prodA1 incorrecto"); Assert.IsTrue((prodB2 as ConcreteProductB2) != null, "prodA1 incorrecto"); } [TestMethod] public void Builder_CheckProductContruction() { var _director = new Director(new ProductBuilder()); var product = _director.BuildProduct(); Assert.IsTrue(!string.IsNullOrEmpty(product.Part1)); Assert.IsTrue(!string.IsNullOrEmpty(product.Part2)); } [TestMethod] public void FactoryMethod_CheckInstance() { var fm = new ConcreteFactory(); var prod = fm.ProductFactoryMethod(); Assert.IsFalse(prod as ConcreteProduct == null); } [TestMethod] public void Prototype_CheckClone() { var concreteB = new ConcretePrototypeB() { Name = "A" }; var concreteA = concreteB.Clone(); Assert.IsTrue(concreteA.Name == concreteB.Name); } [TestMethod] public void SingletonTest() { var ref1 = Singleton.Instance; ref1.StateA = true; var ref2 = Singleton.Instance; Assert.IsTrue(ref1.StateA == ref2.StateA); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.BehaviouralPatterns.State { public class StateA : StateBase { public override void Handle(Context context) { context.State = new StateB(); } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.StructuralPatterns.Composite { public class Composite : Component, IEnumerable<Component> { public override string Operation() { return children.Count.ToString(); } private List<Component> children = new List<Component>(); public void AddChild(Component component) { children.Add(component); } public void RemoveChild(Component component) { if(children.Contains(component)) children.Remove(component); } public Component GetChild(int i) { if(i<0 || i >= children.Count) return null; return children[i]; } public IEnumerator<Component> GetEnumerator() { foreach (var child in children) { yield return child; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.BehaviouralPatterns.State { public class StateB : StateBase { public override void Handle(Context context) { context.State = new StateA(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.StructuralPatterns.Adapter { public interface ITarget { string MethodA(); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.BehaviouralPatterns.Observer { public abstract class ObserverBase { protected SubjectBase _subject; public ObserverBase(SubjectBase subject) { _subject = subject; _subject.Attach(this); } public abstract void Update(); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.BehaviouralPatterns.State { public class Context { public StateBase State { get; set; } public void Request() { this.State.Handle(this); } } } <file_sep>using DesignPatternsLib.BehaviouralPatterns.ChainOfResponsability; using DesignPatternsLib.BehaviouralPatterns.Command; using DesignPatternsLib.BehaviouralPatterns.Interpreter; using DesignPatternsLib.BehaviouralPatterns.Mediator; using DesignPatternsLib.BehaviouralPatterns.Memento; using DesignPatternsLib.BehaviouralPatterns.Observer; using DesignPatternsLib.BehaviouralPatterns.Strategy; using DesignPatternsLib.BehaviouralPatterns.TemplateMethod; using DesignPatternsLib.BehaviouralPatterns.Visitor; using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLibTest { [TestClass] public class BehaviouralPatternsTest { [TestMethod] public void ChainOfResponsability_Test() { var handlerA = new HandlerA(); var handlerB = new HandlerB(); handlerA.SetSucessor(handlerB); handlerB.SetSucessor(handlerA); var resultA = handlerA.RequestHandler(2); var resultB = handlerB.RequestHandler(1); Assert.IsTrue(resultA.Contains("2")); Assert.IsTrue(resultB.Contains("1")); } [TestMethod] public void Command_Test() { var command = new CommandA(new Receiver()); // Receiver contains the action command.Parameter = "hola!!"; var invoker = new Invoker(); invoker.command = command; var result = invoker.ExecuteCommand(); Assert.IsTrue(result.Contains(command.Parameter) && result.Length > command.Parameter.Length); } [TestMethod] public void Interpereter_Test() { var context = new Context("hello"); var terminalA = new TerminalExpression(); var terminalB = new TerminalExpression(); var nonTerminal = new NonTerminalExpression(); nonTerminal.SubExpressionA = terminalA; nonTerminal.SubExpressionB = terminalB; var result = nonTerminal.Interpret(context); Assert.IsTrue(result.Contains(context.Name)); } [TestMethod] public void Mediator_Test() { var mediator = new Mediator(); var A = new Colleague(mediator); var B = new Colleague(mediator); mediator.colleagueA = A; mediator.colleagueB = B; A.Message = "Mike"; A.Send(); var lastMsg = B.LastMessage; Assert.IsTrue(lastMsg.Contains(A.Message)); } [TestMethod] public void Memento_Test() { var originator = new Originator(); originator.State = "A"; var memento = originator.CreateMemento(); originator.State = "B"; originator.RestoreMemento(memento); Assert.IsTrue(originator.State == "A"); } [TestMethod] public void Observer_Test() { var sub = new Subject(); var obsA = new ObserverA(sub); var obsB = new ObserverB(sub); sub.State = "Mike"; var resA = obsA.State; var resB = obsB.State; Assert.IsTrue(resA.Contains(sub.State)); Assert.IsTrue(resB.Contains(sub.State)); } [TestMethod] public void State_Test() { var context = new DesignPatternsLib.BehaviouralPatterns.State.Context(); context.State = new DesignPatternsLib.BehaviouralPatterns.State.StateA(); context.Request(); Assert.IsNotNull(context.State as DesignPatternsLib.BehaviouralPatterns.State.StateB); context.Request(); Assert.IsNotNull(context.State as DesignPatternsLib.BehaviouralPatterns.State.StateA); } [TestMethod] public void Strategy_Test() { var client = new StrategyClient(); client.NumA = 5; client.NumB = 5; client.Strategy = new Suma(); var res = client.CallAlgorithm(); Assert.IsTrue(res == 10); client.Strategy = new Multiplicacion(); res = client.CallAlgorithm(); Assert.IsTrue(res == 25); } [TestMethod] public void TemplateMethod_Test() { var alg = new AlgorithmA(2, 3); var res = alg.TemplateMethod(); Assert.AreEqual(res, 8); } [TestMethod] public void Visitor_Test() { var structure = new Structure(); var e1 = new Element01() { State=0}; var e2 = new Element02() { State =1}; var v1 = new VisitorA(); var v2 = new VisitorB(); structure.Elements.Add(e1); structure.Elements.Add(e2); structure.Accept(v1); Assert.IsTrue(e1.State == 2 && e2.State == 3); structure.Accept(v2); Assert.IsTrue(e1.State == 12 && e2.State == 13); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.BehaviouralPatterns.Interpreter { public abstract class ExpressionBase { public abstract string Interpret(Context context); } } <file_sep>using System; namespace DesignPatternsLib.StructuralPatterns.Facade { internal class ClassB { internal string MethodB() { return "ClassB"; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.CreationalPatterns.FactoryMethod { public class ConcreteFactory : FactoryBase { public override ProductBase ProductFactoryMethod() { return new ConcreteProduct(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.BehaviouralPatterns.Mediator { public class Colleague : ColleagueBase { public Colleague(MediatorBase mediator) : base(mediator) { } public string LastMessage { get; set; } public override string Recv(string msg) { LastMessage = msg; return msg; } public override void Send() { _mediator.SendMesage(this); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLib.StructuralPatterns.Adapter { public class Adapter : ITarget { Adaptee _adaptee; public Adapter(Adaptee adaptee) { _adaptee = adaptee; } public string MethodA() { return _adaptee.MethodB().ToString(); } } }
2948fae813038434aeb4620cce40fdebc1d9e631
[ "C#" ]
70
C#
MiguelArteagaOrozco/DesignPatterns
05942e361d60742aae82cbbbbac8a8e95df71566
c95f35c92cd492c13a64aa3c40b3a10924220ba6
refs/heads/master
<file_sep>package de.wusel.wusellab.game; public class Game { private final Room room = new Room(800, 600); private final Player player1 = new Player(Position.at(0, 50)); private final Player player2 = new Player(Position.at(50, 0)); private final Area goal = new Area(700,500,100,100); public Game() { } public synchronized void step() { updatePlayer(player1); updatePlayer(player2); } private void updatePlayer(Player player) { Position newPosition = player.calculateNewPosition(); if (room.contains(newPosition)) { player.setPosition(newPosition); } } public synchronized void addPlayerDirection(int playerIndex, Direction direction) { getPlayer(playerIndex).addActiveDirection(direction); } public synchronized void removePlayerDirection(int playerIndex, Direction direction) { getPlayer(playerIndex).removeActiveDirection(direction); } private Player getPlayer(int playerIndex) { if (playerIndex == 1) { return player1; } if (playerIndex == 2) { return player2; } throw new IllegalArgumentException("Player " + playerIndex + " does not exist."); } public Room getRoom() { return room; } public Area getGoal() { return goal; } public Player getPlayer1() { return player1; } public Player getPlayer2() { return player2; } } <file_sep>rootProject.name = 'wusellab' <file_sep>package de.wusel.wusellab; public class ApplicationTest { } <file_sep>plugins { id 'java' } group 'de.wusel' version '1.0' sourceCompatibility = 1.10 repositories { mavenCentral() } ext { gdxVersion = '1.9.8' } dependencies { compile "com.badlogicgames.gdx:gdx:$gdxVersion" compile "com.badlogicgames.gdx:gdx-tools:$gdxVersion" compile "com.badlogicgames.gdx:gdx-box2d:$gdxVersion" compile "com.badlogicgames.gdx:gdx-backend-lwjgl:$gdxVersion" compile "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-desktop" compile "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-desktop" testCompile group: 'junit', name: 'junit', version: '4.12' } <file_sep>package de.wusel.wusellab.game; public class Area { private int x; private int y; private int width; private int height; public Area(int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width; this.height = height; } public int getX() { return x; } public int getY() { return y; } public int getWidth() { return width; } public int getHeight() { return height; } public boolean containsPoint(Position position) { return x <= position.getX() && position.getX() <= x + width && y <= position.getY() && position.getY() <= y + height; } } <file_sep>package de.wusel.wusellab; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.backends.lwjgl.LwjglApplication; import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; import de.wusel.wusellab.game.Game; import de.wusel.wusellab.input.PlayerInputHandler; import de.wusel.wusellab.render.GdxGameRenderer; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class Application { private static ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); public static void main(String[] args) { Game game = new Game(); LwjglApplicationConfiguration configuration = new LwjglApplicationConfiguration(); configuration.width = 800; configuration.height = 600; new LwjglApplication(new GdxGameRenderer(game), configuration); Gdx.input.setInputProcessor(new PlayerInputHandler(game)); executorService.scheduleWithFixedDelay(new GameStepper(game), 0, 30, TimeUnit.MILLISECONDS); } private static class GameStepper implements Runnable { private Game game; public GameStepper(Game game) { this.game = game; } @Override public void run() { game.step(); } } } <file_sep>package de.wusel.wusellab.game; public class Room { private final int width; private final int height; public Room(int width, int height) { this.width = width; this.height = height; } public int getWidth() { return width; } public int getHeight() { return height; } public boolean contains(Position position) { int x = position.getX(); int y = position.getY(); return 0 <= x && x <= width && 0 <= y && y <= height; } }
07fbf6cae4ae38d8fa6c7be00a9e6d49c1db1074
[ "Java", "Gradle" ]
7
Java
simonhampe/wusellab
5b80cd33112e11abb533c37b067f2f6d0b5f1893
7a6e017cc3094f709c9dac5cba2982714aa813cd
refs/heads/main
<repo_name>Davide01/language-classification<file_sep>/app/lang_model/utils.py def map_language_code(language_code: str) -> str: languages = { "da": "Danish", "sv": "Swedish", "no": "Norwegian" } if language_code not in languages: raise ValueError("Language not supported") return languages[language_code]<file_sep>/app/lang_model/recognizer.py import os import torch import torch.nn as nn from lang_model import DATA_PATH from lang_model.model import LangModel class LangRecognizer: def __init__(self, vocab_size: int, name: str) -> None: self.path = os.path.join(DATA_PATH, "models", name) self.vocab_size = vocab_size self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") self.__load_model() def __load_model(self) -> None: models = list(filter(lambda x: x.endswith(".pt"), os.listdir(self.path))) if len(models) == 0: raise ValueError("Wrong path.") state_dict = torch.load(os.path.join(self.path, models[0]), map_location=torch.device(self.device)) self.model = LangModel(self.vocab_size) self.model.load_state_dict(state_dict) self.model.eval() def predict(self, data) -> str: # Convert to tensor input = torch.Tensor(data).long() # Add batch and input to model output = self.model(input.unsqueeze(0)) # Get outputs _, pred = torch.max(output["out"].detach(), 1) # Convert to Language name lang_code = int(pred.detach().numpy()[0]) return lang_code <file_sep>/download_data.py import os import wikipediaapi as wikiapi import click DATA_DIR = os.path.join("app", "lang_model", "data") class WikiDataDownloader: def __init__(self, country: str, topic: str): self.country = country self.topic = topic self.wiki = wikiapi.Wikipedia(country) self.__set_folder(country=country) def __set_folder(self, country: str): self.folder_path = os.path.join(DATA_DIR, country) os.makedirs(self.folder_path, exist_ok=True) def _download_for_country(self, categorymembers, level=0, max_level=1): for c in categorymembers.values(): if c.ns == wikiapi.Namespace.CATEGORY and level < max_level: self._download_for_country( c.categorymembers, level=level + 1, max_level=max_level ) self._download_and_save(c.title) def _download_and_save(self, title): page = self.wiki.page(title) path = os.path.join(self.folder_path, f"{title.replace('/', '')}.txt") if os.path.exists(path): return try: with open(path, "w") as file: print(title) file.write(page.text) except OSError as e: print(f"Error downloading {title}. {e.args}") def download(self): cat = self.wiki.page(f"Category:{self.topic}") print(f"Category: {self.topic}") self._download_for_country(cat.categorymembers) @click.command() @click.option("-c", "--country", type=str, prompt="Enter country code (da/sv/no)") @click.option("-t", "--topic", type=str, prompt="Enter topic title") def main(country: str, topic: str): downloader = WikiDataDownloader(country=country, topic=topic) downloader.download() if __name__ == "__main__": main() <file_sep>/requirements.txt pandas numpy nltk torch jupyter wikipedia-api click tqdm tables sklearn fastapi uvicorn<file_sep>/app/lang_model/recognize.py """This class is responsible for recognizing the language. It holds the vocabulary, lookup table, encoder and the recognizer.""" import os import pickle import nltk import re import numpy as np from typing import List from sklearn import preprocessing from lang_model import VOCAB_PATH, ENCODER_PATH from lang_model.recognizer import LangRecognizer from lang_model.utils import map_language_code class RecognizeLang: def __init__(self, model_name: str = "lstm") -> None: # Vocalbulary self.__load_vocab() # Lookup table self.__construct_lookup() self.model = LangRecognizer(vocab_size=len(self.w2i), name=model_name) self.__load_encoder() def __load_vocab(self): path = os.path.join(VOCAB_PATH, "vocab.data") with open(path, "rb") as filehandle: self.vocab = pickle.load(filehandle) def __construct_lookup(self): self.w2i = {word: i for i, word in enumerate(self.vocab)} def __load_encoder(self): self.label_encoder = preprocessing.LabelEncoder() self.label_encoder.classes_ = np.load(os.path.join(ENCODER_PATH, "encoder_classes.npy"), allow_pickle=True) def recognize(self, text: str): # Lowercase and remove numbers text = re.sub(r"\d", "", text.lower()) tokens = self._tokenize(text=text) # Get indexes from the vocalbulary input = [self.w2i[token] for token in tokens if token in self.w2i] # If none of the unput words are in the vocabulary, return error if input is None or len(input) == 0: raise ValueError("Words not recognized.") lang_index = self.model.predict(input) language_code = self.label_encoder.inverse_transform([lang_index]) return map_language_code(language_code[0]) @staticmethod def _tokenize(text: str) -> List[str]: words = nltk.word_tokenize(text) tokens = [word for word in words if word.isalnum()] return tokens <file_sep>/app/lang_model/__init__.py import os PROJECT_PATH = os.path.dirname(os.path.abspath(__file__)) DATA_PATH = os.path.join(PROJECT_PATH, "data") VOCAB_PATH = os.path.join(DATA_PATH, "vocab") ENCODER_PATH = os.path.join(DATA_PATH, "encoder")<file_sep>/app/main.py from fastapi import FastAPI from lang_model.recognize import RecognizeLang app = FastAPI() @app.get( "/lang", summary="Recognizes the language of the provided text.", response_description="Language of the text", ) def language(text: str): try: recognize = RecognizeLang(model_name="lstm") language = recognize.recognize(text) return str(language) except ValueError as ve: return ve.args<file_sep>/app/lang_model/model.py import torch import torch.nn as nn from torch.nn.functional import softmax class LangModel(nn.Module): def __init__(self, vocab_size): super(LangModel, self).__init__() self.embeddings = nn.Embedding(vocab_size, 64) self.rnn_1 = nn.LSTM( input_size=64, hidden_size=100, num_layers=2, bidirectional=True, batch_first=False, ) self.l_out = nn.Sequential( nn.Linear(400, 200), nn.Dropout(0.2), nn.ReLU(inplace=True), nn.Linear(200, 64), nn.ReLU(inplace=True), nn.BatchNorm1d(64), nn.Linear(64, 3), ) def forward(self, x): out = {} # get embeddings x = self.embeddings(x) # output, hidden state x, _ = self.rnn_1(x) x = torch.cat((torch.mean(x, dim=0), torch.max(x, dim=0)[0]), dim=1) # classify out["out"] = softmax(self.l_out(x), dim=1) return out<file_sep>/README.md # Scandinavian language classifier ## Environment For development I used the anaconda environment manager. ```bash conda create --name lan_wire python==3.7 conda activate lan_wire pip install -r requirements.txt ``` ## Data As data source the danish, swedish and norwegian wikipedia was used. The texts were downloaded using their API. A python wikipedia wrapper was used for easier use in python. The data can be downloaded running the download_data.py script. ```bash python download_data.py ``` You must specify the language code (da/sv/no) and the title of the topic for which the data should be downloaded. The title must be specified in the language you want to download for. For the training data the Politics and Nature title was used. For training the model 81000 data samples were used, which was divided into train and test set. The constructed vocabulary consisted of 164700 words. The more topics and data you download the bigger the vocalbulary will be, thus the more accurate predictions you will get. ## Preprocessing The data preprocessing is part of the preprocess.ipynb jupyter notebook. The preprocessing steps taken: 1. New line signs were removed (\n) 2. The texts were divided into sentences 3. All the text was lowercased 4. All sentences were divided into words (To encode as embeddings) 5. Only alphanumeric characters were used Removing stop words and stemming was also considered. The data was divided into train and test set in ratio 80%/20%. ## Model development The pytorch framework was used for model development. A two layer LSTM network with three feed forward layers on the top was developed. Batchnorm and Dropout was used to avoid overfitting. ReLU was used as activation function between the layers and softmax after the last layer to distribute the probabilities across the labels. A vocabulary was constructed from the train and test data in order to encode the input to numeric values. A lookup table was constructed to get the indexes from the vocabulary. Embedding layer was used as first layer in the network. ## Training a model The model was trained for 50 epochs with batch size 72 and learning rate 0.0005. Adam was used as optimization algorithm. CrossEntropy was used as loss function. After each epoch a validation was performed, where the loss and the accuracy of the network was calculated. In every validation the accuracy is compared to the current best model and if it's more, the weights are saved. The checkpoints of the models will are saved in ```bash app/lang_model/data/models/{modelname}/{accuracy}_.pt. ``` More details can be find in the notebook modelling.py. The highest accuracy achieved was 91.3 %. Of course, this can be further tuned, with improving the data, hyperparameter tuning and achitecture tuning. ## Rest API The trained model is exposed via a REST API. The rest api was developed using the fastapi framework. The application runs on uvicorn. To run the app: ```bash cd app uvicorn main:app --reload ``` The requests are accepted at url "/lang" and must contain a url parameter "text" with a text in ont of the three languages (danish, swedish or norwegian). The return will contain the language of the text. The implementation can be found in the app/lang_model folder, while the API is in the main.py file. ## Running from docker The application was dockerized. To build the container: ```bash docker build -t lan_wire . ``` To run the app: ```bash docker run -d --name lan_wire -p 80:80 lan_wire ``` The app will be served at "http://127.0.0.1/lang?text={yourtexttotranslate}" <file_sep>/Dockerfile FROM tiangolo/uvicorn-gunicorn-fastapi:python3.7 COPY ./app /app COPY ./requirements.txt app/requirements.txt COPY ./punkt.py app/punkt.py RUN pip install -r app/requirements.txt RUN python app/punkt.py
ce25d18f07f39b2c270aa43ca7bbe0895490f092
[ "Markdown", "Python", "Text", "Dockerfile" ]
10
Python
Davide01/language-classification
68d480194a463a063f94326c86f31187299acf60
32b789a446f43ad6abe448bbf11cc06d445dff3f
refs/heads/master
<repo_name>ChewyChiyu/Street-Fighter<file_sep>/src/textureClass/Texture.java package textureClass; public class Texture { public static void loadDhalsimTextures(){ new DhalsimTexture(); } public static void loadRyuTextures(){ new RyuTexture(); } public static void loadEHondaTextures(){ new EHondaTexture(); } public static void loadBlankaTextures(){ new BlankaTexture(); } public static void loadMapTextures(){ new MapTexture(); } public static void loadGlobalTextures(){ new GlobalTextures(); } public static void loadDeeJayTextures(){ new DeeJayTexture(); } } <file_sep>/src/textureClass/EHondaTexture.java package textureClass; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; public class EHondaTexture extends Texture{ //EHonda CHARACTER SPRITES RIGHT public static BufferedImage[] idleEHondaRight = new BufferedImage[4]; public static BufferedImage[] walkEHondaRight = new BufferedImage[4]; public static BufferedImage[] verticalJumpEHondaRight = new BufferedImage[4]; public static BufferedImage[] diagonalJumpEHondaRight = new BufferedImage[4]; public static BufferedImage[] punchEHondaRight = new BufferedImage[3]; public static BufferedImage[] kickEHondaRight = new BufferedImage[3]; public static BufferedImage[] idleSneakEHondaRight = new BufferedImage[2]; public static BufferedImage[] sneakpunchEHondaRight = new BufferedImage[7]; public static BufferedImage[] sneakkickEHondaRight = new BufferedImage[5]; public static BufferedImage[] aerialkickEHondaRight = new BufferedImage[3]; public static BufferedImage[] speicalEHondaRight = new BufferedImage[6]; public static BufferedImage[] EHondaTorsoHitRight = new BufferedImage[3]; public static BufferedImage[] EHondaHeadHitRight = new BufferedImage[2]; public static BufferedImage[] knockDownEHondaRight = new BufferedImage[8]; public static BufferedImage[] defeatEHondaRight = new BufferedImage[5]; //END OF EHonda CHARACTER SPRITES RIGHT //EHonda CHARACTER SPRITES LEFT public static BufferedImage[] idleEHondaLeft = new BufferedImage[4]; public static BufferedImage[] walkEHondaLeft = new BufferedImage[4]; public static BufferedImage[] verticalJumpEHondaLeft = new BufferedImage[4]; public static BufferedImage[] diagonalJumpEHondaLeft = new BufferedImage[4]; public static BufferedImage[] punchEHondaLeft = new BufferedImage[3]; public static BufferedImage[] kickEHondaLeft = new BufferedImage[3]; public static BufferedImage[] idleSneakEHondaLeft = new BufferedImage[2]; public static BufferedImage[] sneakpunchEHondaLeft = new BufferedImage[7]; public static BufferedImage[] sneakkickEHondaLeft = new BufferedImage[5]; public static BufferedImage[] aerialkickEHondaLeft = new BufferedImage[3]; public static BufferedImage[] speicalEHondaLeft = new BufferedImage[6]; public static BufferedImage[] EHondaTorsoHitLeft = new BufferedImage[3]; public static BufferedImage[] EHondaHeadHitLeft = new BufferedImage[2]; public static BufferedImage[] knockDownEHondaLeft = new BufferedImage[8]; public static BufferedImage[] defeatEHondaLeft = new BufferedImage[5]; //END OF EHonda CHARACTER SPRITES LEFT protected EHondaTexture(){ loadRight(); loadLeft(); } void loadLeft(){ try{ final int xStart = 1457; BufferedImage EHondaSpriteSheetLeft = ImageIO.read(getClass().getResource("/imgs/characters/EHondaLeft.png")); idleEHondaLeft[0] = EHondaSpriteSheetLeft.getSubimage(xStart-6-60, 48, 60, 84); idleEHondaLeft[1] = EHondaSpriteSheetLeft.getSubimage(xStart-74-68, 52, 68, 82); idleEHondaLeft[2] = EHondaSpriteSheetLeft.getSubimage(xStart-152-62, 56, 62, 78); idleEHondaLeft[3] = EHondaSpriteSheetLeft.getSubimage(xStart-225-63, 52, 63, 80); walkEHondaLeft[0] = EHondaSpriteSheetLeft.getSubimage(xStart-298-74, 52, 74, 82); walkEHondaLeft[1] = EHondaSpriteSheetLeft.getSubimage(xStart-374-68, 52, 68, 80); walkEHondaLeft[2] = EHondaSpriteSheetLeft.getSubimage(xStart-444-64, 54, 64, 80); walkEHondaLeft[3] = EHondaSpriteSheetLeft.getSubimage(xStart-512-64, 54, 64, 78); punchEHondaLeft[0] = EHondaSpriteSheetLeft.getSubimage(xStart-6-72, 174, 72, 78); punchEHondaLeft[1] = EHondaSpriteSheetLeft.getSubimage(xStart-80-90, 176, 90, 76); punchEHondaLeft[2] = EHondaSpriteSheetLeft.getSubimage(xStart-174-70, 172, 70, 82); kickEHondaLeft[0] = EHondaSpriteSheetLeft.getSubimage(xStart-6-68, 294, 68, 82); kickEHondaLeft[1] = EHondaSpriteSheetLeft.getSubimage(xStart-80-94, 306, 94, 68); kickEHondaLeft[2] = EHondaSpriteSheetLeft.getSubimage(xStart-174-72, 293, 72, 84); verticalJumpEHondaLeft[0] = EHondaSpriteSheetLeft.getSubimage(xStart-586-64, 64, 64, 78); verticalJumpEHondaLeft[1] = EHondaSpriteSheetLeft.getSubimage(xStart-650-60, 50, 60, 82); verticalJumpEHondaLeft[2] = EHondaSpriteSheetLeft.getSubimage(xStart-712-56, 54, 56, 60); verticalJumpEHondaLeft[3] = EHondaSpriteSheetLeft.getSubimage(xStart-772-58, 50, 58, 86); // diagonalJumpEHondaLeft[0] = EHondaSpriteSheetLeft.getSubimage(834, 64, 62, 68); // diagonalJumpEHondaLeft[0] = EHondaSpriteSheetLeft.getSubimage(846, 7, 80, 125); diagonalJumpEHondaLeft[0] = EHondaSpriteSheetLeft.getSubimage(xStart-978-66, 32, 66, 76); diagonalJumpEHondaLeft[1] = EHondaSpriteSheetLeft.getSubimage(xStart-1044-56, 34, 56, 62); diagonalJumpEHondaLeft[2] = EHondaSpriteSheetLeft.getSubimage(xStart-1098-72, 24, 72, 88); diagonalJumpEHondaLeft[3] = EHondaSpriteSheetLeft.getSubimage(xStart-1166-76, 24, 76, 90); //diagonalJumpEHondaLeft[6] = EHondaSpriteSheetLeft.getSubimage(1236, 18, 82, 114); idleSneakEHondaLeft[0] = EHondaSpriteSheetLeft.getSubimage(xStart-1324-66, 64, 66, 70); idleSneakEHondaLeft[1] = EHondaSpriteSheetLeft.getSubimage(xStart-1390-60, 70, 60, 64); sneakpunchEHondaLeft[0] = EHondaSpriteSheetLeft.getSubimage(xStart-714-74, 306, 74, 70); sneakpunchEHondaLeft[1] = EHondaSpriteSheetLeft.getSubimage(xStart-798-94, 312, 94, 64); sneakpunchEHondaLeft[2] = EHondaSpriteSheetLeft.getSubimage(xStart-902-78, 314, 78, 62); sneakpunchEHondaLeft[3] = EHondaSpriteSheetLeft.getSubimage(xStart-988-74, 304, 74, 70); sneakpunchEHondaLeft[4] = EHondaSpriteSheetLeft.getSubimage(xStart-1078-74, 312, 74, 62); sneakpunchEHondaLeft[5] = EHondaSpriteSheetLeft.getSubimage(xStart-1162-90, 312, 90, 64); sneakpunchEHondaLeft[6] = EHondaSpriteSheetLeft.getSubimage(xStart-1256-72, 310, 72, 66); sneakkickEHondaLeft[0] = EHondaSpriteSheetLeft.getSubimage(xStart-400-66, 402, 66, 70); sneakkickEHondaLeft[1] = EHondaSpriteSheetLeft.getSubimage(xStart-472-86, 402, 86, 74); sneakkickEHondaLeft[2] = EHondaSpriteSheetLeft.getSubimage(xStart-556-58, 407, 58, 67); sneakkickEHondaLeft[3] = EHondaSpriteSheetLeft.getSubimage(xStart-628-68, 407, 68, 63); sneakkickEHondaLeft[4] = EHondaSpriteSheetLeft.getSubimage(xStart-746-48, 409, 48, 64); aerialkickEHondaLeft[0] = EHondaSpriteSheetLeft.getSubimage(xStart-815-(872-815), 408, (872-815), (463-408)); aerialkickEHondaLeft[1] = EHondaSpriteSheetLeft.getSubimage(xStart-876-(965-876),402,(965-876),(470-402)); aerialkickEHondaLeft[2] = EHondaSpriteSheetLeft.getSubimage(xStart-964-(1031-964), 399, (1031-964), (463-399)); EHondaTorsoHitLeft[0] = EHondaSpriteSheetLeft.getSubimage(xStart-6-70, 919, 70, 75); EHondaTorsoHitLeft[1] = EHondaSpriteSheetLeft.getSubimage(xStart-80-68, 924, 68, 69); EHondaTorsoHitLeft[2] = EHondaSpriteSheetLeft.getSubimage(xStart-150-66, 916, 66, 75); EHondaHeadHitLeft[0] = EHondaSpriteSheetLeft.getSubimage(xStart-232-60, 907, 60, 87); EHondaHeadHitLeft[1] = EHondaSpriteSheetLeft.getSubimage(xStart-292-58, 910, 58, 86); knockDownEHondaLeft[0] = EHondaSpriteSheetLeft.getSubimage(xStart-454-68, 900, 68, 87); knockDownEHondaLeft[1] = EHondaSpriteSheetLeft.getSubimage(xStart-526-70, 901, 70, 86); knockDownEHondaLeft[2] = EHondaSpriteSheetLeft.getSubimage(xStart-598-72, 899, 72, 86); knockDownEHondaLeft[3] = EHondaSpriteSheetLeft.getSubimage(xStart-664-98, 950, 98, 48); knockDownEHondaLeft[4] = EHondaSpriteSheetLeft.getSubimage(xStart-760-72, 912, 72, 80); knockDownEHondaLeft[5] = EHondaSpriteSheetLeft.getSubimage(xStart-846-54, 883, 54, 79); knockDownEHondaLeft[6] = EHondaSpriteSheetLeft.getSubimage(xStart-904-74, 881, 74, 72); knockDownEHondaLeft[7] = EHondaSpriteSheetLeft.getSubimage(xStart-984-66, 927, 66, 64); defeatEHondaLeft[0] = EHondaSpriteSheetLeft.getSubimage(xStart-8-70, 1049, 70, 85); defeatEHondaLeft[1] = EHondaSpriteSheetLeft.getSubimage(xStart-82-66, 1052, 66, 81); defeatEHondaLeft[2] = EHondaSpriteSheetLeft.getSubimage(xStart-148-96, 1094, 96, 48); defeatEHondaLeft[3] = EHondaSpriteSheetLeft.getSubimage(xStart-240-68, 1051, 68, 82); defeatEHondaLeft[4] = EHondaSpriteSheetLeft.getSubimage(xStart-312-88, 1089, 88, 51); speicalEHondaLeft[0] = EHondaSpriteSheetLeft.getSubimage(xStart-8-105,655,105,73); speicalEHondaLeft[1] = EHondaSpriteSheetLeft.getSubimage(xStart-121-81,642,81,86); speicalEHondaLeft[2] = EHondaSpriteSheetLeft.getSubimage(xStart-212-96,655,96,73); speicalEHondaLeft[3] = EHondaSpriteSheetLeft.getSubimage(xStart-315-86,655,86,73); speicalEHondaLeft[4] = EHondaSpriteSheetLeft.getSubimage(xStart-411-104,642,104,86); speicalEHondaLeft[5] = EHondaSpriteSheetLeft.getSubimage(xStart-524-74,655,74,73); }catch(Exception e) { } } void loadRight(){ try{ BufferedImage EHondaSpriteSheetRight = ImageIO.read(getClass().getResource("/imgs/characters/EHondaRight.png")); idleEHondaRight[0] = EHondaSpriteSheetRight.getSubimage(6, 48, 60, 84); idleEHondaRight[1] = EHondaSpriteSheetRight.getSubimage(74, 52, 68, 82); idleEHondaRight[2] = EHondaSpriteSheetRight.getSubimage(152, 56, 62, 78); idleEHondaRight[3] = EHondaSpriteSheetRight.getSubimage(225, 52, 63, 80); walkEHondaRight[0] = EHondaSpriteSheetRight.getSubimage(298, 52, 74, 82); walkEHondaRight[1] = EHondaSpriteSheetRight.getSubimage(374, 52, 68, 80); walkEHondaRight[2] = EHondaSpriteSheetRight.getSubimage(444, 54, 64, 80); walkEHondaRight[3] = EHondaSpriteSheetRight.getSubimage(512, 54, 64, 78); punchEHondaRight[0] = EHondaSpriteSheetRight.getSubimage(6, 174, 72, 78); punchEHondaRight[1] = EHondaSpriteSheetRight.getSubimage(80, 176, 90, 76); punchEHondaRight[2] = EHondaSpriteSheetRight.getSubimage(174, 172, 70, 82); kickEHondaRight[0] = EHondaSpriteSheetRight.getSubimage(6, 294, 68, 82); kickEHondaRight[1] = EHondaSpriteSheetRight.getSubimage(80, 306, 94, 68); kickEHondaRight[2] = EHondaSpriteSheetRight.getSubimage(174, 293, 72, 84); verticalJumpEHondaRight[0] = EHondaSpriteSheetRight.getSubimage(586, 64, 64, 78); verticalJumpEHondaRight[1] = EHondaSpriteSheetRight.getSubimage(650, 50, 60, 82); verticalJumpEHondaRight[2] = EHondaSpriteSheetRight.getSubimage(712, 54, 56, 60); verticalJumpEHondaRight[3] = EHondaSpriteSheetRight.getSubimage(772, 50, 58, 86); // diagonalJumpEHondaRight[0] = EHondaSpriteSheetRight.getSubimage(834, 64, 62, 68); // diagonalJumpEHondaRight[0] = EHondaSpriteSheetRight.getSubimage(846, 7, 80, 125); diagonalJumpEHondaRight[0] = EHondaSpriteSheetRight.getSubimage(978, 32, 66, 76); diagonalJumpEHondaRight[1] = EHondaSpriteSheetRight.getSubimage(1044, 34, 56, 62); diagonalJumpEHondaRight[2] = EHondaSpriteSheetRight.getSubimage(1098, 24, 72, 88); diagonalJumpEHondaRight[3] = EHondaSpriteSheetRight.getSubimage(1166, 24, 76, 90); //diagonalJumpEHondaRight[6] = EHondaSpriteSheetRight.getSubimage(1236, 18, 82, 114); idleSneakEHondaRight[0] = EHondaSpriteSheetRight.getSubimage(1324, 64, 66, 70); idleSneakEHondaRight[1] = EHondaSpriteSheetRight.getSubimage(1390, 70, 60, 64); sneakpunchEHondaRight[0] = EHondaSpriteSheetRight.getSubimage(714, 306, 74, 70); sneakpunchEHondaRight[1] = EHondaSpriteSheetRight.getSubimage(798, 312, 94, 64); sneakpunchEHondaRight[2] = EHondaSpriteSheetRight.getSubimage(902, 314, 78, 62); sneakpunchEHondaRight[3] = EHondaSpriteSheetRight.getSubimage(988, 304, 74, 70); sneakpunchEHondaRight[4] = EHondaSpriteSheetRight.getSubimage(1078, 312, 74, 62); sneakpunchEHondaRight[5] = EHondaSpriteSheetRight.getSubimage(1162, 312, 90, 64); sneakpunchEHondaRight[6] = EHondaSpriteSheetRight.getSubimage(1256, 310, 72, 66); sneakkickEHondaRight[0] = EHondaSpriteSheetRight.getSubimage(400, 402, 66, 70); sneakkickEHondaRight[1] = EHondaSpriteSheetRight.getSubimage(472, 402, 86, 74); sneakkickEHondaRight[2] = EHondaSpriteSheetRight.getSubimage(556, 407, 58, 67); sneakkickEHondaRight[3] = EHondaSpriteSheetRight.getSubimage(628, 407, 68, 63); sneakkickEHondaRight[4] = EHondaSpriteSheetRight.getSubimage(746, 409, 48, 64); aerialkickEHondaRight[0] = EHondaSpriteSheetRight.getSubimage(815, 408, (872-815), (463-408)); aerialkickEHondaRight[1] = EHondaSpriteSheetRight.getSubimage(876,402,(965-876),(470-402)); aerialkickEHondaRight[2] = EHondaSpriteSheetRight.getSubimage(964, 399, (1031-964), (463-399)); EHondaTorsoHitRight[0] = EHondaSpriteSheetRight.getSubimage(6, 919, 70, 75); EHondaTorsoHitRight[1] = EHondaSpriteSheetRight.getSubimage(80, 924, 68, 69); EHondaTorsoHitRight[2] = EHondaSpriteSheetRight.getSubimage(150, 916, 66, 75); EHondaHeadHitRight[0] = EHondaSpriteSheetRight.getSubimage(232, 907, 60, 87); EHondaHeadHitRight[1] = EHondaSpriteSheetRight.getSubimage(292, 910, 58, 86); knockDownEHondaRight[0] = EHondaSpriteSheetRight.getSubimage(454, 900, 68, 87); knockDownEHondaRight[1] = EHondaSpriteSheetRight.getSubimage(526, 901, 70, 86); knockDownEHondaRight[2] = EHondaSpriteSheetRight.getSubimage(598, 899, 72, 86); knockDownEHondaRight[3] = EHondaSpriteSheetRight.getSubimage(664, 950, 98, 48); knockDownEHondaRight[4] = EHondaSpriteSheetRight.getSubimage(760, 912, 72, 80); knockDownEHondaRight[5] = EHondaSpriteSheetRight.getSubimage(846, 883, 54, 79); knockDownEHondaRight[6] = EHondaSpriteSheetRight.getSubimage(904, 881, 74, 72); knockDownEHondaRight[7] = EHondaSpriteSheetRight.getSubimage(984, 927, 66, 64); defeatEHondaRight[0] = EHondaSpriteSheetRight.getSubimage(8, 1049, 70, 85); defeatEHondaRight[1] = EHondaSpriteSheetRight.getSubimage(82, 1052, 66, 81); defeatEHondaRight[2] = EHondaSpriteSheetRight.getSubimage(148, 1094, 96, 48); defeatEHondaRight[3] = EHondaSpriteSheetRight.getSubimage(240, 1051, 68, 82); defeatEHondaRight[4] = EHondaSpriteSheetRight.getSubimage(312, 1089, 88, 51); speicalEHondaRight[0] = EHondaSpriteSheetRight.getSubimage(8,655,105,73); speicalEHondaRight[1] = EHondaSpriteSheetRight.getSubimage(121,642,81,86); speicalEHondaRight[2] = EHondaSpriteSheetRight.getSubimage(212,655,96,73); speicalEHondaRight[3] = EHondaSpriteSheetRight.getSubimage(315,655,86,73); speicalEHondaRight[4] = EHondaSpriteSheetRight.getSubimage(411,642,104,86); speicalEHondaRight[5] = EHondaSpriteSheetRight.getSubimage(524,655,74,73); }catch(Exception e){e.printStackTrace(); } } } <file_sep>/src/gameClass/CharacterSelectLauncher.java package gameClass; import java.awt.CardLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.image.BufferedImage; import javax.swing.AbstractAction; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.KeyStroke; import textureClass.EHondaTexture; import textureClass.MapTexture; import textureClass.RyuTexture; import textureClass.Texture; @SuppressWarnings("serial") public class CharacterSelectLauncher extends JPanel { private GameType g; private Character selectedCharacter = CharacterInfo.RYU.getCharacter(true,false); private Character selectedCharacter2 = CharacterInfo.RYU.getCharacter(false,false); private CharacterInfo[] characterList = {CharacterInfo.RYU,CharacterInfo.EHONDA,CharacterInfo.BLANKA,CharacterInfo.DEEJAY, CharacterInfo.DHALSIM}; private JFrame frame; private CardLayout cardLayout = new CardLayout(); private JPanel screen = new JPanel(cardLayout); boolean[] select = new boolean[characterList.length]; boolean[] select2 = new boolean[characterList.length]; protected CharacterSelectLauncher(GameType g){ this.g = g; select[0] = true; select2[0] = true; if(g.equals(GameType.FIGHT)){ getActionMap().put("LEFT", new AbstractAction(){ @Override public void actionPerformed(ActionEvent e) { for(int subIndex = 1; subIndex < characterList.length; subIndex++){ if(select2[subIndex]){ select2[subIndex] = false; select2[subIndex-1] = true; selectedCharacter2 = characterList[subIndex-1].getCharacter(false,false); repaint(); return; } } } }); getActionMap().put("RIGHT", new AbstractAction(){ @Override public void actionPerformed(ActionEvent e) { for(int subIndex = 0; subIndex < characterList.length-1; subIndex++){ if(select2[subIndex]){ select2[subIndex] = false; select2[subIndex+1] = true; selectedCharacter2 = characterList[subIndex+1].getCharacter(false,false); repaint(); return; } } } }); } panel(); keys(); repaint(); } void keys(){ getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("O"), "O"); getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("A"), "A"); getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("D"), "D"); getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("D"), "D"); getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke((char) KeyEvent.VK_LEFT, 0, false), "LEFT"); getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke((char) KeyEvent.VK_RIGHT, 0 , false), "RIGHT"); getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("ENTER"), "ENTER"); getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke((char) KeyEvent.VK_BACK_SPACE), "BACK"); getActionMap().put("BACK", new AbstractAction(){ @Override public void actionPerformed(ActionEvent e) { new StreetFighterLauncher(); frame.dispose(); } }); getActionMap().put("ENTER", new AbstractAction(){ @Override public void actionPerformed(ActionEvent e) { if(selectedCharacter == null || selectedCharacter2 == null){ return; } if(g.equals(GameType.TRAINING)){ switch((int)(Math.random()*characterList.length)){ case 0: selectedCharacter2 = CharacterInfo.RYU.getCharacter(false,true); break; case 1: selectedCharacter2 = CharacterInfo.EHONDA.getCharacter(false,true); break; case 2: selectedCharacter2 = CharacterInfo.BLANKA.getCharacter(false,true); break; case 3: selectedCharacter2 = CharacterInfo.DEEJAY.getCharacter(false,true); break; case 4: selectedCharacter2 = CharacterInfo.DHALSIM.getCharacter(false,true); break; } } new MapSelectLauncher(selectedCharacter,selectedCharacter2,g); frame.dispose(); } }); getActionMap().put("A", new AbstractAction(){ @Override public void actionPerformed(ActionEvent e) { for(int subIndex = 1; subIndex < characterList.length; subIndex++){ if(select[subIndex]){ select[subIndex] = false; select[subIndex-1] = true; selectedCharacter = characterList[subIndex-1].getCharacter(true,false); repaint(); return; } } } }); getActionMap().put("D", new AbstractAction(){ @Override public void actionPerformed(ActionEvent e) { for(int subIndex = 0; subIndex < characterList.length-1; subIndex++){ if(select[subIndex]){ select[subIndex] = false; select[subIndex+1] = true; selectedCharacter = characterList[subIndex+1].getCharacter(true,false); repaint(); return; } } } }); getActionMap().put("O", new AbstractAction(){ @Override public void actionPerformed(ActionEvent e) { cardLayout.next(screen); } }); } void panel(){ frame = new JFrame(); OptionLauncher.changePanel(screen, cardLayout); screen.add(this, null); screen.add(OptionLauncher.panel, null); frame.add(screen); this.setLayout(null); frame.setPreferredSize(new Dimension(Toolkit.getDefaultToolkit().getScreenSize())); frame.pack(); frame.setVisible(true); frame.setResizable(false); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); cardLayout.show(screen, null); } public void paintComponent(Graphics g){ super.paintComponent(g); g.drawImage(MapTexture.characterSelectBackground, 0, 0,Constants.SCREEN_WIDTH.getIntValue(),Constants.SCREEN_HEIGHT.getIntValue(), null); if(this.g.equals(GameType.TRAINING)){ drawTrainingSelect(g); }else if(this.g.equals(GameType.FIGHT)){ drawFightSelect(g); } } void drawFightSelect(Graphics g){ g.setFont(new Font("Arial",Font.BOLD,40)); int xBuffer = (int)(Constants.SCREEN_WIDTH.getIntValue()*.05); int yBuffer = (int)(Constants.SCREEN_HEIGHT.getIntValue()*.05); for(int subIndex = 0; subIndex < characterList.length; subIndex++){ Color c; if(select[subIndex]){ c = Color.BLACK; g.setColor(Color.RED); g.setFont(new Font("Aerial",Font.BOLD,30)); g.drawString("P1", xBuffer+50, yBuffer-10); }else{ c = Color.GRAY; } g.setColor(c); BufferedImage display = MapTexture.characterSelectSprites[subIndex]; g.drawImage(display, xBuffer, yBuffer, 100, 200,c, null); if(select[subIndex]){ g.drawImage(MapTexture.player1Selector, xBuffer, yBuffer, 100, 200, null); switch(characterList[subIndex]){ case EHONDA: display = MapTexture.characterSelectSprites[1]; break; case DEEJAY: display = MapTexture.characterSelectSprites[3]; break; case RYU: display = MapTexture.characterSelectSprites[0]; break; case BLANKA: display = MapTexture.characterSelectSprites[2]; break; case DHALSIM: display = MapTexture.characterSelectSprites[4]; break; default: break; } g.drawImage(display, 0, (int)(Constants.SCREEN_HEIGHT.getIntValue()*.3), 500, 500, null); } xBuffer+=110; //5 pixel buffer } xBuffer = (int)(Constants.SCREEN_WIDTH.getIntValue()*.4); yBuffer = (int)(Constants.SCREEN_HEIGHT.getIntValue()*.7); for(int subIndex = 0; subIndex < characterList.length; subIndex++){ Color c; if(select2[subIndex]){ c = Color.BLACK; g.setColor(Color.BLUE); g.setFont(new Font("Aerial",Font.BOLD,30)); g.drawString("P2", xBuffer+50, yBuffer-10); }else{ c = Color.GRAY; } g.setColor(c); BufferedImage display = MapTexture.characterSelectSpritesFlipped[subIndex]; g.drawImage(display, xBuffer, yBuffer, 100, 200,c, null); if(select2[subIndex]){ g.drawImage(MapTexture.player2Selector, xBuffer, yBuffer, 100, 200, null); switch(characterList[subIndex]){ case EHONDA: display = MapTexture.characterSelectSpritesFlipped[1]; break; case DEEJAY: display = MapTexture.characterSelectSpritesFlipped[3]; break; case RYU: display = MapTexture.characterSelectSpritesFlipped[0]; break; case BLANKA: display = MapTexture.characterSelectSpritesFlipped[2]; break; case DHALSIM: display = MapTexture.characterSelectSpritesFlipped[4]; break; default: break; } g.drawImage(display, (int)(Constants.SCREEN_WIDTH.getIntValue()*.7), 0, 500, 500, null); } xBuffer+=110; //5 pixel buffer } } void drawTrainingSelect(Graphics g){ g.setFont(new Font("Arial",Font.BOLD,40)); //g.drawString("FIGHT CHARACTER SELECT", (int)(Constants.SCREEN_WIDTH.getIntValue()*.1), (int)(Constants.SCREEN_HEIGHT.getIntValue()*.1)); int xBuffer = (int)(Constants.SCREEN_WIDTH.getIntValue()*.05); int yBuffer = (int)(Constants.SCREEN_HEIGHT.getIntValue()*.05); for(int subIndex = 0; subIndex < characterList.length; subIndex++){ Color c; if(select[subIndex]){ c = Color.BLACK; g.setColor(Color.RED); g.setFont(new Font("Aerial",Font.BOLD,30)); g.drawString("P1", xBuffer+50, yBuffer-10); }else{ c = Color.GRAY; } g.setColor(c); BufferedImage display = MapTexture.characterSelectSprites[subIndex]; g.drawImage(display, xBuffer, yBuffer, 100, 200,c, null); if(select[subIndex]){ g.drawImage(MapTexture.player1Selector, xBuffer, yBuffer, 100, 200, null); switch(characterList[subIndex]){ case EHONDA: display = MapTexture.characterSelectSprites[1]; break; case DEEJAY: display = MapTexture.characterSelectSprites[3]; break; case RYU: display = MapTexture.characterSelectSprites[0]; break; case BLANKA: display = MapTexture.characterSelectSprites[2]; break; case DHALSIM: display = MapTexture.characterSelectSprites[4]; break; default: break; } g.drawImage(display, 0, (int)(Constants.SCREEN_HEIGHT.getIntValue()*.3), 500, 500, null); } //g.drawImage(MapTexture.characterSelectSprites[index][subIndex], xBuffer, yBuffer, 200,200,c,null); xBuffer+=110; //5 pixel buffer } } } <file_sep>/src/gameClass/Projectile.java package gameClass; public abstract class Projectile extends GameObject { protected Projectile(int x, int y, int xVelo, int yVelo){ g = GameType.PROJECTILE; this.x = x; this.y = y; this.xVelo = xVelo; this.yVelo = yVelo; width = 100; height = 100; gravity = false; body = new HitBox(x,y,width,height); } } <file_sep>/src/gameClass/CharacterInfo.java package gameClass; import textureClass.BlankaTexture; import textureClass.EHondaTexture; import textureClass.RyuTexture; public enum CharacterInfo { //will change constant names when more characters are added RYU(1,RyuTexture.idleRyuLeft[0].getWidth()*5,RyuTexture.idleRyuLeft[0].getHeight()*5), EHONDA(2,EHondaTexture.idleEHondaLeft[0].getWidth()*5,EHondaTexture.idleEHondaLeft[0].getHeight()*5), BLANKA(3,BlankaTexture.idleBlankaLeft[0].getWidth()*5,BlankaTexture.idleBlankaLeft[0].getHeight()*5), DEEJAY(4,200,500), DHALSIM(5,200,500); private int location; private int height; private int width; private CharacterInfo(int loc, int width, int height){ location = loc; this.width = width; this.height = height; } int getWidth(){ return width; } int getHeight(){ return height; } int locationInCharSelect(){ return location; } Character getCharacter(boolean right, boolean automated){ switch(location){ case 1: return new Ryu(CharacterInfo.RYU,5,right,automated); case 2: return new EHonda(CharacterInfo.EHONDA,3,right,automated); case 3: return new Blanka(CharacterInfo.BLANKA,5,right,automated); case 4: return new DeeJay(CharacterInfo.DEEJAY,5,right,automated); case 5: return new Dhalsim(CharacterInfo.DHALSIM,5,right,automated); } return null; } public String toString(){ return ""+location; } } <file_sep>/README.md # Street-Fighter Cringe mode <file_sep>/src/gameClass/DeeJay.java package gameClass; import java.awt.Graphics; import java.awt.Image; import textureClass.DeeJayTexture; public class DeeJay extends Character { boolean right; protected DeeJay(CharacterInfo info, int speed, boolean right,boolean isAutomated) { super(CharacterInfo.DEEJAY, speed, right, isAutomated); this.right = right; if(right){ idle = DeeJayTexture.idleDeeJayRight; walk = DeeJayTexture.walkDeeJayRight; verticalJump = DeeJayTexture.verticalJumpDeeJayRight; diagonalJump = DeeJayTexture.diagonalJumpDeeJayRight; punch = DeeJayTexture.punchDeeJayRight; kick = DeeJayTexture.kickDeeJayRight; sneakPunch = DeeJayTexture.sneakpunchDeeJayRight; sneakKick = DeeJayTexture.sneakkickDeeJayRight; aerialKick = DeeJayTexture.aerialkickDeeJayRight; special = DeeJayTexture.speicalDeeJayRight; hitTorso = DeeJayTexture.DeeJayTorsoHitRight; idleSneak = DeeJayTexture.idleSneakDeeJayRight; hitHead = DeeJayTexture.DeeJayHeadHitRight; knockDown = DeeJayTexture.knockDownDeeJayRight; defeat = DeeJayTexture.defeatDeeJayRight; } if(!right){ idle = DeeJayTexture.idleDeeJayLeft; walk = DeeJayTexture.walkDeeJayLeft; verticalJump = DeeJayTexture.verticalJumpDeeJayLeft; diagonalJump = DeeJayTexture.diagonalJumpDeeJayLeft; punch = DeeJayTexture.punchDeeJayLeft; kick = DeeJayTexture.kickDeeJayLeft; sneakPunch = DeeJayTexture.sneakpunchDeeJayLeft; sneakKick = DeeJayTexture.sneakkickDeeJayLeft; aerialKick = DeeJayTexture.aerialkickDeeJayLeft; special = DeeJayTexture.speicalDeeJayLeft; hitTorso = DeeJayTexture.DeeJayTorsoHitLeft; idleSneak = DeeJayTexture.idleSneakDeeJayLeft; hitHead = DeeJayTexture.DeeJayHeadHitLeft; knockDown = DeeJayTexture.knockDownDeeJayLeft; defeat = DeeJayTexture.defeatDeeJayLeft; } } @Override void jump() { if(!inAir){ Thread jump = new Thread(new Runnable(){ public void run(){ for(int index = 0; index < 100; index++){ y -= 5; try{ Thread.sleep(1); }catch(Exception e) {} } } }); jump.start(); } } @Override public String toString() { return "DeeJay"; } @Override void punch() { if(!isAttacking){ Thread punch = new Thread(new Runnable(){ @Override public void run() { isPunching = true; punchIndex = 0; for(int index = 0; index < DeeJayTexture.punchDeeJayRight.length-1; index++){ punchIndex++; try{ Thread.sleep(100); }catch(Exception e) { } } isPunching = false; } }); punch.start(); } } @Override void kick() { if(!isAttacking){ Thread kick = new Thread(new Runnable(){ @Override public void run() { kickIndex = 0; isKicking = true; for(int index = 0; index < DeeJayTexture.kickDeeJayRight.length-1; index++){ kickIndex++; try{ Thread.sleep(40); }catch(Exception e) { } } isKicking = false; } }); kick.start(); } } @Override void special() { if(!isAttacking&&!isGettingKnockedDown){ Thread special = new Thread(new Runnable(){ @Override public void run() { isSpecial = true; specialIndex = 0; for(int index = 0; index < DeeJayTexture.speicalDeeJayRight.length-1; index++){ specialIndex++; try{ Thread.sleep(50); }catch(Exception e) { } } isSpecial = false; } }); special.start(); } } @Override void aerialPunch() { if(!isAttacking){ Thread aerialPunch = new Thread(new Runnable(){ public void run(){ isAerialPunching = true; sneakKickIndex = 0; for(int index = 0; index < DeeJayTexture.sneakkickDeeJayRight.length-1; index++){ sneakKickIndex++; try{ Thread.sleep(100); }catch(Exception e) { } } isAerialPunching = false; } }); aerialPunch.start(); } } @Override void aerialKick() { if(!isAttacking){ Thread aerialKick = new Thread(new Runnable(){ public void run(){ isAerialKicking = true; aerialKickIndex = 0; for(int index = 0; index < DeeJayTexture.aerialkickDeeJayRight.length-1; index++){ aerialKickIndex++; try{ Thread.sleep(200); }catch(Exception e) { } } isAerialKicking = false; } }); aerialKick.start(); } } @Override void sneakPunch() { if(!isAttacking){ Thread sneakPunch = new Thread(new Runnable(){ @Override public void run() { isLowPunching = true; sneakPunchIndex = 0; for(int index = 0; index < DeeJayTexture.sneakpunchDeeJayRight.length-1; index++){ sneakPunchIndex++; try{ Thread.sleep(100); }catch(Exception e) { } } isLowPunching = false; } }); sneakPunch.start(); } } @Override void sneakKick() { if(!isAttacking){ Thread sneakKick = new Thread(new Runnable(){ public void run(){ isLowKicking = true; sneakKickIndex = 0; for(int index = 0; index < DeeJayTexture.sneakkickDeeJayRight.length-1; index++){ sneakKickIndex++; try{ Thread.sleep(100); }catch(Exception e) { } } isLowKicking = false; } }); sneakKick.start(); } } @Override void stand() { isSneaking = false; } @Override void sneak() { isSneaking = true; } @Override void getHitTorso() { Thread gettingHit = new Thread(new Runnable(){ public void run(){ isGettingHitTorso = true; gettingHitTorsoIndex = 0; for(int index = 0; index < DeeJayTexture.DeeJayTorsoHitRight.length-1; index++){ gettingHitTorsoIndex++; try{ Thread.sleep(100); }catch(Exception e) { } } isGettingHitTorso = false; } }); gettingHit.start(); } @Override void getHitHead() { Thread gettingHit = new Thread(new Runnable(){ public void run(){ isGettingHitHead = true; gettingHitHeadIndex = 0; for(int index = 0; index < DeeJayTexture.DeeJayHeadHitRight.length-1; index++){ gettingHitHeadIndex++; try{ Thread.sleep(100); }catch(Exception e) { } } isGettingHitHead = false; } }); gettingHit.start(); } @Override void getKnockedDown() { Thread gettingKnocked = new Thread(new Runnable(){ public void run(){ isGettingKnockedDown = true; gettingKnockedDownIndex = 0; for(int index = 0; index < DeeJayTexture.knockDownDeeJayRight.length-1; index++){ gettingKnockedDownIndex++; try{ Thread.sleep(200); }catch(Exception e) { } } isGettingKnockedDown = false; } }); Thread knockBack = new Thread(new Runnable(){ public void run(){ for(int index = 0; index < 50; index++){ y -= Constants.GRAVITY.getIntValue(); if(!right){ setX(6); } else{ setX(-6); } try{ Thread.sleep(1); }catch(Exception e) { } } } }); knockBack.start(); gettingKnocked.start(); } @Override void defeated() { if(defeated){ return; } Thread defeat = new Thread(new Runnable(){ public void run(){ defeated = true; defeatedIndex = 0; for(int index = 0; index < DeeJayTexture.defeatDeeJayRight.length-1; index++){ defeatedIndex++; try{ Thread.sleep(200); }catch(Exception e) { } } } }); defeat.start(); } } <file_sep>/src/gameClass/GameType.java package gameClass; public enum GameType { TRAINING, FIGHT, PLAYER, PROJECTILE; } <file_sep>/src/gameClass/OptionLauncher.java package gameClass; import java.awt.CardLayout; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.KeyStroke; @SuppressWarnings("serial") class OptionPanel extends JPanel{ protected OptionPanel(){ super(); } public void paintComponent(Graphics g){ super.paintComponent(g); drawStrings(g); } void drawStrings(Graphics g){ g.setFont(new Font("Arial", Font.BOLD, 40)); g.setColor(Color.BLACK); g.fillRect(0, 0, Constants.SCREEN_WIDTH.getIntValue(), Constants.SCREEN_HEIGHT.getIntValue()); g.setColor(Color.WHITE); g.drawString("OPTIONS / CONTROLS", (int)(Constants.SCREEN_WIDTH.getIntValue()*.3), (int)(Constants.SCREEN_HEIGHT.getIntValue()*.2)); g.drawString("PAUSE : P", (int)(Constants.SCREEN_WIDTH.getIntValue()*.1), (int)(Constants.SCREEN_HEIGHT.getIntValue()*.3)); g.drawString("OPTIONS : O", (int)(Constants.SCREEN_WIDTH.getIntValue()*.1), (int)(Constants.SCREEN_HEIGHT.getIntValue()*.4)); g.drawString("PERV SCREEN : BACKSPACE", (int)(Constants.SCREEN_WIDTH.getIntValue()*.1), (int)(Constants.SCREEN_HEIGHT.getIntValue()*.5)); g.drawString("EXIT OPTIONS : A", (int)(Constants.SCREEN_WIDTH.getIntValue()*.1), (int)(Constants.SCREEN_HEIGHT.getIntValue()*.6)); } } @SuppressWarnings("serial") public class OptionLauncher{ static OptionPanel panel = new OptionPanel(); static JPanel panelMain; static CardLayout cardLayout; protected OptionLauncher(JPanel panel, CardLayout cardLayout){ OptionLauncher.cardLayout = cardLayout; panelMain = panel; keys(); } void keys(){ panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("A"), "A"); panel.getActionMap().put("A", new AbstractAction(){ @Override public void actionPerformed(ActionEvent e) { cardLayout.next(panelMain); } }); } static void changePanel(JPanel p, CardLayout c){ panelMain = p; cardLayout = c; } } <file_sep>/src/textureClass/BlankaTexture.java package textureClass; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; public class BlankaTexture extends Texture{ //Blanka CHARACTER SPRITES RIGHT public static BufferedImage[] idleBlankaRight = new BufferedImage[4]; public static BufferedImage[] walkBlankaRight = new BufferedImage[5]; public static BufferedImage[] verticalJumpBlankaRight = new BufferedImage[4]; public static BufferedImage[] diagonalJumpBlankaRight = new BufferedImage[8]; public static BufferedImage[] punchBlankaRight = new BufferedImage[3]; public static BufferedImage[] kickBlankaRight = new BufferedImage[3]; public static BufferedImage[] idleSneakBlankaRight = new BufferedImage[1]; public static BufferedImage[] sneakpunchBlankaRight = new BufferedImage[3]; public static BufferedImage[] sneakkickBlankaRight = new BufferedImage[3]; public static BufferedImage[] aerialkickBlankaRight = new BufferedImage[3]; public static BufferedImage[] speicalBlankaRight = new BufferedImage[8]; public static BufferedImage[] BlankaTorsoHitRight = new BufferedImage[2]; public static BufferedImage[] BlankaHeadHitRight = new BufferedImage[2]; public static BufferedImage[] knockDownBlankaRight = new BufferedImage[9]; public static BufferedImage[] defeatBlankaRight = new BufferedImage[5]; //END OF Blanka CHARACTER SPRITES RIGHT //Blanka CHARACTER SPRITES LEFT public static BufferedImage[] idleBlankaLeft = new BufferedImage[4]; public static BufferedImage[] walkBlankaLeft = new BufferedImage[5]; public static BufferedImage[] verticalJumpBlankaLeft = new BufferedImage[4]; public static BufferedImage[] diagonalJumpBlankaLeft = new BufferedImage[8]; public static BufferedImage[] punchBlankaLeft = new BufferedImage[3]; public static BufferedImage[] kickBlankaLeft = new BufferedImage[3]; public static BufferedImage[] idleSneakBlankaLeft = new BufferedImage[2]; public static BufferedImage[] sneakpunchBlankaLeft = new BufferedImage[3]; public static BufferedImage[] sneakkickBlankaLeft = new BufferedImage[3]; public static BufferedImage[] aerialkickBlankaLeft = new BufferedImage[3]; public static BufferedImage[] speicalBlankaLeft = new BufferedImage[8]; public static BufferedImage[] BlankaTorsoHitLeft = new BufferedImage[2]; public static BufferedImage[] BlankaHeadHitLeft = new BufferedImage[2]; public static BufferedImage[] knockDownBlankaLeft = new BufferedImage[9]; public static BufferedImage[] defeatBlankaLeft = new BufferedImage[5]; //END OF Blanka CHARACTER SPRITES LEFT protected BlankaTexture(){ loadRight(); loadLeft(); } void loadLeft(){ try{ final int xStart = 1188; BufferedImage BlankaSpriteSheetLeft = ImageIO.read(getClass().getResource("/imgs/characters/BlankaSpriteSheetLeft.png")); idleBlankaLeft[0] = BlankaSpriteSheetLeft.getSubimage(xStart-7-63,32,63,87); idleBlankaLeft[1] = BlankaSpriteSheetLeft.getSubimage(xStart-75-66,33,66,86); idleBlankaLeft[2] = BlankaSpriteSheetLeft.getSubimage(xStart-150-63,30,63,88); idleBlankaLeft[3] = BlankaSpriteSheetLeft.getSubimage(xStart-222-59,31,59,87); walkBlankaLeft[0] = BlankaSpriteSheetLeft.getSubimage(xStart-62-297,33,62,86); walkBlankaLeft[1] = BlankaSpriteSheetLeft.getSubimage(xStart-51-378,37,51,78); walkBlankaLeft[2] = BlankaSpriteSheetLeft.getSubimage(xStart-49-451,39,49,76); walkBlankaLeft[3] = BlankaSpriteSheetLeft.getSubimage(xStart-48-521,36,48,82); walkBlankaLeft[4] = BlankaSpriteSheetLeft.getSubimage (xStart-51-590,31,51,87); punchBlankaLeft[0] = BlankaSpriteSheetLeft.getSubimage(xStart-417-73,150,73,90) ; punchBlankaLeft[1] = BlankaSpriteSheetLeft.getSubimage(xStart-507-86,151,86,90); punchBlankaLeft[2] = BlankaSpriteSheetLeft.getSubimage(xStart-604-60,158,60,85); kickBlankaLeft[0] = BlankaSpriteSheetLeft.getSubimage(xStart-12-58,400,58,81); kickBlankaLeft[1] = BlankaSpriteSheetLeft.getSubimage(xStart-80-85,400,85,82); kickBlankaLeft[2] = BlankaSpriteSheetLeft.getSubimage(xStart-177-58,400,58,83); verticalJumpBlankaLeft[0] = BlankaSpriteSheetLeft.getSubimage(xStart-654-55,50,55,72); verticalJumpBlankaLeft[1] = BlankaSpriteSheetLeft.getSubimage(xStart-775-50,12,50,100); verticalJumpBlankaLeft[2] = BlankaSpriteSheetLeft.getSubimage(xStart-834-45,16,45,72); verticalJumpBlankaLeft[3] = BlankaSpriteSheetLeft.getSubimage(xStart-890-40,12,40,100); // diagonalJumpBlankaLeft[0] = BlankaSpriteSheetLeft.getSubimage(834, 64, 62, 68); // diagonalJumpBlankaLeft[0] = BlankaSpriteSheetLeft.getSubimage(846, 7, 80, 125); diagonalJumpBlankaLeft[0] = BlankaSpriteSheetLeft.getSubimage(xStart-409-37,932,37,88); diagonalJumpBlankaLeft[1] = BlankaSpriteSheetLeft.getSubimage(xStart-451-37,937,37,68); diagonalJumpBlankaLeft[2] = BlankaSpriteSheetLeft.getSubimage(xStart-519-37,951,37,48); diagonalJumpBlankaLeft[3] = BlankaSpriteSheetLeft.getSubimage(xStart-589-37,949,37,52); diagonalJumpBlankaLeft[4] = BlankaSpriteSheetLeft.getSubimage(xStart-640-37,951,37,50); diagonalJumpBlankaLeft[5] = BlankaSpriteSheetLeft.getSubimage(xStart-695-37,948,37,53); diagonalJumpBlankaLeft[6] = BlankaSpriteSheetLeft.getSubimage(xStart-749-37,951,37,50); diagonalJumpBlankaLeft[7] = BlankaSpriteSheetLeft.getSubimage(xStart-813-37,962,37,57); // idleSneakBlankaLeft[0] = BlankaSpriteSheetLeft.getSubimage(xStart-950-50,51,50,65); // sneakpunchBlankaLeft[0] = BlankaSpriteSheetLeft.getSubimage(xStart-460-60,530,60,50); sneakpunchBlankaLeft[1] = BlankaSpriteSheetLeft.getSubimage(xStart-530-102,507,102,70); sneakpunchBlankaLeft[2] = BlankaSpriteSheetLeft.getSubimage(xStart-646-57,530,57,50); sneakkickBlankaLeft[0] = BlankaSpriteSheetLeft.getSubimage(xStart-722-55,507,55,76); sneakkickBlankaLeft[1] = BlankaSpriteSheetLeft.getSubimage(xStart-787-83,509,83,63); sneakkickBlankaLeft[2] = BlankaSpriteSheetLeft.getSubimage(xStart-882-60,508,60,72); aerialkickBlankaLeft[0] = BlankaSpriteSheetLeft.getSubimage(xStart-615-85,595,85,85); aerialkickBlankaLeft[1] = BlankaSpriteSheetLeft.getSubimage(xStart-706-103,600,103,80); aerialkickBlankaLeft[2] = BlankaSpriteSheetLeft.getSubimage(xStart-815-85,595,85,85); // BlankaTorsoHitLeft[0] = BlankaSpriteSheetLeft.getSubimage(xStart-5-55,1164,55,85); BlankaTorsoHitLeft[1] = BlankaSpriteSheetLeft.getSubimage(xStart-70-63,1170,63,80); BlankaHeadHitLeft[0] = BlankaSpriteSheetLeft.getSubimage(xStart-3-54,1287,54,78); BlankaHeadHitLeft[1] = BlankaSpriteSheetLeft.getSubimage(xStart-230-60,1175,60,75); knockDownBlankaLeft[0] = BlankaSpriteSheetLeft.getSubimage(xStart-133-83,1294,83,64); knockDownBlankaLeft[1] = BlankaSpriteSheetLeft.getSubimage(xStart-215-97,1314,97,50); knockDownBlankaLeft[2] = BlankaSpriteSheetLeft.getSubimage (xStart-317-107,1326,107,50); knockDownBlankaLeft[3] = BlankaSpriteSheetLeft.getSubimage(xStart-430-50,1280,50,55); knockDownBlankaLeft[4] = BlankaSpriteSheetLeft.getSubimage(xStart-495-105, 1270,105,56) ; knockDownBlankaLeft[5] = BlankaSpriteSheetLeft.getSubimage(xStart-605-75,1270,75,92); knockDownBlankaLeft[6] = BlankaSpriteSheetLeft.getSubimage(xStart-690-85,1280,85,90); knockDownBlankaLeft[7] = BlankaSpriteSheetLeft.getSubimage(xStart-780-80,1285,80,80); knockDownBlankaLeft[8] = BlankaSpriteSheetLeft.getSubimage(xStart-875-55,1310,55,60); defeatBlankaLeft[0] = BlankaSpriteSheetLeft.getSubimage(xStart-5-62,1410,62,70); defeatBlankaLeft[1] = BlankaSpriteSheetLeft.getSubimage(xStart-66-84,1410,84,60); defeatBlankaLeft[2] = BlankaSpriteSheetLeft.getSubimage(xStart-150-100,1435,100,50); defeatBlankaLeft[3] = BlankaSpriteSheetLeft.getSubimage(xStart-250-80,1410,80,60); defeatBlankaLeft[4] = BlankaSpriteSheetLeft.getSubimage(xStart-330-107,1440,107,47); speicalBlankaLeft[0] = BlankaSpriteSheetLeft.getSubimage(xStart-6-55,726-10,55,65+10); speicalBlankaLeft[1] = BlankaSpriteSheetLeft.getSubimage(xStart-69-52,727-10,52,64+10); speicalBlankaLeft[2] = BlankaSpriteSheetLeft.getSubimage(xStart-131-55,726-10,55,65+10); speicalBlankaLeft[3] = BlankaSpriteSheetLeft.getSubimage(xStart-194-52,727-10,52,64+10); speicalBlankaLeft[4] = BlankaSpriteSheetLeft.getSubimage(xStart-255-73,717-10,73,74+10); speicalBlankaLeft[5] = BlankaSpriteSheetLeft.getSubimage(xStart-338-50,734-10,50,57+10); speicalBlankaLeft[6] = BlankaSpriteSheetLeft.getSubimage(xStart-396-73,717-10,73,74+10); speicalBlankaLeft[7] = BlankaSpriteSheetLeft.getSubimage(xStart-479-50,734-10,50,57+10); }catch(Exception e) { } } void loadRight(){ try{ BufferedImage BlankaSpriteSheetRight = ImageIO.read(getClass().getResource("/imgs/characters/BlankaSpriteSheetRight.png")); idleBlankaRight[0] = BlankaSpriteSheetRight.getSubimage(7,32,63,87); idleBlankaRight[1] = BlankaSpriteSheetRight.getSubimage(75,33,66,86); idleBlankaRight[2] = BlankaSpriteSheetRight.getSubimage(150,30,63,88); idleBlankaRight[3] = BlankaSpriteSheetRight.getSubimage(222,31,59,87); walkBlankaRight[0] = BlankaSpriteSheetRight.getSubimage(297,33,62,86); walkBlankaRight[1] = BlankaSpriteSheetRight.getSubimage(378,37,51,78); walkBlankaRight[2] = BlankaSpriteSheetRight.getSubimage(451,39,49,76); walkBlankaRight[3] = BlankaSpriteSheetRight.getSubimage(521,36,48,82); walkBlankaRight[4] = BlankaSpriteSheetRight.getSubimage (590,31,51,87); punchBlankaRight[0] = BlankaSpriteSheetRight.getSubimage(417,150,73,90) ; punchBlankaRight[1] = BlankaSpriteSheetRight.getSubimage(507,151,86,90); punchBlankaRight[2] = BlankaSpriteSheetRight.getSubimage(604,158,60,85); kickBlankaRight[0] = BlankaSpriteSheetRight.getSubimage(12,400,58,81); kickBlankaRight[1] = BlankaSpriteSheetRight.getSubimage(80,400,85,82); kickBlankaRight[2] = BlankaSpriteSheetRight.getSubimage(177,400,58,83); verticalJumpBlankaRight[0] = BlankaSpriteSheetRight.getSubimage(654,50,55,72); verticalJumpBlankaRight[1] = BlankaSpriteSheetRight.getSubimage(775,12,50,100); verticalJumpBlankaRight[2] = BlankaSpriteSheetRight.getSubimage(834,16,45,72); verticalJumpBlankaRight[3] = BlankaSpriteSheetRight.getSubimage(890,12,40,100); // diagonalJumpBlankaRight[0] = BlankaSpriteSheetRight.getSubimage(834, 64, 62, 68); // diagonalJumpBlankaRight[0] = BlankaSpriteSheetRight.getSubimage(846, 7, 80, 125); diagonalJumpBlankaRight[0] = BlankaSpriteSheetRight.getSubimage(409,932,37,88); diagonalJumpBlankaRight[1] = BlankaSpriteSheetRight.getSubimage(451,937,65,68); diagonalJumpBlankaRight[2] = BlankaSpriteSheetRight.getSubimage(519,951,64,48); diagonalJumpBlankaRight[3] = BlankaSpriteSheetRight.getSubimage(589,949,48,52); diagonalJumpBlankaRight[4] = BlankaSpriteSheetRight.getSubimage(640,951,51,50); diagonalJumpBlankaRight[5] = BlankaSpriteSheetRight.getSubimage(695,948,48,53); diagonalJumpBlankaRight[6] = BlankaSpriteSheetRight.getSubimage(749,951,51,50); diagonalJumpBlankaRight[7] = BlankaSpriteSheetRight.getSubimage(813,962,50,57); // idleSneakBlankaRight[0] = BlankaSpriteSheetRight.getSubimage(950,51,50,65); // sneakpunchBlankaRight[0] = BlankaSpriteSheetRight.getSubimage(460,530,60,50); sneakpunchBlankaRight[1] = BlankaSpriteSheetRight.getSubimage(530,507,102,70); sneakpunchBlankaRight[2] = BlankaSpriteSheetRight.getSubimage(646,530,57,50); sneakkickBlankaRight[0] = BlankaSpriteSheetRight.getSubimage(722,507,55,76); sneakkickBlankaRight[1] = BlankaSpriteSheetRight.getSubimage(787,509,83,63); sneakkickBlankaRight[2] = BlankaSpriteSheetRight.getSubimage(882,508,60,72); aerialkickBlankaRight[0] = BlankaSpriteSheetRight.getSubimage(615,595,85,85); aerialkickBlankaRight[1] = BlankaSpriteSheetRight.getSubimage(706,600,103,80); aerialkickBlankaRight[2] = BlankaSpriteSheetRight.getSubimage(815,595,85,85); // BlankaTorsoHitRight[0] = BlankaSpriteSheetRight.getSubimage(5,1164,55,85); BlankaTorsoHitRight[1] = BlankaSpriteSheetRight.getSubimage(70,1170,63,80); BlankaHeadHitRight[0] = BlankaSpriteSheetRight.getSubimage(3,1287,54,78); BlankaHeadHitRight[1] = BlankaSpriteSheetRight.getSubimage(230,1175,60,75); knockDownBlankaRight[0] = BlankaSpriteSheetRight.getSubimage(133,1294,83,64); knockDownBlankaRight[1] = BlankaSpriteSheetRight.getSubimage(215,1314,97,50); knockDownBlankaRight[2] = BlankaSpriteSheetRight.getSubimage (317,1326,107,50); knockDownBlankaRight[3] = BlankaSpriteSheetRight.getSubimage(430,1280,50,55); knockDownBlankaRight[4] = BlankaSpriteSheetRight.getSubimage(495, 1270,105,56) ; knockDownBlankaRight[5] = BlankaSpriteSheetRight.getSubimage(605,1270,75,92); knockDownBlankaRight[6] = BlankaSpriteSheetRight.getSubimage(690,1280,85,90); knockDownBlankaRight[7] = BlankaSpriteSheetRight.getSubimage(780,1285,80,80); knockDownBlankaRight[8] = BlankaSpriteSheetRight.getSubimage(875,1310,55,60); defeatBlankaRight[0] = BlankaSpriteSheetRight.getSubimage(5,1410,62,70); defeatBlankaRight[1] = BlankaSpriteSheetRight.getSubimage(66,1410,84,60); defeatBlankaRight[2] = BlankaSpriteSheetRight.getSubimage(150,1435,100,50); defeatBlankaRight[3] = BlankaSpriteSheetRight.getSubimage(250,1410,80,60); defeatBlankaRight[4] = BlankaSpriteSheetRight.getSubimage(330,1440,107,47); speicalBlankaRight[0] = BlankaSpriteSheetRight.getSubimage(6,726-10,55,65+10); speicalBlankaRight[1] = BlankaSpriteSheetRight.getSubimage(69,727-10,52,64+10); speicalBlankaRight[2] = BlankaSpriteSheetRight.getSubimage(131,726-10,55,65+10); speicalBlankaRight[3] = BlankaSpriteSheetRight.getSubimage(194,727-10,52,64+10); speicalBlankaRight[4] = BlankaSpriteSheetRight.getSubimage(255,717-10,73,74+10); speicalBlankaRight[5] = BlankaSpriteSheetRight.getSubimage(338,734-10,50,57+10); speicalBlankaRight[6] = BlankaSpriteSheetRight.getSubimage(396,717-10,73,74+10); speicalBlankaRight[7] = BlankaSpriteSheetRight.getSubimage(479,734-10,50,57+10); }catch(Exception e){e.printStackTrace(); } } } <file_sep>/src/gameClass/StreetFighterLauncher.java package gameClass; import java.awt.CardLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Toolkit; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.KeyStroke; import textureClass.MapTexture; import textureClass.Texture; @SuppressWarnings("serial") public class StreetFighterLauncher extends JPanel { boolean[] select = new boolean[3]; JFrame frame; CardLayout cardLayout = new CardLayout(); JPanel screen = new JPanel(cardLayout); public static void main(String[] args){ new StreetFighterLauncher(); } protected StreetFighterLauncher(){ Texture.loadMapTextures(); panel(); keys(); loadCharacterImages(); repaint(); } void loadCharacterImages(){ Texture.loadRyuTextures(); Texture.loadEHondaTextures(); Texture.loadBlankaTextures(); Texture.loadDeeJayTextures(); Texture.loadDhalsimTextures(); } void keys(){ select[1] = true; getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("A"), "A"); getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("D"), "D"); getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("ENTER"), "CHOOSE"); getActionMap().put("D", new AbstractAction(){ @Override public void actionPerformed(ActionEvent e) { for(int index = 0; index < select.length-1; index++){ if(select[index]){ select[index] = false; select[index + 1] = true; repaint(); return; } } } }); getActionMap().put("A", new AbstractAction(){ @Override public void actionPerformed(ActionEvent e) { for(int index = 1; index < select.length; index++){ if(select[index]){ select[index] = false; select[index - 1] = true; repaint(); return; } } } }); getActionMap().put("CHOOSE", new AbstractAction(){ @Override public void actionPerformed(ActionEvent e) { for(int index = 0; index < select.length; index++){ if(select[index]){ switch(index){ case 0: new CharacterSelectLauncher(GameType.TRAINING); frame.dispose(); break; case 1: new CharacterSelectLauncher(GameType.FIGHT); frame.dispose(); break; case 2: cardLayout.next(screen); break; } } } } }); } void panel(){ frame = new JFrame(); new OptionLauncher(screen,cardLayout); screen.add(this, null); screen.add(OptionLauncher.panel, null); frame.add(screen); frame.setPreferredSize(new Dimension(Toolkit.getDefaultToolkit().getScreenSize())); frame.pack(); frame.setVisible(true); frame.setResizable(false); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); cardLayout.show(screen, null); } public void paintComponent(Graphics g){ drawBackDrops(g); drawGameModeSelect(g); } void drawGameModeSelect(Graphics g){ int xBuffer = (int)(Constants.SCREEN_WIDTH.getIntValue()*.2); int yBuffer = (int)(Constants.SCREEN_HEIGHT.getIntValue()*.8); g.setFont(new Font("Arial",Font.BOLD,40)); for(int index = 0; index < select.length; index++){ if(select[index]){ g.setColor(Color.GRAY); }else{ g.setColor(Color.BLACK); } String s = ""; switch(index){ case 0: s = "SINGLEPLAYER"; break; case 1: s = "GROUP BATTLE"; break; case 2: s = "OPTIONS"; break; } g.drawString(s, xBuffer, yBuffer); xBuffer += (s.length()*30) + 50; } } void drawBackDrops(Graphics g){ g.setFont(new Font("Arial",Font.BOLD,40)); g.drawImage(MapTexture.launcherSprites[0], 0, 0,Constants.SCREEN_WIDTH.getIntValue(),Constants.SCREEN_HEIGHT.getIntValue(), null); g.drawString("choose with A,D and press Enter to start", (int)(Constants.SCREEN_WIDTH.getIntValue()*.1), (int)(Constants.SCREEN_HEIGHT.getIntValue()*.9)); } } <file_sep>/src/textureClass/DeeJayTexture.java package textureClass; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; public class DeeJayTexture extends Texture{ //DeeJay CHARACTER SPRITES RIGHT public static BufferedImage[] idleDeeJayRight = new BufferedImage[4]; public static BufferedImage[] walkDeeJayRight = new BufferedImage[5]; public static BufferedImage[] verticalJumpDeeJayRight = new BufferedImage[7]; public static BufferedImage[] diagonalJumpDeeJayRight = new BufferedImage[7]; public static BufferedImage[] punchDeeJayRight = new BufferedImage[3]; public static BufferedImage[] kickDeeJayRight = new BufferedImage[8]; public static BufferedImage[] idleSneakDeeJayRight = new BufferedImage[1]; public static BufferedImage[] sneakpunchDeeJayRight = new BufferedImage[2]; public static BufferedImage[] sneakkickDeeJayRight = new BufferedImage[3]; public static BufferedImage[] aerialkickDeeJayRight = new BufferedImage[2]; public static BufferedImage[] speicalDeeJayRight = new BufferedImage[6]; public static BufferedImage[] DeeJayTorsoHitRight = new BufferedImage[4]; public static BufferedImage[] DeeJayHeadHitRight = new BufferedImage[4]; public static BufferedImage[] knockDownDeeJayRight = new BufferedImage[8]; public static BufferedImage[] defeatDeeJayRight = new BufferedImage[4]; //END OF DeeJay CHARACTER SPRITES RIGHT //DeeJay CHARACTER SPRITES LEFT public static BufferedImage[] idleDeeJayLeft = new BufferedImage[4]; public static BufferedImage[] walkDeeJayLeft = new BufferedImage[5]; public static BufferedImage[] verticalJumpDeeJayLeft = new BufferedImage[7]; public static BufferedImage[] diagonalJumpDeeJayLeft = new BufferedImage[7]; public static BufferedImage[] punchDeeJayLeft = new BufferedImage[3]; public static BufferedImage[] kickDeeJayLeft = new BufferedImage[8]; public static BufferedImage[] idleSneakDeeJayLeft = new BufferedImage[1]; public static BufferedImage[] sneakpunchDeeJayLeft = new BufferedImage[2]; public static BufferedImage[] sneakkickDeeJayLeft = new BufferedImage[3]; public static BufferedImage[] aerialkickDeeJayLeft = new BufferedImage[2]; public static BufferedImage[] speicalDeeJayLeft = new BufferedImage[6]; public static BufferedImage[] DeeJayTorsoHitLeft = new BufferedImage[4]; public static BufferedImage[] DeeJayHeadHitLeft = new BufferedImage[4]; public static BufferedImage[] knockDownDeeJayLeft = new BufferedImage[8]; public static BufferedImage[] defeatDeeJayLeft = new BufferedImage[4]; //END OF DeeJay CHARACTER SPRITES LEFT protected DeeJayTexture(){ loadRight(); loadLeft(); } void loadLeft(){ try{ final int xStart = 1385; BufferedImage DeeJaySpriteSheetLeft = ImageIO.read(getClass().getResource("/imgs/characters/DeeJayLeft.png")); idleDeeJayLeft[0] = DeeJaySpriteSheetLeft.getSubimage(xStart-9-40,30,40,90); idleDeeJayLeft[1] = DeeJaySpriteSheetLeft.getSubimage(xStart-60-50,30,50,90); idleDeeJayLeft[2] = DeeJaySpriteSheetLeft.getSubimage(xStart-115-50,25,50,95); idleDeeJayLeft[3] = DeeJaySpriteSheetLeft.getSubimage(xStart-170-50,30,50,90); walkDeeJayLeft[0] = DeeJaySpriteSheetLeft.getSubimage(xStart-233-(271-233),31,271-233,123-31); walkDeeJayLeft[1] = DeeJaySpriteSheetLeft.getSubimage(xStart-278-(321-278),29,321-278,123-29); walkDeeJayLeft[2] = DeeJaySpriteSheetLeft.getSubimage(xStart-327-(384-327),27,384-327,121-27); walkDeeJayLeft[3] = DeeJaySpriteSheetLeft.getSubimage(xStart-392-(447-392),31,447-392,121-31); walkDeeJayLeft[4] = DeeJaySpriteSheetLeft.getSubimage(xStart-458-(497-458),32,497-458,122-32); punchDeeJayLeft[0] = DeeJaySpriteSheetLeft.getSubimage(xStart-8-(40),160,40,85); punchDeeJayLeft[1] = DeeJaySpriteSheetLeft.getSubimage(xStart-63-(75),160,75,85); punchDeeJayLeft[2] = DeeJaySpriteSheetLeft.getSubimage(xStart-145-(55),160,55,85); kickDeeJayLeft[0] = DeeJaySpriteSheetLeft.getSubimage(xStart-2-65,747,65,87); kickDeeJayLeft[1] = DeeJaySpriteSheetLeft.getSubimage(xStart-74-65,746,65,88); kickDeeJayLeft[2] = DeeJaySpriteSheetLeft.getSubimage(xStart-135-55,747,55,90); kickDeeJayLeft[3] = DeeJaySpriteSheetLeft.getSubimage(xStart-196-55,747,55,90); kickDeeJayLeft[4] = DeeJaySpriteSheetLeft.getSubimage(xStart-255-84,741,84,96); kickDeeJayLeft[5] = DeeJaySpriteSheetLeft.getSubimage(xStart-343-84,741,84,96); kickDeeJayLeft[6] = DeeJaySpriteSheetLeft.getSubimage(xStart-432-68,750,68,87); kickDeeJayLeft[7] = DeeJaySpriteSheetLeft.getSubimage(xStart-504-59,753,59,84); verticalJumpDeeJayLeft[0] = DeeJaySpriteSheetLeft.getSubimage(xStart-508-(42),44,42,76); verticalJumpDeeJayLeft[1] = DeeJaySpriteSheetLeft.getSubimage(xStart-555-(45),11,45,115); verticalJumpDeeJayLeft[2] = DeeJaySpriteSheetLeft.getSubimage(xStart-600-(35),25,35,90); verticalJumpDeeJayLeft[3] = DeeJaySpriteSheetLeft.getSubimage(xStart-640-(40),30,40,80); verticalJumpDeeJayLeft[4] = DeeJaySpriteSheetLeft.getSubimage(xStart-680-(40),30,40,75); verticalJumpDeeJayLeft[5] = DeeJaySpriteSheetLeft.getSubimage(xStart-722-(758-722),10,758-722,70); verticalJumpDeeJayLeft[6] = DeeJaySpriteSheetLeft.getSubimage(xStart-765-(35),45,35,80); // diagonalJumpDeeJayLeft[0] = DeeJaySpriteSheetLeft.getSubimage(834, 64, 62, 68); // diagonalJumpDeeJayLeft[0] = DeeJaySpriteSheetLeft.getSubimage(846, 7, 80, 125); diagonalJumpDeeJayLeft[0] = DeeJaySpriteSheetLeft.getSubimage(xStart-821-(858-821),46,858-821,122-46); diagonalJumpDeeJayLeft[1] = DeeJaySpriteSheetLeft.getSubimage(xStart-867-(923-867),33,923-867,123-33); diagonalJumpDeeJayLeft[2] = DeeJaySpriteSheetLeft.getSubimage(xStart-926-(994-926),26,994-926,114-26); diagonalJumpDeeJayLeft[3] = DeeJaySpriteSheetLeft.getSubimage(xStart-997-(1050-997),26,1050-997,122-26); diagonalJumpDeeJayLeft[4] = DeeJaySpriteSheetLeft.getSubimage(xStart-1055-(1141-1055),26,1141-1055,108-26); diagonalJumpDeeJayLeft[5] = DeeJaySpriteSheetLeft.getSubimage(xStart-1146-(1216-1146),32,1216-1146,123-32); diagonalJumpDeeJayLeft[6] = DeeJaySpriteSheetLeft.getSubimage(xStart-1219-(1262-1219),11,1262-1219,123-11); // idleSneakDeeJayLeft[0] = DeeJaySpriteSheetLeft.getSubimage(xStart-1270-(40),45,40,75); // sneakpunchDeeJayLeft[0] = DeeJaySpriteSheetLeft.getSubimage(xStart-190-(60),530,60,70); sneakpunchDeeJayLeft[1] = DeeJaySpriteSheetLeft.getSubimage(xStart-260-(65),540,65, 60); sneakkickDeeJayLeft[0] = DeeJaySpriteSheetLeft.getSubimage(xStart-650-(60),520,60, 80); sneakkickDeeJayLeft[1] = DeeJaySpriteSheetLeft.getSubimage(xStart-710-(90), 520,90, 80); sneakkickDeeJayLeft[2] = DeeJaySpriteSheetLeft.getSubimage(xStart-800-(62), 520, 62,80); aerialkickDeeJayLeft[0] = DeeJaySpriteSheetLeft.getSubimage(xStart-669-( 718-669),645, 718-669, 723-645); aerialkickDeeJayLeft[1] = DeeJaySpriteSheetLeft.getSubimage(xStart-723-( 810-723),647, 810-723,723-647); DeeJayTorsoHitLeft[0] = DeeJaySpriteSheetLeft.getSubimage(xStart-887-(932-887),1130,932-887,1218-1130); DeeJayTorsoHitLeft[1] = DeeJaySpriteSheetLeft.getSubimage(xStart-936-(984-936),1131,984-936,1217-1131); DeeJayTorsoHitLeft[2] = DeeJaySpriteSheetLeft.getSubimage(xStart-994-(1046-994),1129,1046-994,1217-1129); DeeJayTorsoHitLeft[3] = DeeJaySpriteSheetLeft.getSubimage(xStart-1061-(1106-1061),1128,1106-1061,1218-1128); DeeJayHeadHitLeft[0] = DeeJaySpriteSheetLeft.getSubimage(xStart-1112-(1164-1112),1129,1164-1112,1219-1129); DeeJayHeadHitLeft[1] = DeeJaySpriteSheetLeft.getSubimage(xStart-1166-(1225-1166),1130,1225-1166,1218-1130); DeeJayHeadHitLeft[2] = DeeJaySpriteSheetLeft.getSubimage(xStart-1227-(1291-1227),1127,1291-1227,1218-1127); DeeJayHeadHitLeft[3] = DeeJaySpriteSheetLeft.getSubimage(xStart-1299-(1345-1299),1126,1345-1299,1217-1126); knockDownDeeJayLeft[0] = DeeJaySpriteSheetLeft.getSubimage(xStart-5-(71-5),1254, 71-5,1324-1254); knockDownDeeJayLeft[1] = DeeJaySpriteSheetLeft.getSubimage(xStart-73-(156-73),1257,156-73,1316-1257); knockDownDeeJayLeft[2] = DeeJaySpriteSheetLeft.getSubimage(xStart-158-(248-158),1268,248-158,1329-1268); knockDownDeeJayLeft[3] = DeeJaySpriteSheetLeft.getSubimage(xStart-251-(348-251),1296,348-251,1329-1296) ; knockDownDeeJayLeft[4] = DeeJaySpriteSheetLeft.getSubimage(xStart-349-(391-349),1275,391-349,1329-1275) ; knockDownDeeJayLeft[5] = DeeJaySpriteSheetLeft.getSubimage (xStart-414-(464-414),1236,464-414,1325-1236); knockDownDeeJayLeft[6] = DeeJaySpriteSheetLeft.getSubimage(xStart-477-(549-477),1256,549-477,1322-1256); knockDownDeeJayLeft[7] = DeeJaySpriteSheetLeft.getSubimage(xStart-569-(601-569),1253,601-569,1325-1253); defeatDeeJayLeft[0] = DeeJaySpriteSheetLeft.getSubimage(xStart-735-(801-735), 1254, 801-735, 1324-1254) ; defeatDeeJayLeft[1] = DeeJaySpriteSheetLeft.getSubimage(xStart-805-(887-805),1267,887-805,1323-1267); defeatDeeJayLeft[2] = DeeJaySpriteSheetLeft.getSubimage(xStart-894-(977-894),1270, 977-894, 1330-1270); defeatDeeJayLeft[3] = DeeJaySpriteSheetLeft.getSubimage(xStart-1077-( 1174-1077),1299-25, 1174-1077, 1329-1299+25); speicalDeeJayLeft[0] = DeeJaySpriteSheetLeft.getSubimage(xStart-4-56,872,56,97); speicalDeeJayLeft[1] = DeeJaySpriteSheetLeft.getSubimage(xStart-73-63,882,63,87); speicalDeeJayLeft[2] = DeeJaySpriteSheetLeft.getSubimage(xStart-145-71,885,71,84); speicalDeeJayLeft[3] = DeeJaySpriteSheetLeft.getSubimage(xStart-226-67,864,67,105); speicalDeeJayLeft[4] = DeeJaySpriteSheetLeft.getSubimage(xStart-306-66,856,66,113); speicalDeeJayLeft[5] = DeeJaySpriteSheetLeft.getSubimage(xStart-387-55,883,55,86); }catch(Exception e) { } } void loadRight(){ try{ BufferedImage DeeJaySpriteSheetRight = ImageIO.read(getClass().getResource("/imgs/characters/DeeJayRight.png")); idleDeeJayRight[0] = DeeJaySpriteSheetRight.getSubimage(9,30,40,90); idleDeeJayRight[1] = DeeJaySpriteSheetRight.getSubimage(60,30,50,90); idleDeeJayRight[2] = DeeJaySpriteSheetRight.getSubimage(115,25,50,95); idleDeeJayRight[3] = DeeJaySpriteSheetRight.getSubimage(170,30,50,90); walkDeeJayRight[0] = DeeJaySpriteSheetRight.getSubimage(233,31,271-233,123-31); walkDeeJayRight[1] = DeeJaySpriteSheetRight.getSubimage(278,29,321-278,123-29); walkDeeJayRight[2] = DeeJaySpriteSheetRight.getSubimage(327,27,384-327,121-27); walkDeeJayRight[3] = DeeJaySpriteSheetRight.getSubimage(392,31,447-392,121-31); walkDeeJayRight[4] = DeeJaySpriteSheetRight.getSubimage(458,32,497-458,122-32); punchDeeJayRight[0] = DeeJaySpriteSheetRight.getSubimage(8,160,40,85); punchDeeJayRight[1] = DeeJaySpriteSheetRight.getSubimage(63,160,75,85); punchDeeJayRight[2] = DeeJaySpriteSheetRight.getSubimage(145,160,55,85); kickDeeJayRight[0] = DeeJaySpriteSheetRight.getSubimage(2,747,65,87); kickDeeJayRight[1] = DeeJaySpriteSheetRight.getSubimage(74,746,55,88); kickDeeJayRight[2] = DeeJaySpriteSheetRight.getSubimage(135,747,55,90); kickDeeJayRight[3] = DeeJaySpriteSheetRight.getSubimage(196,747,55,90); kickDeeJayRight[4] = DeeJaySpriteSheetRight.getSubimage(255,741,84,96); kickDeeJayRight[5] = DeeJaySpriteSheetRight.getSubimage(343,741,84,96); kickDeeJayRight[6] = DeeJaySpriteSheetRight.getSubimage(432,750,68,87); kickDeeJayRight[7] = DeeJaySpriteSheetRight.getSubimage(504,753,59,84); verticalJumpDeeJayRight[0] = DeeJaySpriteSheetRight.getSubimage(508,44,42,76); verticalJumpDeeJayRight[1] = DeeJaySpriteSheetRight.getSubimage(555,11,45,115); verticalJumpDeeJayRight[2] = DeeJaySpriteSheetRight.getSubimage(600,25,35,90); verticalJumpDeeJayRight[3] = DeeJaySpriteSheetRight.getSubimage(640,30,40,80); verticalJumpDeeJayRight[4] = DeeJaySpriteSheetRight.getSubimage(680,30,40,75); verticalJumpDeeJayRight[5] = DeeJaySpriteSheetRight.getSubimage(722,10,758-722,70); verticalJumpDeeJayRight[6] = DeeJaySpriteSheetRight.getSubimage(765,45,35,80); // diagonalJumpDeeJayRight[0] = DeeJaySpriteSheetRight.getSubimage(834, 64, 62, 68); // diagonalJumpDeeJayRight[0] = DeeJaySpriteSheetRight.getSubimage(846, 7, 80, 125); diagonalJumpDeeJayRight[0] = DeeJaySpriteSheetRight.getSubimage(821,46,858-821,122-46); diagonalJumpDeeJayRight[1] = DeeJaySpriteSheetRight.getSubimage(867,33,923-867,123-33); diagonalJumpDeeJayRight[2] = DeeJaySpriteSheetRight.getSubimage(926,26,994-926,114-26); diagonalJumpDeeJayRight[3] = DeeJaySpriteSheetRight.getSubimage(997,26,1050-997,122-26); diagonalJumpDeeJayRight[4] = DeeJaySpriteSheetRight.getSubimage(1055,26,1141-1055,108-26); diagonalJumpDeeJayRight[5] = DeeJaySpriteSheetRight.getSubimage(1146,32,1216-1146,123-32); diagonalJumpDeeJayRight[6] = DeeJaySpriteSheetRight.getSubimage(1219,11,1262-1219,123-11); // idleSneakDeeJayRight[0] = DeeJaySpriteSheetRight.getSubimage(1270,45,40,75); // sneakpunchDeeJayRight[0] = DeeJaySpriteSheetRight.getSubimage(190,530,60,70); sneakpunchDeeJayRight[1] = DeeJaySpriteSheetRight.getSubimage(260,540,65, 60); sneakkickDeeJayRight[0] = DeeJaySpriteSheetRight.getSubimage(650,520,60, 80); sneakkickDeeJayRight[1] = DeeJaySpriteSheetRight.getSubimage(710, 520,90, 80); sneakkickDeeJayRight[2] = DeeJaySpriteSheetRight.getSubimage(800, 520, 62,80); aerialkickDeeJayRight[0] = DeeJaySpriteSheetRight.getSubimage(669,645, 718-669, 723-645); aerialkickDeeJayRight[1] = DeeJaySpriteSheetRight.getSubimage(723,647, 810-723,723-647); DeeJayTorsoHitRight[0] = DeeJaySpriteSheetRight.getSubimage(887,1130,932-887,1218-1130); DeeJayTorsoHitRight[1] = DeeJaySpriteSheetRight.getSubimage(936,1131,984-936,1217-1131); DeeJayTorsoHitRight[2] = DeeJaySpriteSheetRight.getSubimage(994,1129,1046-994,1217-1129); DeeJayTorsoHitRight[3] = DeeJaySpriteSheetRight.getSubimage(1061,1128,1106-1061,1218-1128); DeeJayHeadHitRight[0] = DeeJaySpriteSheetRight.getSubimage(1112,1129,1164-1112,1219-1129); DeeJayHeadHitRight[1] = DeeJaySpriteSheetRight.getSubimage(1166,1130,1225-1166,1218-1130); DeeJayHeadHitRight[2] = DeeJaySpriteSheetRight.getSubimage(1227,1127,1291-1227,1218-1127); DeeJayHeadHitRight[3] = DeeJaySpriteSheetRight.getSubimage(1299,1126,1345-1299,1217-1126); knockDownDeeJayRight[0] = DeeJaySpriteSheetRight.getSubimage(5,1254, 71-5,1324-1254); knockDownDeeJayRight[1] = DeeJaySpriteSheetRight.getSubimage(73,1257,156-73,1316-1257); knockDownDeeJayRight[2] = DeeJaySpriteSheetRight.getSubimage(158,1268,248-158,1329-1268); knockDownDeeJayRight[3] = DeeJaySpriteSheetRight.getSubimage(251,1296,348-251,1329-1296) ; knockDownDeeJayRight[4] = DeeJaySpriteSheetRight.getSubimage(349,1275,391-349,1329-1275) ; knockDownDeeJayRight[5] = DeeJaySpriteSheetRight.getSubimage (414,1236,464-414,1325-1236); knockDownDeeJayRight[6] = DeeJaySpriteSheetRight.getSubimage(477,1256,549-477,1322-1256); knockDownDeeJayRight[7] = DeeJaySpriteSheetRight.getSubimage(569,1253,601-569,1325-1253); defeatDeeJayRight[0] = DeeJaySpriteSheetRight.getSubimage(735, 1254, 801-735, 1324-1254) ; defeatDeeJayRight[1] = DeeJaySpriteSheetRight.getSubimage(805,1267,887-805,1323-1267); defeatDeeJayRight[2] = DeeJaySpriteSheetRight.getSubimage(894,1270, 977-894, 1330-1270); defeatDeeJayRight[3] = DeeJaySpriteSheetRight.getSubimage(1077,1299-25, 1174-1077, 1329-1299+25); speicalDeeJayRight[0] = DeeJaySpriteSheetRight.getSubimage(4,872,56,97); speicalDeeJayRight[1] = DeeJaySpriteSheetRight.getSubimage(73,882,63,87); speicalDeeJayRight[2] = DeeJaySpriteSheetRight.getSubimage(145,885,71,84); speicalDeeJayRight[3] = DeeJaySpriteSheetRight.getSubimage(226,864,67,105); speicalDeeJayRight[4] = DeeJaySpriteSheetRight.getSubimage(306,856,66,113); speicalDeeJayRight[5] = DeeJaySpriteSheetRight.getSubimage(387,883,55,86); }catch(Exception e){e.printStackTrace(); } } } <file_sep>/src/textureClass/GlobalTextures.java package textureClass; public class GlobalTextures extends Texture{ protected GlobalTextures(){ load(); } void load(){ } } <file_sep>/src/gameClass/Constants.java package gameClass; import java.awt.Toolkit; public enum Constants { SCREEN_WIDTH(Toolkit.getDefaultToolkit().getScreenSize().width), SCREEN_HEIGHT(Toolkit.getDefaultToolkit().getScreenSize().height) ,GRAVITY(9), ENERGYBALL_WIDTH(100), ENERGYBALL_HEIGHT(100); private int num; private Constants(int num){ this.num = num; } int getIntValue(){ return num; } }
e0895a5cd8aa135c4ea7ee0ac687ceaefd9a0ce9
[ "Markdown", "Java" ]
14
Java
ChewyChiyu/Street-Fighter
00fcf0c4d98f3d5ae220a3dd9712f24fed1439ba
ccf8fa9cae0464decd116b349b65f8faaa3649e6
refs/heads/master
<file_sep>module.exports = { jwtSecret: process.env.JWT_SECRET || '<KEY>' };<file_sep># Strapi application My JAM Stack application (backend)
0a89e6d11e530d8a5cb0d9395d89dd0b55e7be82
[ "JavaScript", "Markdown" ]
2
JavaScript
ThingsOfBeam/JAM-thingsofbeam-app-backend
4c87279982b0c058069e6eb5f44063dfb5044a29
f6613018f2c82925bf16062d98260e3c298322d1
refs/heads/master
<repo_name>richardartoul/regex-engine<file_sep>/regexEngine.js var regexEngine = function(regex, string) { // Since JavaScript doesn't support pointer arithmetic, we mimic // that behavior using counter variables which indicate which position // in the array we want to be referencing at each step in the recursion regexCounter = 0; stringCounter = 0; function match() { // If regex starts with ^ then string must begin with match of remainder of expression if (regex[0] === '^') { // If regex matches starting with first character, this will return true // Otherwise it will return false return matchHere(regexCounter+1, stringCounter); } // Else, walk through string and check to see if string match beginning of expression at each point in string // This is an example of backtracking. If the regex doesn't match at this point in the string, the next // character in the string will be consumed and the regex will be checked again starting at that point. for (var i = 0; i < string.length; i++) { if (matchHere(regexCounter, stringCounter + i)) { return true; } } // If the regex can't be matched starting at any point in the string, return false return false; } // Variable shadowing --- Again, replacement for pointer arithmetic function matchHere(regexCounter, stringCounter) { // If we reach the end of the regex pattern, we've found a match if (regexCounter === regex.length) { return true; } // Handle * case if (regex[regexCounter + 1] === '*') { return matchStar(regex[regexCounter], regexCounter + 2, stringCounter); } // Handle + case if (regex[regexCounter + 1] === '+') { return matchPlus(regex[regexCounter], regexCounter + 2, stringCounter); } // If the current regex char specfies the end of the string then return true or false depending on whether we've reached the end of the string if (regex[regexCounter] === '$' && regexCounter === regex.length -1) { return stringCounter === string.length; } // If we're not at the end of the string and the regular expression character is a wildcard or the same as the string character, continue recursing if (stringCounter !== string.length && (regex[regexCounter] === '.' || regex[regexCounter] === string[stringCounter])) { return matchHere(regexCounter + 1, stringCounter + 1); } // If all else fails, return false. No match. return false; }; // This is a lazy (non-greedy) implementation of matchStart. This means that matchStart will attempt to match the minimum number of characters // possible, as opposed to greedily matching as many as possible. There is no difference in the final output between using greedy and non-greedy // matching, but it will alter how fast the regex-engine runs on certain inputs based on the amount of backtracking that needs to occur. function matchStar(starChar, regexCounter, stringCounter) { // Lazy (non-greedy) implementation of star. Since the minimum number of characters a start can match is 0, can immediately check if regex // matches from this point onward, return true since the * does not need to consume any characters. if (matchHere(regexCounter, stringCounter)) { return true; }; // If consuming 0 characters fails, consume one character and check, then continue consuming a character and checking if the regex pattern // matches until there are no more characters to consume. stringCounter++; while (stringCounter !== string.length && (string[stringCounter] === starChar || starChar === '.')) { if (matchHere(regexCounter, stringCounter)) { return true; } stringCounter++; } // If the regex pattern was never able to match return false return false; }; // This is a greedy implementation of plus. It will match / consume as many character as possible. If matching the regex pattern after it has coonsumed // as many characters as possible fails, then it will relinquish a character and try again, repeating this process until only one character remains. If // the regex still fails to match at that point, then it will return false. function matchPlus(plusChar, regexCounter, stringCounter) { // Count for keeping track of how many characters have been matched. Minimum is 1 for plus to be successful. var numFound = 0; // If the first character doesn't match (and we're not using a . to match all characters) then return false if (string[stringCounter] !== plusChar && plusChar !== '.') { return false; } // This is where the greediness happens. Keep incrementing stringCounter (equivalent to consuming a character) until the character no longer matches while (string[stringCounter] === plusChar || (plusChar === '.' && stringCounter !== string.length)) { stringCounter++; numFound++; } // After greedily consuming all the characters, check if the regamining regex/string combination matches. if (matchHere(regexCounter, stringCounter) && numFound >= 1) { return true; } // If it doesn't match, then relinquish a character and try again. Continue doing so until a match is found, or all characters (except one) have // been relinquished. If only one character remains and the pattern has not matched, then return false as plus requires at least one character match. else { stringCounter--; numFound--; while (string[stringCounter] === plusChar || (plusChar === '.' && stringCounter !== string.length && stringCounter !== 0)) { if (matchHere(regexCounter, stringCounter) && numFound >= 1) { return true; } stringCounter--; numFound--; } return false; } }; // This function is for instruction only, it shows what a lazy (non-greedy) implementation of match plus would look like. It handles certain pathological // regex patterns / string combinations (like regex: a+a+a+a+a+a+a+a+ and string: aaaaaaaaaaaaaaaaaaaaaab) much more efficiently function matchPlusLazy(plusChar, regexCounter, stringCounter) { var numFound = 0; if (string[stringCounter] !== plusChar && plusChar !== '.') { return false; } // This is lazy (non-greedy) implementation. It consumes on character only, then tries to match the remaining regex / string. If that fails, it then consumes // another token. Rinse and repeat until it reaches the end of the string. while (string[stringCounter] === plusChar || (plusChar === '.' && stringCounter !== string.length)) { stringCounter++; numFound++; if (matchHere(regexCounter, stringCounter) && numFound >= 1) { return true; } } // Return false if it never matches return false; }; return match(); } // Simple testing functionality var tester = { numAssertions: 0, numSuccessful: 0, runTest: function(regex,string, result) { this.numAssertions++; if (regexEngine(regex, string) === result) { this.numSuccessful++; } }, finishTests: function() { console.log('Tests complete: ' + this.numSuccessful + '/' + this.numAssertions + ' assertions successful'); } }; tester.runTest('a','a', true); tester.runTest('a', 'b', false); tester.runTest('ab', 'ab', true); tester.runTest('ab', 'abc', true); tester.runTest('ab$', 'abc', false); tester.runTest('^dab', 'dabb', true); tester.runTest('a*b', 'b', true); tester.runTest('a*b', 'ab', true); tester.runTest('a*b', 'aaaaab', true); tester.runTest('a*b', 'a', false); tester.runTest('a+', 'a', true); tester.runTest('a+', 'ab', true); tester.runTest('a+', 'b', false); tester.runTest('a+', '', false); tester.runTest('.*ab', 'asdfadsab', true); tester.runTest('.*ab', 'ab', true); tester.runTest('.*ab', 'absdfadsfa', true); tester.runTest('.+ab', 'asdfadsab', true); tester.runTest('.+ab', 'ab', false); tester.runTest('.+ab', 'absdfadsfa', false); tester.runTest('.+ab', 'aab', true); tester.runTest('d+a+bb', 'dabb', true); tester.runTest('d+a+abb', 'dabb', false); tester.runTest('d+a+a*bb', 'dabb', true); tester.runTest('d+a+a*bb', 'daaaaaabb', true); // Example of a pathological regex / string combination that causes a LOT of backtracking with the greedy plus character, potentially crashes browser in some cases. // However if its run with the lazy version of matchPlus, it executes extremely quickly. // tester.runTest('a+a+a+a+a+a+a+a+a+', 'aaaaaaaaaaaaaaaaaaaaaab', true); tester.finishTests();<file_sep>/README.md # Simple Regex Engine in JavaScript (Backtracking Algorithm) **Note:** This README is relatively brief because the source code is verbosely documented. This is a simple implementation of a regex engine in JavaScript that uses a traditional "backtracking" algorithm to match regular expression patterns against strings. The engine handles the following special regular expression characters: 1. ^ Beginning of string 2. $ End of string 3. * Match previous expression 0 or more times 4. + Match previous expression 1 or more times This code was written to learn about how backtracking regular expresssion engines work (as such its heavily commented), as well as how certain toxic regular expression / string combinations can cause backtracking engines to take exponential time to determine if a match exists. It started off as being a simple translation of the C program specified in Resources[2], however, I modified it to include extra functionality such as handling the + character, as well as a simple testing suite. ## Next Steps At some point, I'd like to return to this project and implement a non-recursive NFA/DFA solution, however, I have to finish writing my hack compiler first :) ## Resources: 1. https://swtch.com/~rsc/regexp/regexp1.html 2. http://www.ddj.com/architect/184410904 --- Simple backtracking algorithm implemented in C 3. http://www.codeproject.com/Articles/5412/Writing-own-regular-expression-parser --- For when I decide to write the NFA/DFA solution 4. http://www.regular-expressions.info/
1a8c6005fab4da01183c22741dd77442e4e03ae8
[ "JavaScript", "Markdown" ]
2
JavaScript
richardartoul/regex-engine
e61aad510e506f14de754231f230b1d431d8c7be
0dae8fa93f9b5748816e87901a389bd058b6f726
refs/heads/master
<file_sep>use std::env; use std::path::Path; use std::fs::File; use std::io::prelude::*; fn simd_type(w: &mut Write, t: &str, width: u32, length: u32) { assert!(length >= 2); assert!(t == "f" || t == "u" || t == "i"); let ty = format!("{}{}", t, width); let mut contents = String::new(); for _ in (0..length) { if !contents.is_empty() { contents.push_str(", ") } contents.push_str("pub "); contents.push_str(&ty); } writeln!(w, "\ #[simd] #[derive(Copy, Clone, Debug)] /// {length} values of type {ty} in a single SIMD vector. pub struct {ty}x{length}({contents});", ty=ty, length=length, contents=contents).unwrap() } fn main() { let path = env::var("OUT_DIR").unwrap(); let dst = Path::new(&path); let mut out = File::create(&dst.join("types.rs")).unwrap(); for length in [2, 4, 8, 16, 32, 64].iter().cloned() { for &int in ["i", "u"].iter() { for &int_width in [8, 16, 32, 64].iter() { simd_type(&mut out, int, int_width, length) } } let float = "f"; for &float_width in [32, 64].iter() { simd_type(&mut out, float, float_width, length) } } } <file_sep>[package] name = "simdty" version = "0.0.3" authors = ["<NAME> <<EMAIL>>"] homepage = "https://github.com/huonw/simdty" repository = "https://github.com/huonw/simdty" documentation = "http://huonw.github.io/simdty/simdty/" license = "MIT/Apache-2.0" keywords = ["numerics", "simd"] readme = "README.md" description = """ Definitions of many SIMD types. """ build = "build.rs" [features] unstable = [] <file_sep>#![feature(simd)] #![allow(non_camel_case_types)] //! Definitions of many SIMD types of fixed lengths. include!(concat!(env!("OUT_DIR"), "/types.rs"));
a23e20227adf52ae083861d46efbac333063ef1e
[ "TOML", "Rust" ]
3
Rust
huonw/simdty
18e9f5101ad8fde72acbda3eb161a1e70354c3f6
3a22131c648efde1639b368c3f2f5b04d295b2d3
refs/heads/master
<repo_name>mo-spec1/mo-spec1-sauclabsdemo<file_sep>/src/test/java/com/saucedemo/Readme.md Project Overview: 1) How to run the project - Access the Runner via this path src/test/java/com/saucedemo/runner - Right-click on the TestRunner class - Click on Run 'TestRunner' - At this stage your test should all run successfully 2) How to generate the report - Navigate to this path 'target/Pretty-cucumber/cucumber-html-reports' - Right-click on the last file in this folder - Hover over 'Open in Browser' and select desired browser - The report should be generated<file_sep>/src/test/java/com/saucedemo/pages/OverviewPage.java package com.saucedemo.pages; import org.junit.Assert; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; public class OverviewPage extends BasePage { public OverviewPage (WebDriver driver) { this.driver = driver; PageFactory.initElements(driver, this); } @FindBy (className = "subheader") private WebElement overviewHeader; public void isOverviewPageVisible() { Assert.assertTrue(overviewHeader.isDisplayed()); } @FindBy (css = ".btn_action.cart_button") private WebElement finishButton; public ThankYouPage clickOnTheFinishButton() { finishButton.click(); return new ThankYouPage(driver); } } <file_sep>/src/test/java/com/saucedemo/pages/BasePage.java package com.saucedemo.pages; import com.saucedemo.common.Driver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; public class BasePage extends Driver { public String BaseURL = "https://www.saucedemo.com/"; public Select select; public void launchURL() { driver.navigate().to(BaseURL); } public void selectByText(WebElement element, String text) { select = new Select(element); select.selectByVisibleText(text); } public void selectByValue (WebElement element, String value) { select = new Select(element); select.selectByValue(value); } public void selectByIndex(WebElement element, int index) { select = new Select (element); select.selectByIndex(index); } public void waitForElementToBeDisplayed(WebElement element) { wait = new WebDriverWait(driver,10); wait.until(ExpectedConditions.visibilityOf(element)); } } <file_sep>/src/test/java/com/saucedemo/pages/ThankYouPage.java package com.saucedemo.pages; import org.junit.Assert; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; public class ThankYouPage extends BasePage { public ThankYouPage (WebDriver driver) { this.driver = driver; PageFactory.initElements(driver, this); } @FindBy(className = "complete-header") private WebElement thankYouHeader; public void isThankYouHeaderVisible() { Assert.assertTrue(thankYouHeader.isDisplayed()); } }
ece49c4a855690abc98da3f8eb83915059bd9238
[ "Markdown", "Java" ]
4
Markdown
mo-spec1/mo-spec1-sauclabsdemo
2efadbc48bd0577fb7df1668dc1610950451db5c
9eb2d3c80c57421e4f3ab7947123df35bf0b15ab
refs/heads/main
<repo_name>XueWang2019/Arvato_customer_segmentation<file_sep>/etl.py #!/usr/bin/env python # coding: utf-8 # In[1]: # import libraries here; add more as necessary import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # magic word for producing visualizations in notebook get_ipython().run_line_magic('matplotlib', 'inline') # In[2]: from sklearn.metrics import roc_auc_score from sklearn.cluster import KMeans from sklearn.decomposition import PCA from sklearn.model_selection import train_test_split #pd.options.mode.chained_assignment = None # In[3]: from sklearn import preprocessing from sklearn.preprocessing import StandardScaler from imblearn.over_sampling import SMOTE from imblearn.combine import SMOTEENN from sklearn.ensemble import RandomForestClassifier from xgboost import XGBClassifier from sklearn.linear_model import LogisticRegression from sklearn.metrics import confusion_matrix, accuracy_score # In[ ]: from sklearn.model_selection import GridSearchCV # In[ ]: def get_to_know_data(df): print("shape: {}".format(df.shape)) print('') print("info: {}".format(df.info())) print('') print("Thers is {} duplicated records".format(sum(df.duplicated()))) # In[ ]: def plot1(df): ''' This function is to plot the null value percentage in column wise input: dataframe ''' df_null=(df.isnull().sum()/df.shape[0]).sort_values(ascending=False) df_null=pd.DataFrame(df_null,columns=['percentage']) print("null value percentage description: {}".format(df_null.describe())) # when customers_null is dataframe, use data and x plt.figure(figsize=(15,5)) bins = np.arange(0, df_null.values.max(), 0.005) plt.hist(data = df_null, x = 'percentage', bins = bins) plt.title('Null value percentage in column wise') plt.xlabel('Null value percentage in column wise') plt.ylabel('Column count') plt.xticks(np.arange(0, df_null.values.max()+0.05, 0.05)); # In[1]: def data_clean(val2,df): #1. check the most missing value columns #as there are two columns, use zip # The target is: if a is in azdias columns, for all val1 in b, replace the vala as nan # The most intelligent part is for all for a,b in zip(val2.feature,val2.new): if a in df.columns: #print(a) for val1 in b: df[a]=df[a].replace(val1,np.nan) # now check the missing values in columns for azdias, # The target is that if the missing values is higher than a certain percentage, the column can be reduced df_null_col=df.isnull().sum().sort_values(ascending=False) df_null_col_per=df_null_col/df.shape[0] df_null_list=[keys for keys,values in df_null_col_per.items() if values>0.9] # del the columns from df_azd_null_list as below for i in df_null_list: del df[i] #2. now clean the object data # further clean the other value which hasn't been found previously into nan df.loc[df['CAMEO_DEU_2015']=='XX', 'CAMEO_DEU_2015']=np.nan # Replace the nan with the most frequent value, use mode() df.loc[df['CAMEO_DEU_2015'].isnull(), 'CAMEO_DEU_2015']=df['CAMEO_DEU_2015'].mode()[0] df.loc[df['CAMEO_DEUG_2015']=='X', 'CAMEO_DEUG_2015']=np.nan # set nan as the most frequent value df.loc[df['CAMEO_DEUG_2015'].isnull(), 'CAMEO_DEUG_2015']=df['CAMEO_DEUG_2015'].mode()[0] # unify the type as int64 df['CAMEO_DEUG_2015']=df['CAMEO_DEUG_2015'].astype('int64') df.loc[df['CAMEO_INTL_2015']=='XX', 'CAMEO_INTL_2015']=np.nan df.loc[df['CAMEO_INTL_2015'].isnull(), 'CAMEO_INTL_2015']=df['CAMEO_INTL_2015'].mode()[0] # unify the type as int64 df['CAMEO_INTL_2015']=df['CAMEO_INTL_2015'].astype('int64') df.loc[df['D19_LETZTER_KAUF_BRANCHE'].isnull(), 'D19_LETZTER_KAUF_BRANCHE']=df['D19_LETZTER_KAUF_BRANCHE'].mode()[0] df.loc[df['EINGEFUEGT_AM'].isnull(), 'EINGEFUEGT_AM']=df['EINGEFUEGT_AM'].mode()[0] # only care about the inserted year df['EINGEFUEGT_AM']=pd.to_datetime(df['EINGEFUEGT_AM']).dt.year df.loc[df['OST_WEST_KZ'].isnull(), 'OST_WEST_KZ']=df['OST_WEST_KZ'].mode()[0] df['OST_WEST_KZ'].replace(to_replace=['W','O'],value=[0,1],inplace=True) #After checking the value attributes, I think CMEO-DEU-2015 is detail info for CMEO-DEUG-2015, which can be represent by it #The D19_LETZTER_KAUF_BRANCHE no need to encoding, as it is just summarized of the other info #LNR is the identification, can be dropped df_index=df['LNR'] del df['CAMEO_DEU_2015'], df['D19_LETZTER_KAUF_BRANCHE'],df['LNR'] # In my ETL file, I also delete the raw records in row with nan percentage >=0.5, that can be as a practis, here I don't touch it # fill all of the other nan as column's mean() fill_mode = lambda col: col.fillna(col.mode()[0]) df=df.apply(fill_mode, axis=0) ''' drop row with most missing value df.ind=[] df.loc[(df_azdias_pca.isnull().sum(axis=1).sort_values(ascending=False))/(df.shape[1])>=0.5,'ind']=1 df.loc[(df_azdias_pca.isnull().sum(axis=1).sort_values(ascending=False))/(df.shape[1])<0.5,'ind']=0 df['ind']=df_azdias_pca['ind'].astype('int64') df.drop(df[df['ind']==1].index) ''' return df, df_index # save cleaned azdias data #df.to_csv('2_cleaned_data.csv',index=False) # In[ ]: def do_pca(n_components, data): ''' Transforms data using PCA to create n_components, and provides back the results of the transformation. INPUT: n_components - int - the number of principal components to create data - the data you would like to transform OUTPUT: pca: pca object after instatiant X_pca: new matrix after the instatiant being fit and transformed X: is not input or output, but better to mention that it is the scaled (standardized) data from the original ''' X = StandardScaler().fit_transform(data) pca = PCA(n_components) X_pca = pca.fit_transform(X) return pca, X_pca # In[ ]: def print_weights(n): ''' n: number of principal component ''' components = pd.DataFrame(np.round(pca.components_[n - 1: n], 4), columns = azdias.keys()) components.index = ['Weights'] components = components.sort_values(by = 'Weights', axis = 1, ascending=False) components = components.T print(components) return components # In[ ]: def scree_plot_1(pca): ''' Creates a scree plot associated with the principal components INPUT: pca - the result of instantian of PCA in scikit learn OUTPUT: None ''' num_components = len(pca.explained_variance_ratio_) ind = np.arange(num_components) vals = pca.explained_variance_ratio_ plt.figure(figsize=(10, 6)) ax = plt.subplot(111) cumvals = np.cumsum(vals) ax.bar(ind, vals) ax.plot(ind, cumvals) ''' for i in range(num_components): ax.annotate(r"%s%%" % ((str(vals[i]*100)[:4])), (ind[i]+0.2, vals[i]), va="bottom", ha="center", fontsize=12) ''' ax.xaxis.set_tick_params(width=0) ax.yaxis.set_tick_params(width=2, length=12) ax.set_xlabel("Principal Component") ax.set_ylabel("Variance Explained (%)") plt.title('Explained Variance Per Principal Component') # In[ ]: def scree_plot_2(pca): ''' Creates a scree plot associated with the principal components INPUT: pca - the result of instantian of PCA in scikit learn OUTPUT: None ''' num_components = len(pca.explained_variance_ratio_) ind = np.arange(num_components) vals = pca.explained_variance_ratio_ plt.figure(figsize=(10, 6)) ax = plt.subplot(111) cumvals = np.cumsum(vals) ax.bar(ind, vals) ax.plot(ind, cumvals) for i in range(num_components): ax.annotate(r"%s%%" % ((str(vals[i]*100)[:4])), (ind[i]+0.2, vals[i]), va="bottom", ha="center", fontsize=12) ax.xaxis.set_tick_params(width=0) ax.yaxis.set_tick_params(width=2, length=12) ax.set_xlabel("Principal Component") ax.set_ylabel("Variance Explained (%)") plt.title('Explained Variance Per Principal Component') # In[ ]: # now fit the decomposited data to kmeans # it takes time # use elbow method to find the best k def model_kmeans(X_pca): get_ipython().run_line_magic('time', '') SSE = [] # 存放每次结果的误差平方和 for k in range(2, 11): #stimator = KMeans(n_clusters=k) # 构造聚类器 #estimator.fit(np.array(mdl[['Age', 'Gender', 'Degree']])) #SSE.append(estimator.inertia_) k_means = KMeans(init = "k-means++", n_clusters = k) k_means.fit(X_pca) SSE.append(k_means.inertia_) X = range(2, 11) plt.xlabel('k') plt.ylabel('SSE') plt.plot(X, SSE, 'o-') plt.show() return k_means # In[ ]: def plot_comparision(df): #plt.figure(figsize=figsize) plt.bar(df.cluster, df.percentage) plt.xlabel('Cluster label', fontsize=14) plt.xticks(fontsize=14) plt.yticks(fontsize=14) plt.title('1', fontsize=18) #plt.gca().invert_yaxis(); <file_sep>/readme.md # Arvato_customer_segmentation ## Libraries: * numpy * pandas * matplotlib * seaborn * sklearn * imblearn * xgboost ## Motivation Nowadays, with big data becomes reality, people now focus on how to use the data to realize commercial values. One area which is much more mature is how to picture the potential customer or predict the behavior of the customer, to target the market or customer more precisely. Bertelsman Arvato Finaincial Solution has provided a challenge: how to target the population and convert them into a mailout company's customers more efficiently. ## Summary: The work I have implemented in this project summarized as below: * Exploratory the demographics data: general population of Germany, customers of a mail-order company, and market campaign train and test datasets. * Cleaned the dataset and select features. * Used PCA and KMeans to cluster the population.  * Analyzed the higher potential clusters' top 10 features to get a relatively clear picture of the target population * Applied supervised machine learning with RandomForestClassifier, LogisticsRegression, and XGBClassifier, GridsearchCV to develop a model that can label the positive response probability to a market campaign.  ## Takesaways: Through the iteration process, I realized that the different estimators might improve the performance a bit, but in order to approach the real limitation, I still have to come back to the first step to process the data more precisely, which is the basis of improving the model performance. ```python ```
64bdb4cf859c8bc5b9479ef7a9ae1b956bd554b8
[ "Markdown", "Python" ]
2
Python
XueWang2019/Arvato_customer_segmentation
3c239d974b4e9df131ceed0915a54e95e8d0b0a4
e57f1ce6c59a34ec7fc381101e3093aa03d5cc62
refs/heads/main
<file_sep>from random import randint,sample import time password=chr(randint(65,90)) password+=chr(randint(65,90)) password+=str(randint(0,9)) password+=str(randint(0,9)) password+=chr(randint(97,122)) password+=chr(randint(97,122)) password+=chr(64) finalpass=''.join(sample(password,len(password))) print(finalpass) time.sleep(10)
df4aea6527f68ac89b36306c08f49fa597d8f217
[ "Python" ]
1
Python
JaySurana0710/Password-Generator
c20740cc36136444f2ba5ee7d947e96b6ebebe49
0e64b8c0ef1be30ea669a3d4cf1be1f55d8a05d3
refs/heads/master
<file_sep><?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. // original plugin by 2013 <NAME> <<EMAIL>> /** * Defines the version of videostream. * * This code fragment is called by moodle_needs_upgrading() and * /admin/index.php. * * @package block_video * @copyright 2020 Chaya@openapp * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ // defined('MOODLE_INTERNAL') || die; require_once(__DIR__ . '/../../../config.php'); global $USER, $DB; $videos = optional_param('videos',null, PARAM_RAW); $course = required_param('course', PARAM_RAW); $courseid = explode('-', $course)[1]; $videos = json_decode($videos); //print_r($videos);die; foreach ($videos as $vid) { $video = $DB->get_record('block_video_course', ['courseid' => $courseid, 'videoid' => $vid->id]); if (isset($video) && !empty($video)) { if ($vid->checked == false) { $DB->delete_records('block_video_course', ['courseid' => $courseid, 'videoid' => $vid->id]); } } else if ($vid->checked == true) { $v = new stdClass(); $v->videoid = $vid->id; $v->courseid = $courseid; $v->usermodifiedid = $USER->id; $v->timemodified = time(); $DB->insert_record('block_video_course', $v); } } print_r($CFG->wwwroot . '/course/view.php?id=' . $courseid);<file_sep><?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. // original plugin by 2013 <NAME> <<EMAIL>> /** * Defines the version of videostream. * * This code fragment is called by moodle_needs_upgrading() and * /admin/index.php. * * @package block_video * @copyright 2020 Chaya@openapp * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); class block_video extends block_base { public function init() { $this->title = get_string('video', 'block_video'); } // The PHP tag and the curly bracket for the class definition // will only be closed after there is another function added in the next section. function has_config() { return true; } public function get_content() { global $OUTPUT, $COURSE, $PAGE, $CFG, $USER, $DB; // Do not show block content for guest or non logged on user // There should be a right way of doing this... // require_login() make infinite redirects // --Yedidia if ($USER->id <= 1) { return ""; } if ($this->content !== null) { return $this->content; } require_once(__DIR__ . '/locallib.php'); $PAGE->requires->js(new moodle_url($CFG->wwwroot . '/blocks/video/javascript/javascript.js')); $hiddenzoomvideos = get_config('block_video', 'hiddenzoomvideos'); $videos = get_videos_from_zoom($COURSE->id); $videos = array_map(function($v) { if (isset($v->hidden) && !empty($v->hidden)) { $obj = (array)$v; $obj['hiddenclass'] = 'fa-eye-slash'; $v = (object)$obj; } else { $obj = (array)$v; $obj['hiddenclass'] = $hiddenzoomvideos? 'fa-eye-slash' :'fa-eye'; $v = (object)$obj; } return $v; }, $videos); $zoomvideos = get_videos_from_video_directory_by_course($COURSE); $this->content = new stdClass;; $contextcourse = context_course::instance($COURSE->id); $data = [ 'wwwroot' => $CFG->wwwroot, 'dirrtl' => current_language() == 'he' ? true : false, 'course' => $COURSE->id, 'canaddlocalvideos' => has_capability('block/video:addlocalvideos', $contextcourse), 'caneditnamevideo' => has_capability('block/video:editnamevideo', $contextcourse), 'showingpreferencelist' => get_showingprefernece_of_user() == 'list' ? true : false, 'videos' => $videos, 'showvideos' => is_array($videos) && count($videos) > 0 ? true : false, 'zoomvideos' => $zoomvideos, 'showzoomvideos' => count($zoomvideos) > 0 || has_capability('block/video:addlocalvideos', $contextcourse) ? true : false, 'haszoomvideos' => count($zoomvideos) > 0 ? true : false, 'showheader' => count($zoomvideos) > 0 || count($videos) > 0 ? true : false ]; //if (!(count($zoomvideos) > 0 && !(count($videos)) || has_capability('block/video:addlocalvideos', $contextcourse)) ) { // return $this->content; //} $this->content->text = $OUTPUT->render_from_template('block_video/blockvideo', $data); return $this->content; } } <file_sep><?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. // original plugin by 2013 <NAME> <<EMAIL>> /** * * This code fragment is called by moodle_needs_upgrading() and * /admin/index.php. * * @package block_video * @copyright 2020 Chaya@openapp * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die; require_once( __DIR__ . '/../../config.php'); require_once($CFG->dirroot . '/local/video_directory/locallib.php'); function block_video($id , $courseid) { $output = "<div class='videostream'>"; $config = get_config('videostream'); if (($config->streaming == "symlink") || ($config->streaming == "php")) { $output .= block_video_get_video_videojs($config->streaming, $id, $courseid); } else if ($config->streaming == "hls" || ($config->streaming == "vimeo" && !$config->vimeoplayer)) { // Elements for video sources. (here we get the hls video). $output .= block_video_get_video_hls($id, $courseid); } else if($config->streaming == "vimeo") { $output .= block_video_get_video_vimeo($id, $courseid); } $output .= block_video_get_bookmark_controls($id); $output .= html_writer::end_tag('video'); $output .= "</div>"; return $output; } function get_video_source_elements_vimeo($videostream) { global $CFG, $OUTPUT, $DB; $video = $DB->get_record('local_video_directory', ['id' => $videostream->get_instance()->videoid]); $videovimeo = $DB->get_record('local_video_directory_vimeo', ['videoid' => $videostream->get_instance()->videoid]); $data = array('width' => $width, 'height' => $height, 'symlinkstream' => $videovimeo->streamingurl, 'type' => 'video/mp4', 'wwwroot' => $CFG->wwwroot, 'video_id' => $video->id, 'video_vimeoid' => $videovimeo->vimeoid); $output = $OUTPUT->render_from_template("mod_videostream/vimeo", $data); $output .= $this->video_events($videostream, 1); return $output; } function block_video_get_video_vimeo($id, $courseid) { global $CFG, $OUTPUT, $DB; $width = '800px'; $height = '500px'; $videovimeo = $DB->get_record('local_video_directory_vimeo', ['videoid' => $id]); $data = array('width' => $width, 'height' => $height, 'symlinkstream' => $videovimeo->streamingurl, 'type' => 'video/mp4', 'wwwroot' => $CFG->wwwroot, 'video_id' => $id, 'video_vimeoid' => $videovimeo->vimeoid); $output = $OUTPUT->render_from_template("block_video/vimeo", $data); //$output .= block_video_events($id, $courseid); return $output; } function block_video_get_video_videojs($type, $id, $courseid) { global $CFG, $OUTPUT; $width = '800px'; $height = '500px'; $videolink = block_video_createsymlink($id); $data = array('width' => $width, 'height' => $height, 'videostream' => $videolink, 'wwwroot' => $CFG->wwwroot, 'videoid' => $id, 'type' => 'video/mp4'); $output = $OUTPUT->render_from_template("block_video/hls", $data); $output .= block_video_events($id, $courseid); return $output; } function block_video_createHLS($videoid) { global $DB; $config = get_config('videostream'); $id = $videoid; $streams = $DB->get_records("local_video_directory_multi", array("video_id" => $id)); if ($streams) { foreach ($streams as $stream) { $files[] = $stream->filename; } $hls_streaming = $config->hls_base_url; } else { $files[] = local_video_directory_get_filename($id); $hls_streaming = $config->hlsingle_base_url; } $parts = array(); foreach ($files as $file) { $parts[] = preg_split("/[_.]/", $file); } $hls_url = $hls_streaming . $parts[0][0]; if ($streams) { $hls_url .= "_"; foreach ($parts as $key => $value) { $hls_url .= "," . $value[1]; } } $hls_url .= "," . ".mp4".$config->nginx_multi."/master.m3u8"; return $hls_url; } function block_video_events($id, $courseid) { global $CFG, $DB; $context = context_course::instance($courseid); $sesskey = sesskey(); $jsmediaevent = "<script language='JavaScript'> var v = document.getElementsByTagName('video')[0]; v.addEventListener('seeked', function() { sendEvent('seeked'); }, true); v.addEventListener('play', function() { sendEvent('play'); }, true); v.addEventListener('stop', function() { sendEvent('stop'); }, true); v.addEventListener('pause', function() { sendEvent('pause'); }, true); v.addEventListener('ended', function() { sendEvent('ended'); }, true); v.addEventListener('ratechange', function() { sendEvent('ratechange'); }, true); function sendEvent(event) { console.log(event); require(['jquery'], function($) { $.post('" . $CFG->wwwroot . "/blocks/video/ajax/event_ajax.php', { videoid: " . $id . ", contextid: ".$context->id .", action: event, sesskey: '" . $sesskey . "' } ); }); } </script>"; return $jsmediaevent; } function is_teacher($user = '') { global $USER, $COURSE; if (is_siteadmin($USER)) { return true; } // Check if user is editingteacher. $context = context_course::instance($COURSE->id); $roles = get_user_roles($context, $USER->id, true); $keys = array_keys($roles); foreach ($keys as $key) { if ($roles[$key]->shortname == 'editingteacher') { return true; } } return false; } function block_video_get_bookmark_controls($videoid) { global $DB, $USER, $OUTPUT; $output = ''; $isteacher = is_teacher(); $sql = "select * from {block_video_bookmarks} where (userid =? or permission = ?) and video_id = ?"; $bookmarks = $DB->get_records_sql($sql, ['userid' => $USER->id, 'permission' => 'public', 'video_id' => $videoid]); $bookmarks = array_values(array_map(function($a) { $a->bookmarkpositionvisible = gmdate("H:i:s", (int)$a->videoposition); $a->permission = $a->permission == 'public'? 1: 0; return $a; }, $bookmarks)); //print_r($bookmarks);die; $submit = get_string('submitbookmark' , 'block_video' ); $output .= $OUTPUT->render_from_template('block_video/bookmark_controls', ['bookmarks' => $bookmarks, 'video_id' => $videoid, 'isteacher' => $isteacher, 'submit' => $submit, 'userid' => $USER->id]); return $output; } function block_video_get_video_hls($id, $courseid) { global $CFG, $OUTPUT, $PAGE, $DB; $width = '800px'; $height = '500px'; $config = get_config('videostream'); if ($config->streaming == "vimeo") { $hlsstream = $DB->get_field_sql("SELECT streaminghls FROM {local_video_directory_vimeo} WHERE videoid = ? limit 1", ['videoid' => $id]); } else { $hlsstream = block_video_createHLS($id); } $data = array('width' => $width, 'height' => $height, 'videostream' => $hlsstream, 'wwwroot' => $CFG->wwwroot, 'videoid' => $id, 'type' => 'application/x-mpegURL'); $output = $OUTPUT->render_from_template("block_video/hls", $data); $output .= block_video_events($id, $courseid); return $output; } function block_video_createsymlink($videoid) { global $DB; $filename = $DB->get_field('local_video_directory', 'filename', [ 'id' => $videoid ]); if (substr($filename, -4) != '.mp4') { $filename .= '.mp4'; } $config = get_config('local_video_directory'); return $config->streaming . "/" . $filename; } function get_videos_from_zoom($courseid = null) { global $COURSE, $DB, $USER, $CFG; $filename = $CFG->dirroot . '/local/video_directory/cloud/locallib.php'; if (file_exists($filename)) { require_once($CFG->dirroot . '/local/video_directory/cloud/locallib.php'); } $course = $DB->get_record("course", ["id"=> $courseid]); if ($course == null) { $course = $COURSE; } $result = []; $streamingurl = get_config('local_video_directory', 'streaming') . '/'; $sql = "SELECT DISTINCT vv.id, vv.orig_filename as name, vv.filename,vv.timemodified, vv.timecreated, thumb, vv.length, bv.hidden FROM {local_video_directory} vv LEFT JOIN {local_video_directory_zoom} vz ON vv.id = vz.video_id LEFT JOIN {zoom} z ON z.meeting_id = vz.zoom_meeting_id LEFT JOIN {block_video} as bv ON vv.id = bv.videoid WHERE z.course = ?"; $videos = $DB->get_records_sql($sql, [$course->id]); foreach ($videos as $video) { $video->source = $CFG->wwwroot . '/blocks/video/viewvideo.php?id=' . $video->id . '&courseid=' . $course->id . '&type=2'; if (get_config('local_video_directory_cloud', 'cloudtype') == 'Vimeo') { if(!isset(get_data_vimeo($video->id)->streamingurl)) { unset($videos[$video->id]); } } else { if ( ! check_file_exist($streamingurl . $video->filename . '.mp4')) { unset($videos[$video->id]); continue; } } if (get_config('local_video_directory_cloud', 'cloudtype') == 'Vimeo') { $video->imgurl = get_data_vimeo($video->id)->thumburl; if (!isset($video->imgurl)) { $video->imgurl = ''; } } else { $video->imgurl = $CFG->wwwroot . '/local/video_directory/thumb.php?id=' . $video->id . '&mini=1'; } $video->date = date('d-m-Y H:i:s', $video->timecreated); } return array_values($videos); } function sortdate($a, $b) { $a = strtotime($a->date); $b = strtotime($b->date); return $a < $b ? 1 : -1; } function get_showingprefernece_of_user($userid = null) { global $USER, $COURSE, $DB; if ($userid == null) { $userid = $USER->id; } $data = $DB->get_field('block_video_preferences', 'data', ['userid' => $userid, 'courseid' => $COURSE->id, 'name' => 'videosdisplay']); if (!isset($data) || empty($data) || $data == '') { $data = get_config('block_video', 'defaultshowingvideos'); } return $data; } function get_videos_from_video_directory_by_course($course = null) { global $COURSE, $DB, $USER, $CFG; $filename = $CFG->dirroot . '/local/video_directory/cloud/locallib.php'; if (file_exists($filename)) { require_once($CFG->dirroot . '/local/video_directory/cloud/locallib.php'); } if ($course == null) { $course = $COURSE; } $result = []; $streamingurl = get_config('local_video_directory', 'streaming') . '/'; $sql = 'SELECT vid.id, vid.orig_filename name, vid.filename, length, vid.timemodified, vid.timecreated, vc.courseid from mdl_block_video_course vc join mdl_local_video_directory vid on vid.id = vc.videoid where vc.courseid = ? ORDER BY vid.timemodified desc'; $videos = $DB->get_records_sql($sql, [$course->id]); foreach ($videos as $video) { $video->source = $CFG->wwwroot . '/blocks/video/viewvideo.php?id=' . $video->id . '&courseid=' . $course->id . '&type=2'; if (get_config('local_video_directory_cloud', 'cloudtype') == 'Vimeo') { if(!isset(get_data_vimeo($video->id)->streamingurl)) { unset($videos[$video->id]); } } else { if ( !check_file_exist($streamingurl . $video->filename . '.mp4')) { unset($videos[$video->id]); continue; } } $video->imgurl = $CFG->wwwroot . '/local/video_directory/thumb.php?id=' . $video->id . '&mini=1'; $video->date = date('d-m-Y H:i:s', $video->timecreated); } return array_values($videos); } /* * This function return the list of videos from video directory for choose. * Params: * $course - optional. If not - global course * $userid - optional. If not - global user->id * $public - optional. * Return true if the file exist and flase if not. */ function get_videos_from_video_directory_by_owner($course = null, $userid = null, $public = false) { global $DB, $USER, $COURSE, $CFG; $filename = $CFG->dirroot . '/local/video_directory/cloud/locallib.php'; if (file_exists($filename)) { require_once($CFG->dirroot . '/local/video_directory/cloud/locallib.php'); } if ($userid == null) { $userid = $USER->id; } if ($course == null) { $course = $COURSE; } $admins = get_admins(); $isadmin = false; foreach ($admins as $admin) { if ($userid == $admin->id) { $isadmin = true; break; } } $streamingurl = get_config('local_video_directory', 'streaming') . '/'; if ($isadmin) { $sql = 'SELECT vid.id, vid.orig_filename name, vid.filename, length, vid.timemodified, vid.timecreated, vc.courseid ,vid.private, vid.owner_id, concat(u.firstname, " ", u.lastname) as ownername from mdl_local_video_directory vid left join mdl_block_video_course vc on vid.id = vc.videoid and vc.courseid = ? left join mdl_user u on vid.owner_id = u.id where (vid.owner_id in (SELECT userid FROM mdl_role_assignments as a join mdl_context as c on a.contextid = c.id where a.roleid = 3 and c.contextlevel = 50 and c.instanceid = ? ) or private = 0) OR vc.courseid = ? ORDER BY name'; $videos = $DB->get_records_sql($sql, [$course->id, $course->id, $course->id]); } else { $sql = 'SELECT vid.id, vid.orig_filename name, vid.filename, length, vid.timemodified, vid.timecreated, vc.courseid ,vid.private, vid.owner_id, concat(u.firstname, " ", u.lastname) as ownername from mdl_local_video_directory vid left join mdl_block_video_course vc on vid.id = vc.videoid and vc.courseid = ? left join mdl_user u on vid.owner_id = u.id where (vid.owner_id = ? or private = 0) OR vc.courseid = ? ORDER BY name'; $videos = $DB->get_records_sql($sql, [ $course->id, $userid, $course->id]); } foreach ($videos as $video) { $video->select = $video->courseid == $course->id ? true : false; $video->source = $streamingurl . $video->filename . '.mp4'; if (get_config('local_video_directory_cloud', 'cloudtype') == 'Vimeo') { if(!isset(get_data_vimeo($video->id)->streamingurl)) { unset($videos[$video->id]); } } else { if ( !check_file_exist($video->source)) { unset($videos[$video->id]); continue; } } $video->imgurl = $CFG->wwwroot . '/local/video_directory/thumb.php?id=' . $video->id . '&mini=1'; $video->canedit = $video->owner_id == $USER->id || $video->private == 0 || $isadmin ? true : false; $video->public = $video->private == 0 ? get_string('yes') : get_string('no'); $video->date = date('d-m-Y H:i:s', $video->timecreated); $video->dateday = date('m-d-Y', $video->timecreated); } return $videos; } /* * This function check if remote file is exist. * Get $url to the file * Return true if the file exist and false if not. */ function check_file_exist($url) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_NOBODY, true); curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); return $code == 200 ? true : false; } <file_sep><?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * List all videos. * * @package local_video_directory * @copyright 2017 <NAME> <<EMAIL>> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ require_once( __DIR__ . '/../../config.php'); require_login(); defined('MOODLE_INTERNAL') || die(); require_once('locallib.php'); if (!CLI_SCRIPT) { require_login(); // Check if user have permissionss. // $context = context_system::instance(); // if (!has_capability('local/video_directory:video', $context) && !is_video_admin($USER)) { // die("Access Denied. You must get rights... Please see your site admin."); // } } // $tags = optional_param('tag', 0, PARAM_RAW); // $tc = optional_param('tc', 0, PARAM_INT); // $action = optional_param('action', 0, PARAM_RAW); // $group = optional_param('group', 0, PARAM_RAW); // $category = optional_param('category', 0, PARAM_RAW); // if (!property_exists($SESSION, 'groups')) { // $SESSION->groups = []; // } // if (!property_exists($SESSION, 'categories')) { // $SESSION->categories = []; // } // if ($action) { // if ($action == "addgroup") { // $SESSION->groups[$group] = ['name' => $group]; // } else if ($action == "removegroup") { // unset($SESSION->groups[$group]); // } else if ($action == "addcategory") { // $SESSION->categories[$category] = ['id' => $category]; // } else if ($action == "removecategory") { // unset($SESSION->categories[$category]); // } // } // if ($tc == 1) { // redirect($CFG->wwwroot . "/local/video_directory/tag.php?action=add&tag=".$tags); // } // if ($tags == '') { // $SESSION->video_tags = ' - '; // } $PAGE->set_context(context_system::instance()); $PAGE->set_heading(get_string('list', 'local_video_directory')); $PAGE->set_title(get_string('list', 'local_video_directory')); $PAGE->set_url('/local/video_directory/list.php'); $PAGE->navbar->add(get_string('pluginname', 'local_video_directory'), new moodle_url('/local/video_directory/')); $PAGE->navbar->add(get_string('list', 'local_video_directory')); $PAGE->set_pagelayout('standard'); $PAGE->requires->js('/local/video_directory/datatables/jquery.dataTables.js'); $PAGE->requires->css('/local/video_directory/datatables/jquery.dataTables.min.css'); require($CFG->libdir . '/jquery/plugins.php'); // Just populates the variable "$plugins" in the next line. $PAGE->requires->css('/lib/jquery/' . $plugins['ui-css']['files'][0]); // Include font awesome in case of moodle 32 and older. if ($CFG->branch < 33) { $PAGE->requires->css('/local/video_directory/font_awesome/css/all.min.css'); } $PAGE->requires->css('/local/video_directory/style.css'); $PAGE->requires->js('/blocks/video/video_list.js'); // Table headers. $PAGE->requires->strings_for_js(array('id', 'private', 'streaming_url', 'owner', 'orig_filename', 'convert_status'), 'local_video_directory'); echo $OUTPUT->header(); $settings = get_settings(); // Menu. // require('menu.php'); // Check is streaming is set well. if (!check_streaming_server_url()) { $dirs = get_directories(); $message = get_string('nostreaming', 'local_video_directory'); $message .= "<br><tt><b>ln -s " . $dirs['converted'] . ' ' . $CFG->dirroot . "/streaming</b></tt>"; \core\notification::warning($message); } // Find all movies tags. $alltags = $DB->get_records_sql('SELECT DISTINCT name FROM {tag_instance} ti LEFT JOIN {tag} t ON ti.tagid=t.id WHERE itemtype = \'local_video_directory\' ORDER BY name'); $alltagsurl = array(); foreach ($alltags as $key => $value) { array_push($alltagsurl, array('name' => $key, 'url' => urlencode($key))); } $selectedtags = array(); if (!isset($SESSION->video_tags)) { $SESSION->video_tags = array(); } if (is_array($SESSION->video_tags)) { if ((count($SESSION->video_tags) > 0)) { foreach ($SESSION->video_tags as $key => $value) { array_push($selectedtags, array('name' => $value, 'url' => urlencode($value))); } } } $fields = $settings->fieldorder; $f = 'actions, thumb, id, name, usergroup, orig_filename, length, timecreated'; $fields = $f; echo "<pre>"; var_dump($fields); $fields = explode(",", $fields); $fieldsv = []; $liststrings = []; $order = 2; foreach ($fields as $key => $value) { if (trim($value) == 'id') { $order = $key; } if (!( ($settings->group == 'none' && trim($value) == 'usergroup') || ($settings->embedcolumn == 0 && trim($value) == 'streaming_url') )) { $fieldsv[$key]['name'] = trim($value); array_push($liststrings, get_string(trim($value), 'local_video_directory')); } } // var_dump(array_values($fieldsv));die; // var_dump($liststrings);die; // $groups = local_video_get_groups($settings); // $g = []; // if ($groups) { // foreach ($groups as $key => $value) { // $g[$key]['name'] = $value; // } // } // $cats = $DB->get_records('local_video_directory_cats', [], 'id', 'id, cat_name'); // foreach ($cats as $cat) { // $allcats[$cat->id] = $cat->cat_name; // } // $selectedcats = array(); // foreach ($SESSION->categories as $cat) { // $selectedcats[$cat['id']] = ['id' => $cat['id'], 'name' => $allcats[$cat['id']]]; // } // 'alltags' => $alltagsurl, // 'existvideotags' => is_array($SESSION->video_tags), // 'videotags' => $selectedtags, // showgroupcloud' => $settings->groupcloud, // 'groups' => array_values($g), // 'existselectedgroups' => count($SESSION->groups), // 'selectedgroups' => array_values($SESSION->groups), // 'showcatscloud' => $settings->catscloud, // 'categories' => array_values($cats), // 'existselectedcats' => count($SESSION->categories), // 'selectedcats' => array_values($selectedcats), // 'tags' => $tags, echo $OUTPUT->render_from_template('block_video/list', ['wwwroot' => $CFG->wwwroot, 'liststrings' => $liststrings, 'lang' => current_language(), 'fields' => array_values($fieldsv), 'order' => $order ]); // echo $OUTPUT->render_from_template('local_video_directory/player', []); echo $OUTPUT->footer();<file_sep><?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. // original plugin by 2013 <NAME> <<EMAIL>> /** * Defines the version of videostream. * * This code fragment is called by moodle_needs_upgrading() and * /admin/index.php. * * @package block_video * @copyright 2020 Chaya@openapp * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die; if ($ADMIN->fulltree) { $settings->add(new admin_setting_heading( 'block_video/generalsetting', get_string('generalsetting', 'block_video'), '') ); $choices = ['list' => get_string('list', 'block_video'), 'table' => get_string('table', 'block_video')]; $settings->add(new admin_setting_configselect( 'block_video/defaultshowingvideos', get_string('defaultshowingvideos', 'block_video'), get_string('defaultshowingvideos_help', 'block_video'), '', $choices) ); $settings->add(new admin_setting_configcheckbox( 'block_video/addpublicbookmarks', get_string('addpublicbookmarks', 'block_video'), get_string('addpublicbookmarks_help', 'block_video'), 1) ); $settings->add(new admin_setting_configcheckbox( 'block_video/hiddenzoomvideos', get_string('hiddenzoomvideos', 'block_video'), get_string('hiddenzoomvideos_help', 'block_video'), 0) ); } <file_sep><?php define('AJAX_SCRIPT', true); require __DIR__ . '/../../../config.php'; if (!isloggedin() || isguestuser()) { print_error('No permissions'); } if ($id = optional_param('delete', null, PARAM_INT)) { // $DB->delete_records('videostreambookmarks', ['id' => $id, 'userid' => $USER->id]);. $DB->delete_records('block_video_bookmarks', ['id' => $id]); die('1'); } $videotype = required_param('videotype', PARAM_INT); $video_id = required_param('id', PARAM_RAW); $videoposition = required_param('bookmarkposition', PARAM_FLOAT); $text = required_param('bookmarkname', PARAM_RAW); // $bookmarkflag = required_param('bookmarkflag', PARAM_RAW); $userid = $USER->id; $timemodified = time(); $permission = optional_param('teacherbookmark', null, PARAM_INT) == 1 ? 'public' : 'private'; $object = compact('userid', 'video_id', 'videoposition', 'text', 'permission', 'timemodified'); $id = $DB->insert_record('block_video_bookmarks', $object); echo json_encode($DB->get_record('block_video_bookmarks', ['id' => $id])); <file_sep><?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * @package local_video_directory * @copyright 2017 <NAME> <<EMAIL>> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); function xmldb_block_video_upgrade($oldversion) { global $DB; $dbman = $DB->get_manager(); if ($oldversion < 2020090700) { // Define table local_video_multi to be created. $table = new xmldb_table('block_video_course'); // Adding fields to table local_video_directory_multi. $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('videoid', XMLDB_TYPE_INTEGER, '20', null, XMLDB_NOTNULL, null, null); $table->add_field('courseid', XMLDB_TYPE_INTEGER, '20', null, XMLDB_NOTNULL, null, null); $table->add_field('usermodifiedid', XMLDB_TYPE_INTEGER, '20', null, XMLDB_NOTNULL, null, null); $table->add_field('timemodified', XMLDB_TYPE_INTEGER, '20', null, null, null, null); // Adding keys to table block_video_course. $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); // Conditionally launch create table for local_video_directory_multi. if (!$dbman->table_exists($table)) { $dbman->create_table($table); } upgrade_plugin_savepoint(true, 2020090700, 'block', 'video'); } return 1; } <file_sep><?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Defines the version of videostream. * * This code fragment is called by moodle_needs_upgrading() and * /admin/index.php. * * @package block_video * @copyright 2020 <EMAIL> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ // defined('MOODLE_INTERNAL') || die; require_once(dirname(__FILE__) . '/../../config.php'); require_once(dirname(__FILE__) . '/locallib.php'); // global $PAGE; $id = required_param('id', PARAM_RAW); $courseid = optional_param('courseid', 1 , PARAM_INT); // Block page for non auth users require_login($courseid); $course = $DB->get_record('course', ['id' => $courseid]); $videoname = $DB->get_field('local_video_directory', 'orig_filename', ['id' => $id]); $url = new moodle_url('/blocks/videodirectory/view.php', array('id' => $id, 'courseid' => $courseid)); $PAGE->set_url($url); $PAGE->set_heading($course->fullname); $PAGE->set_title($course->shortname . ': ' . $videoname); $PAGE->set_context(context_system::instance()); $PAGE->set_pagelayout('standard'); $PAGE->navbar->add($videoname); $PAGE->requires->css('/blocks/videodirectory/videojs-seek-buttons/videojs-seek-buttons.css'); $PAGE->requires->css(new moodle_url($CFG->wwwroot . '/blocks/video/videostyle.css')); $contextcourse = context_course::instance($courseid); $PAGE->set_context($contextcourse); $blockid = $DB->get_field('block_instances', 'id', ['parentcontextid' => $contextcourse->id, 'blockname' => 'video']); $PAGE->set_course($course); $PAGE->set_pagelayout('course'); require_login(); if (!is_enrolled($contextcourse, $USER->id) && !is_siteadmin($USER) && !has_capability('block/video:viewvideo', $contextblock)) { redirect($CFG->wwwroot . '/course/view.php?id=' . $courseid); } $_SESSION['videoid'] = $id; $context = context_course::instance($courseid); //print_r($context->id);die; $event = \block_video\event\video_view::create(array( 'objectid' => $context->id, 'contextid' => $context->id, )); $event->trigger(); $output = ''; $output .= block_video($id, $courseid); echo $OUTPUT->header(); echo $OUTPUT->heading($videoname); echo $output; echo $OUTPUT->footer(); <file_sep><?php // This file is part of Moodle - http://moodle.org/ /// // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * * This code fragment is called by moodle_needs_upgrading() and * /admin/index.php. * * @package block_video * @copyright 2020 <EMAIL> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ require_once( __DIR__ . '/../../../config.php'); require_login();//print_r('aaa');die; defined('MOODLE_INTERNAL') || die(); require_once(__DIR__ .'/../locallib.php'); require_once(__DIR__ . '/../../../local/video_directory/locallib.php'); global $DB; // $videos = $DB->get_records_sql('SELECT DISTINCT v.*, ' . $DB->sql_concat_join("' '", array("firstname", "lastname")) . // ' AS name // FROM {local_video_directory} v // LEFT JOIN {user} u on v.owner_id = u.id // WHERE (owner_id =' . $USER->id . // ' OR (private IS NULL OR private = 0))'); $videos = get_videos_from_video_directory_by_owner(); $config = get_config('local_video_directory'); print_r($videos);die; function my_block_video_get_thumbnail_url($thumb, $videoid, $clean=0) { global $CFG, $DB; $config = get_config('local_video_directory'); $dirs = get_directories(); $thumb = str_replace(".png", "-mini.png", $thumb); $thumbdata = explode('-', $thumb); $thumbid = $thumbdata[0]; $thumbseconds = isset($thumbdata[1]) ? "&second=$thumbdata[1]" : ''; $video = $DB->get_record('local_video_directory', ['id' => $videoid]); // echo $video->filename; // echo $config->streaming . "/" . local_video_directory_get_filename($videoid) . ".mp4"; if ((file_exists( $dirs['converted'] . $videoid . ".mp4")) || (file_exists( $dirs['converted'] . $video->filename . ".mp4"))) { $alt = 'title="' . get_string('play', 'local_video_directory') . '" alt="' . get_string('play', 'local_video_directory') . '"'; if (get_streaming_server_url()) { if ($video->filename != $videoid . '.mp4') { $playbutton = ' data-video-url="' . htmlspecialchars(get_streaming_server_url()) . "/" . $video->filename . '.mp4" data-id="' . $videoid . '"'; } else { $playbutton = ' data-video-url="' . htmlspecialchars(get_streaming_server_url()) . "/" . $videoid . '.mp4" data-id="' . $videoid . '"'; } } else { $playbutton = ' data-video-url="play.php?video_id=' . $videoid . '" data-id="' . $videoid . '"'; } } else { $playbutton = ''; } $thumb = "<div class='video-thumbnail' " . $playbutton . ">" . ($thumb ? "<img src='$CFG->wwwroot/local/video_directory/thumb.php?id=$thumbid$thumbseconds&mini=1 ' class='thumb' " . $playbutton ." >" : get_string('noimage', 'local_video_directory')) . "</div>"; if ($clean) { $thumb = "$CFG->wwwroot/local/video_directory/thumb.php?id=$thumbid$thumbseconds"; } return $thumb; } foreach ($videos as $video) { $video->selected = '<input type= checkbox>'; // echo $video->filename;die; $video->thumb = my_block_video_get_thumbnail_url($video->thumb, $video->id); // print_r($video->thumb); // $filename = local_video_directory_get_filename($video->id) // $video->streaming_url = '<a target="_blank" href="' . get_streaming_server_url() . '/' . $filename . '.mp4">' // . get_streaming_server_url() . '/' . $filename . '.mp4</a><br>'; } // $videodata = json_decode($data); // $total = count(local_video_directory_get_videos(0, null, null, $search)); // $videos = local_video_directory_get_videos($order, $videodata->start, $videodata->length, $search); // echo "<pre>"; print_r(json_encode( array_values($videos), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)); // return json_encode( array_values($videos), // JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); <file_sep>// require.config({catchError:true}); // require(['jquery', 'jqueryui', 'datatables', 'core/ajax'], function($, jqueryui, datatables, ajax) { // $(document).ready(function() { // var table = $("#video_table").DataTable({ // $.ajax({url: M.cfg.wwwroot + '/blocks/video/get_video_ajax.php', // success: function(data){ // return data; // } // ,error: function(error){console.log(error);} // }); // }, // "order": [[{{order}}, "desc"]], // "columns": [ // {{#fields}} // {"data": "{{name}}"}, // {{/fields}} // ], // initComplete: function(){ // $('.showembed').click(function(e) { // e.preventDefault(); // // Find index of line by video id. // for (index = 0; index < table.columns().data()[2].length; ++index) { // if (table.columns().data()[2][index] == $(this).data('id')) { // var myindex = index; // } // } // var qrimg = '<img src="' + M.cfg.wwwroot + '/local/video_directory/qr.php?id=' + $(this).data('id') + '">'; // $(".ui-dialog-content").dialog("close"); // $('<div id="messagemodal">' + table.columns().data()[8][myindex] + qrimg + '</div>').dialog({width: 650, height: 400}); // }) // } // }); // var clickEmbed = function(){ // $('.showembed').click(function(e) { // e.preventDefault(); // // Find index of line by video id. // for (index = 0; index < table.columns().data()[2].length; ++index) { // if (table.columns().data()[2][index] == $(this).data('id')) { // var myindex = index; // } // } // var qrimg = '<img src="' + M.cfg.wwwroot + '/local/video_directory/qr.php?id=' + $(this).data('id') + '">'; // $(".ui-dialog-content").dialog("close"); // $('<div id="messagemodal">' + table.columns().data()[8][myindex] + qrimg + '</div>').dialog({width: 650, height: 400}); // }) // }; // var myReload = function(){ // table.ajax.reload(clickEmbed); // } // $('#datatable_ajax_reload').click(function() { // table.ajax.reload(clickEmbed); // }); // $('#datatable_ajax_clear_tags').click(function() { // window.location = 'list.php'; // }); // $('#video_table').on('change', '.ajax_edit', function () { // var data = this.id.split('_'); // var field = this.type == 'checkbox' ? 'private' : 'orig_filename'; // var id = data.pop(); // var status = this.type == 'checkbox' ? this.checked : null; // var value = this.type == 'checkbox' ? null : this.value; // var promises = ajax.call([ // { methodname: 'local_video_directory_edit', args: { videoid: id, field: field, value: value, status: status } } // ]); // }); // $('.play_video').click(function () { // $("#video_player").show(); // }); // // reload table every 60 seconds // setTimeout(myReload, 60000); // }); // }<file_sep><?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. // original plugin by 2013 <NAME> <<EMAIL>> /** * * This code fragment is called by moodle_needs_upgrading() and * /admin/index.php. * * @package block_video * @copyright 2020 Chaya@openapp * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); $string['pluginname'] = 'Video'; $string['video'] = 'Video'; $string['list'] = 'List'; $string['table'] = 'Table'; $string['defaultshowingvideos'] = 'The default showing the videos on the block'; $string['defaultshowingvideos_help'] = 'The default showing the videos on the block'; $string['addpublicbookmarks'] = 'Add public bookmarks'; $string['addpublicbookmarks_help'] = 'Add public bookmarks'; $string['livebroadcasttitle'] = 'Live broadcast'; $string['videostitle'] = 'Zoom Videos'; $string['zoomvideostitle'] = 'Videos from zoom'; $string['addsmartbookmark'] = 'Add smart bookmark'; $string['bookmarkname'] = 'Bookmark name'; $string['addteacherbookmark'] = 'Add teacher bookmark'; $string['deletebookmark'] = 'Delete bookmark'; $string['subject'] = 'Subject'; $string['starttime'] = 'Start time'; $string['length'] = 'Length'; $string['daterecord'] = 'Date recording'; $string['generalsetting'] = 'General settings'; $string['search'] = 'Search'; $string['selected'] = 'select'; $string['nosearchresult'] = 'No search results'; $string['id'] = 'ID'; $string['private'] = 'private'; $string['streaming_url'] = 'streaming_url'; $string['owner'] = 'owner'; $string['orig_filename'] = 'orig filename'; $string['convert_status'] = 'convert status'; $string['thumb'] = 'Image'; $string['name'] = 'Name'; $string['timecreated'] = 'Time created'; $string['choosevideostitle'] = 'Choose videos'; $string['save'] = 'Save changes'; $string['video:addlocalvideos'] = 'Add video from video directory'; $string['video:addpublicbookmarks'] = 'Add public bookmark on video'; $string['video:editnamevideo'] = 'Edit name of the video from zoom'; $string['video:viewvideo'] = 'View video'; $string['public'] = 'Public'; $string['searchtexttitle'] = 'Text'; $string['sortby'] = 'Sort by:'; $string['searchstartdatetitle'] = 'Start date'; $string['searchenddatetitle'] = 'End date'; $string['viewvideo'] = 'view videos'; $string['submitbookmark'] = 'Submit bookmark'; $string['student'] = 'Student'; $string['hiddenfromstudents'] = 'hidden from students'; $string['hiddenzoomvideos'] = 'hidden zoom videos from students'; $string['hiddenzoomvideos_help'] = 'by defult hidden zoom videos from students'; <file_sep><?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. // original plugin by 2013 <NAME> <<EMAIL>> /** * Defines the version of videostream. * * This code fragment is called by moodle_needs_upgrading() and * /admin/index.php. * * @package block_video * @copyright 2020 Chaya<EMAIL> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ require_once( __DIR__ . '/../../config.php'); defined('MOODLE_INTERNAL') || die; global $PAGE, $OUTPUT, $DB; require_login(); require_once('locallib.php'); $courseid = required_param('courseid', PARAM_RAW); $contextcourse = context_course::instance($courseid); $blockid = $DB->get_field('block_instances', 'id', ['parentcontextid' => $contextcourse->id, 'blockname' => 'video']); //$contextblock = context_block::instance($blockid); $PAGE->set_context($contextcourse); $PAGE->set_heading(get_string('list', 'block_video')); $PAGE->set_url('/blocks/video/choosevideos.php'); $PAGE->set_title(get_string('list', 'block_video')); $PAGE->requires->css('/blocks/video/jquery-ui.css'); $PAGE->set_pagelayout('incourse'); $course = $DB->get_record('course', ['id' => $courseid]); $PAGE->set_course($course); //if (! has_capability('block/video:addlocalvideos', $contextblock)) { // redirect($CFG->wwwroot . '/course/view.php?id=' . $courseid); //} $PAGE->requires->js(new moodle_url($CFG->wwwroot . '/blocks/video/javascript/choosevideos.js')); echo $OUTPUT->header(); $fields = ['selected', 'thumb', 'id', 'name', 'length', 'owner', 'public', 'timecreated']; $liststrings = []; foreach ($fields as $field) { $liststrings[] = get_string($field, 'block_video'); } $videos = array_values(get_videos_from_video_directory_by_owner($course)); $datafortemplate = [ 'wwwroot' => $CFG->wwwroot, 'liststrings' => $liststrings, 'videos' => $videos ]; echo $OUTPUT->render_from_template('block_video/choosevideos', $datafortemplate); echo $OUTPUT->footer();
485ea1528fcda5bdfbaebdb9b5226b58fab4c43e
[ "JavaScript", "PHP" ]
12
PHP
ToviKurztag/moodle-block_video
f2806c75ac9ba43e0576243ec38ef6106f95b51e
b59941af9999ed63fa709e97c0f604756f5845c5
refs/heads/main
<repo_name>AthamAbdullox/Recipe-Search-App<file_sep>/src/contexts/axios.js import axios from "axios"; const options = { method: 'GET', url: 'https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/100/information', headers: { 'x-rapidapi-key': '79d55e6135msh32b4af25cbeedd5p14a581jsn1c7792f0f9df', 'x-rapidapi-host': 'spoonacular-recipe-food-nutrition-v1.p.rapidapi.com' } }; const requests = axios.request(options) export default requests;<file_sep>/src/components/Header.js import React from "react"; import { Navbar, Nav, NavDropdown } from "react-bootstrap"; import { useAuth } from "../contexts/AuthContext" import { Link, useHistory } from "react-router-dom" export default function Header() { const [error, setError] = React.useState("") const history = useHistory() const { currentUser, logout } = useAuth() async function handleLogout() { setError("") try { await logout() history.push("/login") } catch { setError("Failed to log out") } } const emailValue = currentUser?( <NavDropdown title={currentUser.email} id="basic-nav-dropdown"> <NavDropdown.Item> <Link to="/update-profile"> Update Profile </Link> </NavDropdown.Item> <NavDropdown.Divider /> <NavDropdown.Item variant="link" onClick={handleLogout} style={{color:"blue"}}> Log out </NavDropdown.Item> </NavDropdown> ): (<div> <Link to="/Login" className="btn btn-primary" style={{marginRight:"20px"}}> Login </Link> <Link to="/Signup" className="btn btn-primary"> Signup </Link> </div> ) return ( <div> <Navbar bg="light" expand="lg"> <Navbar.Brand href="/"> NiceRecipe </Navbar.Brand> <Navbar.Toggle aria-controls="basic-navbar-nav" /> <Navbar.Collapse id="basic-navbar-nav" className="justify-content-end"> <Nav className="mr-auto"> <Nav.Link active href="/"> Home {error} </Nav.Link> <Nav.Link href="https://rapidapi.com/spoonacular/api/recipe-food-nutrition/details">Api Documentation</Nav.Link> <Nav.Link href="https://spoonacular.com/food-api">Food Api Website</Nav.Link> {emailValue} </Nav> </Navbar.Collapse> </Navbar> </div> ); } <file_sep>/src/components/Dashboard.js import React ,{ useState }from "react" import { Form, Button } from "react-bootstrap" import axios from "axios"; import './Results.css' import CardsBar from './CardsBar'; export default function Dashboard() { const [ recipes, setRecipes ] = useState([]) // eslint-disable-next-line react-hooks/exhaustive-deps const options = { method: 'GET', url: 'https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/search', params:{"number":20}, headers: { 'x-rapidapi-key': '79d55e6135msh32b4af25cbeedd5p14a581jsn1c7792f0f9df', 'x-rapidapi-host': 'spoonacular-recipe-food-nutrition-v1.p.rapidapi.com' } }; function searchButton() { if(document.getElementById("formBasicSearch").value){ options.params={...options.params, "query":document.getElementById("formBasicSearch").value, "diet":document.getElementById("formBasicCheckbox").checked?"vegetarian":"" } document.getElementById("formBasicSearch").value="" const requests = axios.request(options) async function fetchData() { requests.then(function (response) { setRecipes(response.data.results) }).catch(function (error) { console.error(error); }); } fetchData() } } return ( <> <div> <Form className="form"> <Form.Group className="mb-3" controlId="formBasicSearch"> <Form.Label> Search </Form.Label> <Form.Control type="text" placeholder="Search" onKeyPress={event => { if (event.key === 'Enter') { searchButton() }}}/> <Form.Text className="text-muted"> Search recipe which you need </Form.Text> </Form.Group> <Form.Group className="mb-3" controlId="formBasicCheckbox"> <Form.Check type="checkbox" label="vegetarian" /> </Form.Group> <Button variant="primary" onClick={searchButton}> search </Button> </Form> <div className="scene"> {recipes.map((recipeData)=> ( <CardsBar recipeData={recipeData}/> ))} </div> </div> </> ) }<file_sep>/src/components/CardsBar.js import React, { useState, useEffect } from 'react' import { Link } from "react-router-dom" import { Card, OverlayTrigger, Tooltip } from "react-bootstrap" import axios from "axios"; export default function CardsBar(props) { const [recipeInform,SetRecipeInform] = useState([]) const [options] = useState({ method: 'GET', url: `https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/${props.recipeData.id}/information`, headers: { 'x-rapidapi-key': '79d55e6135msh32b4af25cbeedd5p14a581jsn1c7792f0f9df', 'x-rapidapi-host': 'spoonacular-recipe-food-nutrition-v1.p.rapidapi.com' } }); useEffect(()=>{ const requests = axios.request(options) async function fetchData() { requests.then(function (response) { SetRecipeInform(response.data) }).catch(function (error) { console.error(error); }); } fetchData() },[options]) const renderTooltip = () => { return( <Tooltip id="button-tooltip" > <h5>Ingredients</h5> <ul className="list-group">{recipeInform.extendedIngredients && recipeInform.extendedIngredients.map((ingredients)=>( <li key={ingredients.name} className="list-group-item">{ingredients.name}</li> ))}</ul> </Tooltip> ); } return ( <Card style={{ width: '18rem' }} className="Card"> <Card.Img variant="top" src={`https://spoonacular.com/recipeImages/${props.recipeData.image}`} /> <Card.Body className="CardBody"> <OverlayTrigger placement="right" delay={{ show: 250, hide: 400 }} overlay={renderTooltip()} > <Card.Title><Link to={{pathname:"recipe-Inform", search:`${props.recipeData.id}` }} > {props.recipeData.title} </Link> </Card.Title> </OverlayTrigger> </Card.Body> </Card> ) } <file_sep>/src/components/RecipeInform.js import React, { useState, useEffect } from 'react' import axios from "axios"; import './RecipeInform.css' export default function RecipeInform(props) { const [recipeInform,setRecipeInform] = useState([]) const [ options ] = useState({ method: 'GET', url: `https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/${props.location.search.replace(/\D/g,"")}/information`, headers: { 'x-rapidapi-key': '79d55e6135msh32b4af25cbeedd5p14a581jsn1c7792f0f9df', 'x-rapidapi-host': 'spoonacular-recipe-food-nutrition-v1.p.rapidapi.com' } }) useEffect(()=>{ const requests = axios.request(options) async function fetchData() { requests.then(function (response) { console.log(response.data) setRecipeInform(response.data) }).catch(function (error) { console.error(error); }); } fetchData() }, [options]) return ( <div> <section className="title"> <h1 className="title__text">{recipeInform.title}</h1> </section> <section className="row__column"> <div className="list__block"> <ul className="list-group"> {recipeInform.extendedIngredients && recipeInform.extendedIngredients.map(ingredient => ( <li className="list-group-item"> {ingredient.originalString} </li> ))} </ul> </div> <div className="image__block"> <img src={recipeInform.image} alt="recipe" /> </div> </section> <section className="numbered__block"> {recipeInform.analyzedInstructions && recipeInform.analyzedInstructions[0].steps.map(step=> {if(step.number % 2 === 0) return ( <div className="block__separator"> <p>{step.step}</p> <div className={`number__block number-${step.number}`} >{step.number}</div> </div> ) else return ( <div className="block__separator"> <div className={`number__block number-${step.number}`} >{step.number}</div> <p>{step.step}</p> </div> ) } ) } </section> <section className="info"> <div className="info__block"> <h2>Agregate Likes</h2> <p>❤️{recipeInform.aggregateLikes}</p> </div> <div className="info__block"> <h2>Health Score</h2> <p>{recipeInform.healthScore}</p> </div> <div className="info__block"> <h2>Cooking Minutes</h2> <p>{recipeInform.cookingMinutes && recipeInform.readyInMinutes}</p> </div> </section> </div> ) }
9c0261ab0fc2c30ae24954a99212e130fc46c47b
[ "JavaScript" ]
5
JavaScript
AthamAbdullox/Recipe-Search-App
fd6d6e51a0a469b8225eb04c58f87cab9c67d542
6e53922d6609dbfc938b122334dffb08e9d0fc67
refs/heads/master
<file_sep>Django==1.11 django-environ==0.4.5 django-rosetta==0.9.0 microsofttranslator==0.8 polib==1.1.0 <file_sep>.. _api-utils: .. currentmodule:: guardian.utils Utilities ========= .. automodule:: guardian.utils get_anonymous_user ------------------ .. autofunction:: get_anonymous_user get_identity ------------ .. autofunction:: get_identity clean_orphan_obj_perms ---------------------- .. autofunction:: clean_orphan_obj_perms <file_sep>from guardian.compat import url from posts import views urlpatterns = [ url(r'^$', views.post_list, name='posts_post_list'), url(r'^(?P<slug>[-\w]+)/$', views.post_detail, name='posts_post_detail'), ] <file_sep>.. _api-template-tags: Template tags ============= .. automodule:: guardian.templatetags.guardian_tags get_obj_perms ------------- .. autofunction:: guardian.templatetags.guardian_tags.get_obj_perms <file_sep>.. _supported-versions: Supported versions ================== ``django-guardian`` supports Python 2.7+/3.3+ and Django 1.11+. Rules ----- * We would support Python 2.7. We also support Python 3.4+. * Support for Python 3.4 may get dropped in the future. * We support Django 1.11+. This is due to many simplifications in code we could do. <file_sep>.. _api-core: Core ==== .. automodule:: guardian.core ObjectPermissionChecker ----------------------- .. autoclass:: guardian.core.ObjectPermissionChecker :members: <file_sep>#!/bin/bash set -ev pip install -U pip # Array of packages PACKAGES=('mock==1.0.1' 'pytest' 'pytest-django' 'pytest-cov' 'django-environ' 'setuptools_scm') # Install django master or version if [[ "$DJANGO_VERSION" == 'master' ]]; then PACKAGES+=('https://github.com/django/django/archive/master.tar.gz'); else PACKAGES+=("Django==$DJANGO_VERSION"); fi; # Install database drivers if [[ $DATABASE_URL = postgres* ]]; then PACKAGES+=('psycopg2==2.7.5'); fi; if [[ $DATABASE_URL = mysql* ]]; then PACKAGES+=('mysqlclient==1.3.13'); fi; echo "Install " ${PACKAGES[*]}; pip install --upgrade --upgrade-strategy=only-if-needed ${PACKAGES[*]}; pip check <file_sep>from guardian.compat import include, url, handler404, handler500 from django.conf import settings from django.contrib import admin from django.contrib.auth.views import LogoutView __all__ = ['handler404', 'handler500'] admin.autodiscover() urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^logout/$', LogoutView.as_view(next_page='/'), name='logout'), url(r'^article/', include('articles.urls', namespace='articles')), url(r'^', include('posts.urls')), ] if 'grappelli' in settings.INSTALLED_APPS: urlpatterns += [url(r'^grappelli/', include('grappelli.urls')), ] if 'rosetta' in settings.INSTALLED_APPS: urlpatterns += [url(r'^rosetta/', include('rosetta.urls')), ] <file_sep>.. _caveats: Caveats ======= Orphaned object permissions --------------------------- Note the following does not apply if using direct foreign keys, as documented in :ref:`performance-direct-fk`. Permissions, including so called *per object permissions*, are sometimes tricky to manage. One case is how we can manage permissions that are no longer used. Normally, there should be no problems, however with some particular setup it is possible to reuse primary keys of database models which were used in the past once. We will not answer how bad such situation can be - instead we will try to cover how we can deal with this. Let's imagine our table has primary key to the filesystem path. We have a record with pk equal to ``/home/www/joe.config``. User *jane* has read access to joe's configuration and we store that information in database by creating guardian's object permissions. Now, *joe* user removes account from our site and another user creates account with *joe* as username. The problem is that if we haven't removed object permissions explicitly in the process of first *joe* account removal, *jane* still has read permissions for *joe's* configuration file - but this is another user. There is no easy way to deal with orphaned permissions as they are not foreign keyed with objects directly. Even if they would, there are some database engines - or *ON DELETE* rules - which restricts removal of related objects. .. important:: It is **extremely** important to remove :model:`UserObjectPermission` and :model:`GroupObjectPermission` as we delete objects for which permissions are defined. Guardian comes with utility function which tries to help to remove orphaned object permissions. Remember - those are only helpers. Applications should remove those object permissions explicitly by itself. Taking our previous example, our application should remove user object for *joe*, however, permisions for *joe* user assigned to *jane* would **NOT** be removed. In this case, it would be very easy to remove user/group object permissions if we connect proper action with proper signal. This could be achieved by following snippet:: from django.contrib.contenttypes.models import ContentType from django.db.models import Q from django.db.models.signals import pre_delete from guardian.models import User from guardian.models import UserObjectPermission from guardian.models import GroupObjectPermission def remove_obj_perms_connected_with_user(sender, instance, **kwargs): filters = Q(content_type=ContentType.objects.get_for_model(instance), object_pk=instance.pk) UserObjectPermission.objects.filter(filters).delete() GroupObjectPermission.objects.filter(filters).delete() pre_delete.connect(remove_obj_perms_connected_with_user, sender=User) This signal handler would remove all object permissions connected with user just before user is actually removed. If we forgot to add such handlers, we may still remove orphaned object permissions by using :command:`clean_orphan_obj_perms` command. If our application uses celery_, it is also very easy to remove orphaned permissions periodically with :func:`guardian.utils.clean_orphan_obj_perms` function. We would still **strongly** advise to remove orphaned object permissions explicitly (i.e. at view that confirms object removal or using signals as described above). .. seealso:: - :func:`guardian.utils.clean_orphan_obj_perms` - :command:`clean_orphan_obj_perms` .. _celery: http://www.celeryproject.org/ Using multiple databases ------------------------ This is not supported at present time due to a Django bug. See 288_ and 16281_. .. _288: https://github.com/django-guardian/django-guardian/issues/288 .. _16281: https://code.djangoproject.com/ticket/16281 <file_sep>#!/bin/sh DIR="." CMD="make html" NOTIFY='growlnotify guardian Documentation -m Recreated' # Run command echo " => Documentation would be available at file://$PWD/build/html/index.html" $CMD $NOTIFY # Run command on .rst file change. watchmedo shell-command --pattern "*.rst" --recursive -w -c "clear && $CMD && $NOTIFY" $DIR <file_sep>from django.contrib.auth import get_user_model from django.test import TestCase from django.test.client import RequestFactory from guardian.shortcuts import assign_perm from articles.models import Article from articles.views import (ArticleCreateView, ArticleDeleteView, ArticleDetailView, ArticleListView, ArticleUpdateView) class ViewTestCase(TestCase): def setUp(self): self.article = Article.objects.create(title='foo-title', slug='foo-slug', content='bar-content') self.factory = RequestFactory() self.user = get_user_model().objects.create_user( 'joe', '<EMAIL>', 'doe') self.client.login(username='joe', password='doe') def test_list_permitted(self): request = self.factory.get('/') request.user = self.user assign_perm('articles.view_article', self.user, self.article) assign_perm('articles.delete_article', self.user, self.article) view = ArticleListView.as_view() response = view(request) response.render() self.assertContains(response, 'foo-title') def test_list_denied(self): request = self.factory.get('/') request.user = self.user view = ArticleListView.as_view() response = view(request) response.render() self.assertNotContains(response, 'foo-title') def test_create_permitted(self): request = self.factory.get('/~create') request.user = self.user assign_perm('articles.add_article', self.user) view = ArticleCreateView.as_view() response = view(request) self.assertEqual(response.status_code, 200) def test_create_denied(self): request = self.factory.get('/~create') request.user = self.user view = ArticleCreateView.as_view() response = view(request) self.assertEqual(response.status_code, 302) def test_detail_permitted(self): request = self.factory.get('/foo/') request.user = self.user assign_perm('articles.view_article', self.user, self.article) view = ArticleDetailView.as_view() response = view(request, slug='foo-slug') self.assertEqual(response.status_code, 200) def test_detail_denied(self): request = self.factory.get('/foo/') request.user = self.user view = ArticleDetailView.as_view() response = view(request, slug='foo-slug') self.assertEqual(response.status_code, 302) def test_update_permitted(self): request = self.factory.get('/') request.user = self.user assign_perm('articles.view_article', self.user, self.article) assign_perm('articles.change_article', self.user, self.article) view = ArticleUpdateView.as_view() response = view(request, slug='foo-slug') self.assertEqual(response.status_code, 200) def test_update_denied(self): request = self.factory.get('/') request.user = self.user view = ArticleUpdateView.as_view() response = view(request, slug='foo-slug') self.assertEqual(response.status_code, 302) def test_delete_permitted(self): request = self.factory.get('/foo-slug/~delete') request.user = self.user assign_perm('articles.view_article', self.user, self.article) assign_perm('articles.delete_article', self.user, self.article) view = ArticleDeleteView.as_view() response = view(request, slug='foo-slug') self.assertEqual(response.status_code, 200) def test_delete_denied(self): request = self.factory.get('/foo/~delete') request.user = self.user view = ArticleDeleteView.as_view() response = view(request, slug='foo-slug') self.assertEqual(response.status_code, 302) <file_sep>.. _api: API Reference ============= .. toctree:: :maxdepth: 2 guardian.admin guardian.backends guardian.core guardian.decorators guardian.forms guardian.management.commands guardian.managers guardian.mixins guardian.models guardian.shortcuts guardian.utils guardian.templatetags.guardian_tags <file_sep>import datetime from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): birth_date = models.DateField(null=True, blank=True) def get_custom_anon_user(User): return User( username='AnonymousUser', birth_date=datetime.date(1410, 7, 15), ) <file_sep>import guardian def version(request): return {'version': guardian.get_version()} <file_sep>.. _guide: User Guide ========== .. toctree:: :maxdepth: 2 example_project assign check remove admin-integration custom-user-model performance caveats <file_sep>[pytest] DJANGO_SETTINGS_MODULE=guardian.testapp.testsettings filterwarnings = once::DeprecationWarning once::PendingDeprecationWarning <file_sep>Django>=1.11 django-environ bumpversion mock <file_sep>#!/bin/bash echo "Running test suite with coverage report at the end" echo -e "( would require coverage python package to be installed )\n" OMIT="guardian/testsettings.py,guardian/compat.py" coverage run setup.py test coverage report --omit "$OMIT" -m guardian/*.py <file_sep>#!/bin/bash python ./setup.py --version py.test --cov=guardian # Test example_project on supported django versions if [ "${DJANGO_VERSION:0:3}" = "1.11" ] || \ [ "${DJANGO_VERSION:0:3}" = "2.0" ] || \ [ "${DJANGO_VERSION:0:3}" = "2.1" ] || \ [ "${DJANGO_VERSION:0:3}" = "2.2" ] || \ [ "$DJANGO_VERSION" = "master" ]; then pip install .; cd example_project; python -Wa manage.py test; fi; <file_sep>import os import sys import environ env = environ.Env() abspath = lambda *p: os.path.abspath(os.path.join(*p)) THIS_DIR = abspath(os.path.dirname(__file__)) ROOT_DIR = abspath(THIS_DIR, '..') # so the preferred guardian module is one within this repo and # not system-wide sys.path.insert(0, ROOT_DIR) SECRET_KEY = 'NO_NEED_SECRET' INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.contenttypes', 'django.contrib.admin', 'django.contrib.sites', 'guardian', 'benchmarks', ) DJALOG_LEVEL = 40 DATABASES = {'default': env.db(default="sqlite:///")} <file_sep>.. _api-management-commands: Management commands =================== .. command:: clean_orphan_obj_perms .. autoclass:: guardian.management.commands.clean_orphan_obj_perms.Command <file_sep>from django.db import models from guardian.models import UserObjectPermissionBase from guardian.models import GroupObjectPermissionBase class TestModel(models.Model): name = models.CharField(max_length=128) class DirectUser(UserObjectPermissionBase): content_object = models.ForeignKey('TestDirectModel', on_delete=models.CASCADE) class DirectGroup(GroupObjectPermissionBase): content_object = models.ForeignKey('TestDirectModel', on_delete=models.CASCADE) class TestDirectModel(models.Model): name = models.CharField(max_length=128) <file_sep>{% extends "base.html" %} {% block content %} <div class="row"> <div class="span12"> <div class="hero-unit"> <h1>Articles</h1> <a href="{% url "articles:create" %}" class="btn btn-primary">Add article</a> </div> </div> {% for object in object_list %} <div class="span3"> </div> <div class="span9"> <a href="{{object.get_absolute_url}}" name="{{ post.id }}"><h1>{{ object.title }}</h1></a> <h5>at {{ object.created_at }}</h5> <hr/> {{ object.content|safe }} </div> {% endfor %} </div> {% endblock %} <file_sep>.. _api-mixins: Mixins ====== .. versionadded:: 1.0.4 .. automodule:: guardian.mixins .. mixin:: LoginRequiredMixin LoginRequiredMixin ------------------ .. autoclass:: guardian.mixins.LoginRequiredMixin :members: .. mixin:: PermissionRequiredMixin PermissionRequiredMixin ----------------------- .. autoclass:: guardian.mixins.PermissionRequiredMixin :members: PermissionListMixin ----------------------- .. autoclass:: guardian.mixins.PermissionListMixin :members: <file_sep>.. _api-admin: Admin ===== .. automodule:: guardian.admin .. admin:: GuardedModelAdmin GuardedModelAdmin ----------------- .. autoclass:: guardian.admin.GuardedModelAdmin :members: GuardedModelAdminMixin ---------------------- .. autoclass:: guardian.admin.GuardedModelAdminMixin :members: <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf.urls import url from . import views app_name = 'articles' urlpatterns = [ url(r'^$', views.ArticleListView.as_view(), name="list"), url(r'^~create$', views.ArticleCreateView.as_view(), name="create"), url(r'^(?P<slug>[\w-]+)$', views.ArticleDetailView.as_view(), name="details"), url(r'^(?P<slug>[\w-]+)/~update$', views.ArticleUpdateView.as_view(), name="update"), url(r'^(?P<slug>[\w-]+)/~delete$', views.ArticleDeleteView.as_view(), name="delete"), ] <file_sep>.. _api-managers: Managers ======== .. automodule:: guardian.managers .. manager:: UserObjectPermissionManager UserObjectPermissionManager --------------------------- .. autoclass:: guardian.managers.UserObjectPermissionManager :members: .. manager:: GroupObjectPermissionManager GroupObjectPermissionManager ---------------------------- .. autoclass:: guardian.managers.GroupObjectPermissionManager :members: <file_sep>from django.contrib import admin from posts.models import Post from guardian.admin import GuardedModelAdmin class PostAdmin(GuardedModelAdmin): prepopulated_fields = {"slug": ("title",)} list_display = ('title', 'slug', 'created_at') search_fields = ('title', 'content') ordering = ('-created_at',) date_hierarchy = 'created_at' admin.site.register(Post, PostAdmin) <file_sep>.. _api-forms: Forms ===== .. automodule:: guardian.forms .. form:: UserObjectPermissionsForm UserObjectPermissionsForm ------------------------- .. autoclass:: guardian.forms.UserObjectPermissionsForm :members: :show-inheritance: .. form:: GroupObjectPermissionsForm GroupObjectPermissionsForm -------------------------- .. autoclass:: guardian.forms.GroupObjectPermissionsForm :members: :show-inheritance: .. form:: BaseObjectPermissionsForm BaseObjectPermissionsForm ------------------------- .. autoclass:: guardian.forms.BaseObjectPermissionsForm :members: <file_sep>.. _api-backends: Backends ======== .. automodule:: guardian.backends ObjectPermissionBackend ----------------------- .. autoclass:: guardian.backends.ObjectPermissionBackend :members: <file_sep>import _ast import os import sys from setuptools import Command #from pyflakes.scripts import pyflakes as flakes def check(filename): from pyflakes import reporter as mod_reporter from pyflakes.checker import Checker codeString = open(filename).read() reporter = mod_reporter._makeDefaultReporter() # First, compile into an AST and handle syntax errors. try: tree = compile(codeString, filename, "exec", _ast.PyCF_ONLY_AST) except SyntaxError: value = sys.exc_info()[1] msg = value.args[0] (lineno, offset, text) = value.lineno, value.offset, value.text # If there's an encoding problem with the file, the text is None. if text is None: # Avoid using msg, since for the only known case, it contains a # bogus message that claims the encoding the file declared was # unknown. reporter.unexpectedError(filename, 'problem decoding source') else: reporter.syntaxError(filename, msg, lineno, offset, text) return 1 except Exception: reporter.unexpectedError(filename, 'problem decoding source') return 1 else: # Okay, it's syntactically valid. Now check it. lines = codeString.splitlines() warnings = Checker(tree, filename) warnings.messages.sort(key=lambda m: m.lineno) real_messages = [] for m in warnings.messages: line = lines[m.lineno - 1] if 'pyflakes:ignore' in line.rsplit('#', 1)[-1]: # ignore lines with pyflakes:ignore pass else: real_messages.append(m) reporter.flake(m) return len(real_messages) class RunFlakesCommand(Command): """ Runs pyflakes against guardian codebase. """ description = "Check sources with pyflakes" user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): try: import pyflakes # pyflakes:ignore except ImportError: sys.stderr.write("No pyflakes installed!\n") sys.exit(-1) thisdir = os.path.dirname(__file__) guardiandir = os.path.join(thisdir, 'guardian') warns = 0 # Define top-level directories for topdir, dirnames, filenames in os.walk(guardiandir): paths = (os.path.join(topdir, f) for f in filenames if f .endswith('.py')) for path in paths: if path.endswith('tests/__init__.py'): # ignore that module (it should only gather test cases with # *) continue warns += check(path) if warns > 0: sys.stderr.write( "ERROR: Finished with total %d warnings.\n" % warns) sys.exit(1) else: print("No problems found in source codes.") <file_sep>.. _api-models: Models ====== .. automodule:: guardian.models .. model:: BaseObjectPermission BaseObjectPermission -------------------- .. autoclass:: guardian.models.BaseObjectPermission :members: .. model:: UserObjectPermission UserObjectPermission -------------------- .. autoclass:: guardian.models.UserObjectPermission :members: .. model:: GroupObjectPermission GroupObjectPermission --------------------- .. autoclass:: guardian.models.GroupObjectPermission :members: <file_sep>from django.contrib.auth import get_user_model from django.contrib.auth.models import Group from django.shortcuts import render, get_object_or_404 from django.views.generic import ListView from django.template import RequestContext from guardian.decorators import permission_required_or_403 from .models import Post User = get_user_model() class PostList(ListView): model = Post context_object_name = 'posts' post_list = PostList.as_view() @permission_required_or_403('posts.view_post', (Post, 'slug', 'slug')) def post_detail(request, slug, **kwargs): data = { 'post': get_object_or_404(Post, slug=slug), 'users': User.objects.all(), 'groups': Group.objects.all(), } return render( request, 'posts/post_detail.html', data, RequestContext(request))
95558961b7316ea338064b1f068a0d7ceaa5e55f
[ "HTML", "reStructuredText", "INI", "Python", "Text", "Shell" ]
33
Text
rmgorman/django-guardian
0d4a634561fccd1f510d2f6e0b64ef99ad21ccf4
fddaa3d350681014e7e5dd3ee74fcc9b919eb6ed
refs/heads/master
<repo_name>samtfm/nice-rocks-landing-page<file_sep>/src/App.js import React from 'react'; import './App.scss'; import Banner from './components/Banner'; import { ThemeProvider } from '@material-ui/core' import { createMuiTheme } from '@material-ui/core/styles'; import InfoSection from './components/InfoSection'; import CenteredInfo from './components/CenteredInfo'; import Footer from './components/Footer'; const theme = createMuiTheme({ palette: { primary: { main: '#f7ad45', }, secondary: { main: '#12b8ff', }, }, }) function App() { return ( <ThemeProvider theme={theme}> <div className="App"> <Banner /> <CenteredInfo title={"Nice... “Rocks”?"} body={"This project was inspired by the bowerbird, which delicately assembles intricate nests filled with special flowers, shells, and rocks to share with that special somebird.\nIf you’re looking for a personal, friendly, “nest-to-nest” sharing system, we hope you find it here."} /> <InfoSection title={"There, for you"} paragraphs={[ { title: "Favorite things", body: "A Rock is a recommendation to you, for something you might enjoy. It could be music, books, articles, or really anything.", }, { title: "Personal content by design", body: 'There are no algorithmically generated feeds or influencer accounts to follow. The only recomendations you see will be made personally to you, by your friends.', }, { title: "Resharable", body: "Re-sharing a Rock that was sent to you is easy. Just tap the arrow icon and add a new note to your friend.", }, ]} screenshot={"./images/received-rocks.png"} graphic={"./images/bird.svg"} /> <InfoSection title={"No time pressure"} paragraphs={[ { title: "Customizable notification settings", body: "Choose times you want to be notified about new content. You can be alerted to new recommendations right when your workday ends and your leisure time begins.", }, { title: "Catch up at your leisure", body: "Rocks stay in your collection until you have the time for them. No more scrolling back through long chat threads to find the name of that movie you’ve been meaning to see.", }, { title: "Send a response", body: "Once you’re finished, send a response! Let your friend know if your thoughts, and the rock will move from your collection to your archive. Out of the way, but there if you want to revisit it.", }, ]} screenshot={"./images/send-response.png"} graphic={"./images/rocks.svg"} horizontalFlip /> <InfoSection title={"Secure and reliable"} paragraphs={[ { title: "Never lose a thing", body: "Nice rocks is built on Google Firebase, so all your data is stored on Google’s cloud servers.", }, { title: "Offline mode", body: "Access your collection without an internet connection. You can even send rocks and responses, which will queue in the background and then send as soon as you reconnect.", }, ]} screenshot={"./images/new-rock.png"} graphic={"./images/leaves.svg"} /> </div> <Footer /> </ThemeProvider> ); } export default App; <file_sep>/src/components/Banner.js import React from 'react'; import './Banner.scss'; import Button from '@material-ui/core/Button' import WatchLaterIcon from '@material-ui/icons/WatchLater'; import People from '@material-ui/icons/People'; import ChatIcon from '@material-ui/icons/Chat'; import FancyFavs from './FancyFavs'; const bullets = [ { icon: People, text: 'Share personal recommendations one\u2011on\u2011one' }, { icon: WatchLaterIcon, text: 'Browse your collection in your leisure time' }, { icon: ChatIcon, text: 'Use feedback on items you share to guide your next recommendation' }, ] const Banner = () => { return ( <> <div className='TopBar'> <div className='TopBar-contents'><span className='TopBar-brandName'>{"NiceRocks"}</span></div> </div> <section className='Banner'> <div> <h1 className='Banner-tagline'> {"Recommend your \u00A0"}<FancyFavs></FancyFavs>{" to your favorite\u00A0people"} </h1> <div className='Banner-keyFeatures'> <ul > {bullets.map(bullet => ( <li key={bullet.text}> <bullet.icon style={{color: '#ffc229'}}/> <span>{bullet.text}</span> </li> ))} </ul> </div> <h2 className={'Banner-coming-soon'}>{"Coming soon to iOS and Android"}</h2> {/* <div className='Banner-buttons'> <span> <Button size="large" variant="contained" color="secondary">iOS</Button> <Button size="large" variant="contained" color="secondary">Android</Button> </span> </div> */} </div> </section> </> ) } export default Banner;<file_sep>/src/useResponsiveState.js import { useState, useEffect } from 'react'; const useResponsiveState = () => { const [responsiveState, setResponsiveState] = useState(null); useEffect(() => { const onResize = () => { if (window.innerWidth <= 600) { setResponsiveState('mobile') } else { setResponsiveState('desktop') } } window.addEventListener("resize", onResize); return () => window.removeEventListener("mouseup", onResize); }, []); return responsiveState; } export default useResponsiveState;<file_sep>/src/components/CenteredInfo.js import React from 'react'; import './CenteredInfo.scss'; const CenteredInfo = ({title, body}) => { console.log(body.split('\n')) return ( <section className='CenteredInfo'> <h1 className={'CenteredInfo-title'}>{title}</h1> {body.split('\n').map(paragraph => ( <p key={paragraph.slice(0, 10)}> {paragraph} </p> ))} </section> ) } export default CenteredInfo;
440c964a672417dff18ab65acc35f3184e000005
[ "JavaScript" ]
4
JavaScript
samtfm/nice-rocks-landing-page
d551178c5e48971b2ed54c039ddb0ab7b416a914
34647e21445c3711c1ac827d132adef5b0058ddd
refs/heads/master
<file_sep> /* A simple One-Pass Compiler */ /* global.h */ #include <stdio.h> /* include declarations for i/o routines */ #include <ctype.h> /* ... and for character test routines */ #include <stdlib.h> /*and for some standard routines, such as exit*/ #include <string.h> /* ... and for string routines */ #define BSIZE 128 /* buffer size */ #define NONE -1 #define EOS '\0' #define NUM 256 #define DIV 257 #define MOD 258 #define ID 259 #define DONE 260 extern int tokenval; /* value of token attribute */ extern int lineno; struct entry { /* form of symbol table entry */ char *lexptr; int token; int value; }; struct StackItem { int t; int tval; }; struct StackTrace { char* description; struct StackTrace* next; }; extern struct entry symtable[]; /* symbol table */ void emit (int t, int tval); /* generates output */ void error(char* m); /* generates all error messages */ void stack1Push(int t, int tval); /* Pushes to the stack 1 */ struct StackItem stack1Pop(); /* Pops from the stack 1 */ void stack2Push(int t, int tval); /* Pushes to the stack 2 */ struct StackItem stack2Pop(); /* Pops from the stack 2 */ char* calculateStack(); /* Calculates the stack contents */ int stack1Size(); /* The current size of the stack 1 */ int stack2Size(); /* The current size of the stack 2 */ //----------------------------------------------------- /* lexer.c */ char lexbuf[BSIZE]; int lineno = 1; int tokenval = NONE; int lexan (){ /* lexical analyzer */ int t; while(1) { t = getchar (); if (t == ' ' || t == '\t') ; /* strip out white space */ else if (t == '\n') lineno = lineno + 1; else if (isdigit (t)) { /* t is a digit */ ungetc(t, stdin); scanf("%d", &tokenval); return NUM; } else if (isalpha(t)) { /* t is a letter */ int p, b = 0; while (isalnum(t)) { /* t is alphanumeric */ lexbuf [b] = t; t = getchar (); b = b + 1; if (b >= BSIZE) error("compiler error"); } lexbuf[b] = EOS; if (t != EOF) ungetc(t, stdin); p = lookup (lexbuf); if (p == 0) p = insert (lexbuf, ID); tokenval = p; return symtable[p].token; } else if (t == EOF) return DONE; else { tokenval = NONE; return t; } } } //----------------------------------------------------- /* parser.c -- without the optimizations */ int lookahead; char* match(int); void start(), list(); char* expr(); char* moreterms(); char* term(); char* morefactors(); char* factor(); void parse() /* parses and translates expression list */ { lookahead = lexan(); start(); } void start () { /* Just one production for start, so we don't need to check lookahead */ list(); match(DONE); } void finishExpression(char* err){ if (err != NULL) printf("Error at line %d: %s => %c\n", lineno, err, lookahead); while (lookahead != ';') lookahead = lexan(); parse(); } void list() { if (lookahead == '(' || lookahead == ID || lookahead == NUM) { char* err = expr(); if (err == NULL) { err = calculateStack(); if (err == NULL){ err = match(';'); if (err == NULL) { list(); } else { finishExpression(err); } } else { finishExpression(err); } } else { finishExpression(err); } } else { /* Empty */ finishExpression(NULL); } } char* expr () { char* err; if (lookahead == ID){ emit(lookahead, tokenval); match(ID); if (lookahead == '=') { err = match('='); if (err != NULL) return err; err = term(); if (err != NULL) return err; err = moreterms(); if (err != NULL) return err; emit('=', tokenval); } else err = moreterms(); if (err != NULL) return err; } else{ err = term(); if (err != NULL) return err; err = moreterms(); if (err != NULL) return err; } return NULL; } char* moreterms() { char* err; if (lookahead == '+') { err = match('+'); if (err != NULL) return err; err = term(); if (err != NULL) return err; emit('+', tokenval); err = moreterms(); if (err != NULL) return err; } else if (lookahead == '-') { err = match('-'); if (err != NULL) return err; err = term(); if (err != NULL) return err; emit('-', tokenval); err = moreterms(); if (err != NULL) return err; } else { /* Empty */ } return NULL; } char* term () { /* Just one production for term, so we don't need to check lookahead */ char* err; err = factor(); if (err != NULL) return err; err = morefactors(); if (err != NULL) return err; return NULL; } char* morefactors () { char* err; if (lookahead == '*') { err = match('*'); if (err != NULL) return err; err = factor(); if (err != NULL) return err; emit('*', tokenval); err = morefactors(); if (err != NULL) return err; } else if (lookahead == '/') { err = match('/'); if (err != NULL) return err; err = factor(); if (err != NULL) return err; emit('/', tokenval); err = morefactors(); if (err != NULL) return err; } else if (lookahead == DIV) { err = match(DIV); if (err != NULL) return err; err = factor(); if (err != NULL) return err; emit(DIV, tokenval); err = morefactors(); if (err != NULL) return err; } else if (lookahead == MOD) { err = match(MOD); if (err != NULL) return err; err = factor(); if (err != NULL) return err; emit(MOD, tokenval); err = morefactors(); if (err != NULL) return err; } else { /* Empty */ } return NULL; } char* factor () { char* err; if (lookahead == '(') { err = match('('); if (err != NULL) return err; err = expr(); if (err != NULL) return err; err = match(')'); if (err != NULL) return err; } else if (lookahead == ID) { int id_lexeme = tokenval; err = match(ID); if (err != NULL) return err; emit(ID, id_lexeme); } else if (lookahead == NUM) { int num_value = tokenval; err = match(NUM); if (err != NULL) return err; emit(NUM, num_value); } else return "syntax error in factor"; return NULL; } char* match(int t) { char* err; if (lookahead == t) lookahead = lexan(); else{ return "syntax error in match"; } return NULL; } //----------------------------------------------------- /* emitter.c */ void emit (int t, int tval) /* generates output */ { stack1Push(t, tval); return; switch(t) { case '+' : case '-' : case '*' : case '/': case '=': printf("%c\n", t); break; case DIV: printf("DIV\n"); break; case MOD: printf("MOD\n"); break; case NUM: printf("%d\n", tval); break; case ID: printf("%s\n", symtable[tval].lexptr); break; default: printf("token %d, tokenval %d\n", t, tval); } } //----------------------------------------------------- /* symbol.c */ #define STRMAX 999 /* size of lexemes array */ #define SYMMAX 100 /* size of symbol table */ char lexemes[STRMAX]; int lastchar = - 1; /* last used position in lexemes */ struct entry symtable[SYMMAX]; int lastentry = 0; /* last used position in symtable */ int lookup(char *s) /* returns position of entry for s */ { int p; for (p = lastentry; p > 0; p = p - 1) if (strcmp(symtable[p].lexptr, s) == 0) return p; return 0; } int insert(char *s, int tok)/*returns position of entry for s*/ { int len; len = strlen(s); /* strlen computes length of s */ if (lastentry + 1 >= SYMMAX) error ("symbol table full"); if (lastchar + len + 1 >= STRMAX) error ("lexemes array full"); lastentry = lastentry + 1; symtable[lastentry].token = tok; symtable[lastentry].lexptr = &lexemes[lastchar + 1]; lastchar = lastchar + len + 1; strcpy(symtable[lastentry].lexptr, s); return lastentry; } //----------------------------------------------------- /* init.c */ struct entry keywords[] = { { "div", DIV }, { "mod", MOD, }, { 0, 0 } }; void init() /* loads keywords into symtable */ { struct entry *p; for (p = keywords; p->token; p++) insert(p->lexptr, p->token); } //----------------------------------------------------- /* error.c */ void error(char* m) /* generates all error messages */ { fprintf(stderr, "line %d: %s\n", lineno, m); //exit(EXIT_FAILURE); /* unsuccessful termination */ } //----------------------------------------------------- /* main.c */ int main( ) { init(); parse(); exit(0); /* successful termination */ } //------------------------------------------------------ /* stack.c */ struct StackItem stack1[1024]; int stack1Pointer = -1; struct StackItem stack2[1024]; int stack2Pointer = -1; void stack1Push(int t, int tval){ struct StackItem a; a.t = t; a.tval = tval; stack1Pointer++; stack1[stack1Pointer] = a; } int stack1Size(){ return stack1Pointer + 1; } int stack2Size(){ return stack2Pointer + 1; } struct StackItem stack1Pop(){ if (stack1Pointer == -1){ struct StackItem a; a.t = NONE; return a; } return stack1[stack1Pointer--]; } void stack2Push(int t, int tval){ struct StackItem a; a.t = t; a.tval = tval; stack2Pointer++; stack2[stack2Pointer] = a; } struct StackItem stack2Pop(){ if (stack2Pointer == -1) { struct StackItem a; a.t = NONE; return a; } return stack2[stack2Pointer--]; } void stack2BackToStack1(){ struct StackItem tmpItem = stack2Pop(); while (tmpItem.t != NONE){ stack1Push(tmpItem.t, tmpItem.tval); tmpItem = stack2Pop(); } } void printStack1(){ struct StackItem i = stack1Pop(); printf("---------------Stack-----------\n"); int count = 0; while (i.t != NONE){ count++; stack2Push(i.t, i.tval); if (i.t == ID) printf("%s\n", symtable[i.tval].lexptr); else if (i.t == NUM) printf("%d\n", i.tval); else printf("%c\n", i.t); i = stack1Pop(); } for (int j = 0; j < count; j++){ i = stack2Pop(); stack1Push(i.t, i.tval); } printf("----------------End------------\n"); } int aaa = 1; char* calculateStack(){ struct StackItem item = stack1Pop(); int lastOperator = NONE; int hasLastNum = 0; // as boolean int lastNum; char* err; while (item.t != NONE){ switch (item.t){ case '+': case '-': case '*': case '/': case DIV: case MOD: case '=': if (lastOperator != NONE) stack2Push(lastOperator, NONE); lastOperator = item.t; break; case NUM: if (hasLastNum) { int result; switch (lastOperator){ case '+': result = item.tval + lastNum; break; case '-': result = item.tval - lastNum; break; case '*': result = item.tval * lastNum; break; case '/': case DIV: result = item.tval / lastNum; break; case MOD: result = item.tval % lastNum; break; default: printStack1(); return "Invalid operation"; } stack1Push(NUM, result); stack2BackToStack1(); hasLastNum = 0; lastOperator = NONE; } else { lastNum = item.tval; hasLastNum = 1; } break; case ID: if (lastOperator == '='){ if (hasLastNum){ // put last num to symtable symtable[item.tval].value = lastNum; } else { return "Nothing to asign to variable"; } } else { // add value of id to the stack1 stack1Push(NUM, symtable[item.tval].value); if (hasLastNum) stack1Push(NUM, lastNum); if (lastOperator != NONE) stack1Push(lastOperator, NONE); stack2BackToStack1(); hasLastNum = 0; lastOperator = NONE; } } item = stack1Pop(); } printf("%d\n", lastNum); // Empty second stack item = stack2Pop(); while(item.t != NONE) item = stack2Pop(); return NULL; }
54deb758fe50afce21528cc43d8ebe38ecb4ff03
[ "C" ]
1
C
emranbm/eLex
21012cd5929ecc8d1a9bf132a765335aa0f455c8
ce638104dc8c2f8cf03424acd58455b7e0607fe6
refs/heads/master
<repo_name>jacekngo/CVApp-master<file_sep>/app/src/main/java/io/github/wzieba/supercv/MainActivity.java package io.github.wzieba.supercv; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.NavigationView; import android.support.v4.app.Fragment; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.MenuItem; import android.widget.FrameLayout; import butterknife.BindView; import butterknife.ButterKnife; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { public static final String TAG = MainActivity.class.getSimpleName(); @BindView(R.id.drawerLayout) DrawerLayout drawerLayout; @BindView(R.id.container) FrameLayout container; @BindView(R.id.navigationView) NavigationView navigationView; @BindView(R.id.toolbar) Toolbar toolbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); setupToolbar(); navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { toolbar.setTitle(item.getTitle()); item.setChecked(true); switch (item.getItemId()) { case R.id.menu_contact: openFragment(ContactFragment.newInstance()); break; case R.id.menu_experience: break; case R.id.menu_skills: openFragment(SkillsFragment.newInstance()); break; } drawerLayout.closeDrawer(Gravity.LEFT); return false; } }); } @Override protected void onPostCreate(@Nullable Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); navigationView.getMenu().performIdentifierAction(R.id.menu_contact, 0); } private void openFragment(Fragment fragment) { getSupportFragmentManager() .beginTransaction() .replace(R.id.container, fragment) .commit(); } private void setupToolbar() { setSupportActionBar(toolbar); ActionBarDrawerToggle adidas = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.app_name, R.string.app_name); drawerLayout.addDrawerListener(adidas); adidas.syncState(); } @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { return false; } }
cdacf3d39d16bb45e84b0145019cdb24e6a0c5bc
[ "Java" ]
1
Java
jacekngo/CVApp-master
58e3a5ae62714ccf962f2e5c5fd09728fab26021
c6635b2433502102b1819099f9b5e47fc95492fa
refs/heads/master
<repo_name>olossss/3DModel<file_sep>/3DModel/Game1.cs using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; namespace _3DModel { public class Game1 : Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; private Model model; private Matrix world = Matrix.CreateTranslation(0,0,0); private Matrix view = Matrix.CreateLookAt(new Vector3(-4, 3, 5), new Vector3(2, -1, 0), Vector3.Up); private Matrix projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(60), 800f / 480f, 0.1f, 100f); public Game1() : base() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; } protected override void Initialize() { // TODO: Add your initialization logic here base.Initialize(); } protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); model = Content.Load<Model>("1x2x5"); // TODO: use this.Content to load your game content here } protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } protected override void Update(GameTime gameTime) { if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape)) Exit(); // TODO: Add your update logic here base.Update(gameTime); } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); DrawModel(model, world, view, projection); // TODO: Add your drawing code here base.Draw(gameTime); } private void DrawModel(Model model, Matrix world, Matrix view, Matrix projection) { foreach (ModelMesh mesh in model.Meshes) { foreach (BasicEffect effect in mesh.Effects) { effect.World = world; effect.View = view; effect.Projection = projection; } mesh.Draw(); } } } }
76be7182d0460af871940423e1da5545d9c5bfa6
[ "C#" ]
1
C#
olossss/3DModel
84b7e7ff7a497d5e0595719c307da0c77e64dcad
98edcf028d75ec810488d66251ea2632fe100237
refs/heads/master
<repo_name>lordcirth/minetest-digipad<file_sep>/README.txt HybridDog has taken over maintaining this mod https://github.com/HybridDog/digipad The digipad allows you to enter a number 1-10 digits, which will be sent down a digiline. You can select channels 1-3 with buttons in the formspec. channels are prefixed with "keypad" so Channel 1 transmits on "keypad1" etc. The hardened digipad shares the same functions, but has different physical properties. It is a full 1m wide, so it can cover a wire channel in a wall completely. It also has the same digging properties as a steel block, so some random noob with a stone pickaxe can't steal it. The keyboard allows arbitrary strings to be entered. It sends only on channel "keyb1" right now. The terminal allows entering strings, and receiving responses. It's channel prefix is "tty" and the suffix can be set with /channel <suffix>. Default suffix is "1", making the channel "tty1". "/help" will display a help text. See also - https://github.com/lordcirth/minetest-wireless adds wireless transmitters/receivers - excellent for passworded doors with no traceable wire. Just link a digipad to a wireless transmitter, and a receiver to the luacontroller for the door. <file_sep>/init.lua digipad = {} dofile(minetest.get_modpath("digipad").."/terminal.lua") -- add terminal to mod -- ======================== --Declare shared variables / functions -- ======================== digipad.digipad_formspec = -- Defines the grid of buttons "size[4,6]".. "button[0,1;1,1;dc1;1]button[1,1;1,1;dc2;2]button[2,1;1,1;dc3;3]".. "button[0,2;1,1;dc4;4]button[1,2;1,1;dc5;5]button[2,2;1,1;dc6;6]".. "button[0,3;1,1;dc7;7]button[1,3;1,1;dc8;8]button[2,3;1,1;dc9;9]".. "button_exit[0,4;1,1;dcC;Cancel]button[1,4;1,1;dc0;0]button_exit[2,4;1,1;dcA;Submit]".. "button[3,1;1,1;chan1;Chan 1]button[3,2;1,1;chan2;Chan 2]button[3,3;1,1;chan3;Chan 3]" digipad.hidecode = function(len) if (len == 0 or len==nil) then return "" -- not sure if needed else return string.rep("*",len) end end digipad.submit = function (pos, channel, number) --minetest.chat_send_player("singleplayer", "Code is "..number) digiline:receptor_send(pos, digiline.rules.default, channel, number) end digipad.cons = function (pos) local meta = minetest.env:get_meta(pos) meta:set_string("formspec", digipad.digipad_formspec.."label[0,0;Enter Code:]") meta:set_string("code", "") meta:set_string("baseChannel", "keypad"); meta:set_int("channelExt",1) end digipad.recvFields = function(pos,formname,fields,sender) local meta = minetest.env:get_meta(pos) local node=minetest.env:get_node(pos) local rules=mesecon.rules.buttonlike_get(node) local baseChannel=meta:get_string("baseChannel") local ext=meta:get_int("channelExt") local code=meta:get_string("code") if fields.dcA then --Accept button if code~="" then digipad.submit(pos, (baseChannel..ext), code) --print(meta:get_string("baseChannel")) --~ else --~ meta:set_string("formspec", digipad.digipad_formspec.."label[0,0;Enter Code:]") end meta:set_string("code","") elseif fields.dcC then -- Cancel button meta:set_string("formspec", digipad.digipad_formspec.."label[0,0;Enter Code:]") meta:set_string("code","") elseif fields.chan1 then --Set Channel 1 meta:set_int("channelExt",1) elseif fields.chan2 then --Set Channel 2 meta:set_int("channelExt",2) elseif fields.chan3 then --Set Channel 3 meta:set_int("channelExt",3) else local button=nil; if fields.dc0 then button="0" elseif fields.dc1 then button="1" elseif fields.dc2 then button="2" elseif fields.dc3 then button="3" elseif fields.dc4 then button="4" elseif fields.dc5 then button="5" elseif fields.dc6 then button="6" elseif fields.dc7 then button="7" elseif fields.dc8 then button="8" elseif fields.dc9 then button="9" end if button then -- if button ~= nil (ie a number button was pressed) if string.len(meta:get_string("code")) >= 10 then -- If code is really long, submit & start over digipad.submit(pos, (baseChannel..ext), code) meta:set_string("code","") end meta:set_string("code",meta:get_string("code")..button) end end meta:set_string("formspec",digipad.digipad_formspec.."label[1,0;"..digipad.hidecode(meta:get_string("code"):len()).."]") end -- ======================== -- Begin node declarations -- ======================== minetest.register_node("digipad:digipad", { description = "Digipad", tiles = { "digicode_side.png", "digicode_side.png", "digicode_side.png", "digicode_side.png", "digicode_side.png", "digicode_front.png" }, drawtype = "nodebox", paramtype = "light", paramtype2 = "facedir", sunlight_propagates = true, walkable = true, inventory_image = "digicode_front.png", selection_box = { type = "fixed", fixed = { -6/16, -.5, 6/16, 6/16, .5, 8/16 } }, node_box = { type = "fixed", fixed = { -6/16, -.5, 6/16, 6/16, .5, 8/16 } }, digiline = { receptor={}, }, groups = {choppy = 3, dig_immediate = 2}, sounds = default.node_sound_stone_defaults(), on_construct = function(pos) --Initialize some variables (local per instance) local meta = minetest.env:get_meta(pos) digipad.cons(pos) meta:set_string("infotext", "Digipad") end, on_receive_fields = function(pos,formname,fields,sender) digipad.recvFields(pos,formname,fields,sender) end }) minetest.register_node("digipad:digipad_hard", { description = "Hardened Digipad", tiles = { "digicode_side.png", "digicode_side.png", "digicode_side.png", "digicode_side.png", "digicode_side.png", "digipad_hard_front.png" }, drawtype = "nodebox", paramtype = "light", paramtype2 = "facedir", sunlight_propagates = true, walkable = true, digiline = { receptor={}, }, node_box = { type = "fixed", --All values -0.5 to 0.5, measured from center --- Left, down, depth of front, right, up, depth of back fixed = { -0.5, -.5, 1/4, 0.5, .5, 0.5} }, inventory_image="digipad_hard_front.png", groups = {cracky=1,level=2}, on_construct = function(pos) local meta = minetest.env:get_meta(pos) digipad.cons(pos) meta:set_string("infotext", "Hardened Digipad") end, on_receive_fields = function(pos,formname,fields,sender) digipad.recvFields(pos,formname,fields,sender) end }) -- ======================== --Crafting recipes -- ======================== minetest.register_craft({ output = 'digipad:digipad', recipe = { {"mesecons_button:button_off", "mesecons_button:button_off", "mesecons_button:button_off"}, {"default:steel_ingot", "mesecons_luacontroller:luacontroller0000", "default:steel_ingot"}, {"default:steel_ingot", "digilines:wire_std_00000000", "default:steel_ingot"}, } }) minetest.register_craft({ output = 'digipad:digipad_hard', recipe = { {"default:steel_ingot", "default:steel_ingot", "default:steel_ingot"}, {"default:steel_ingot", "digipad:digipad", "default:steel_ingot"}, {"default:steel_ingot","digilines:wire_std_00000000","default:steel_ingot"}, } })<file_sep>/terminal.lua -- ================ -- Variable declarations -- ================ digipad.keyb_form_first = "size[4,1;]".. "field[0,0;2,1;chan;Channel;]".. "label[0,0;Channel " digipad.keyb_form_second = "]".. "field[0,1;5,1;input;Input;]" digipad.keyb_base_chan = "keyb" digipad.keyb_def_chan = "1" digipad.term_base_chan = "tty" digipad.term_def_chan = "1" digipad.keyb_formspec = digipad.keyb_form_first .. digipad.keyb_base_chan .. digipad.keyb_def_chan .. digipad.keyb_form_second digipad.terminal_formspec = "size[4,5;]".. "field[0,5;5,1;input;;]" -- ================ -- Function declarations -- ================ digipad.get_keyb_formspec = function(pos) -- Construct updated formspec for keyboard local meta = minetest.env:get_meta(pos) local current_chan = meta:get_string("chan_num") new_formspec = "size[4,1;]".. "field[0,0;2,1;chan;Channel;" .. current_chan .. "]".. "label[0,0;Channel " .. digipad.keyb_base_chan .. current_chan .. "]".. "field[0,1;5,1;input;Input;]" return new_formspec end digipad.set_channel = function(pos, new_channel) local meta = minetest.env:get_meta(pos) meta:set_string("channel", new_channel) end digipad.help = function(pos) -- print help text digipad.new_line(pos, "Commands preceded with a / go to the") digipad.new_line(pos, "terminal. All others are sent along the digiline.") digipad.new_line(pos, "Commands are: /clear /help /channel") end digipad.delete_spaces = function(s) -- <NAME> -- trim whitespace from both ends of string return s:find'^%s*$' and '' or s:match'^%s*(.*%S)' end digipad.clear = function(pos) local meta = minetest.env:get_meta(pos) print("clearing screen") meta:set_string("formspec", digipad.terminal_formspec) -- reset to default formspec meta:set_int("lines", 0) -- start at the top of the screen again end digipad.parse_cmd = function(pos, cmd) if cmd == "clear" then digipad.clear(pos) elseif cmd == "help" then digipad.help(pos) elseif string.sub(cmd, 1, 7) == "channel" then -- If cmd _starts_with_ "channel", since we need an argument too. raw_arg = string.sub(cmd, 8) -- Cut "channel" out arg = digipad.delete_spaces(raw_arg) if (arg ~= nil) and (arg ~= "") then digipad.set_channel(pos, digipad.term_base_chan .. arg) digipad.new_line(pos, "Channel set to " .. digipad.term_base_chan .. arg) else -- no argument digipad.new_line(pos, "Example: ''/channel 2'' will change") digipad.new_line(pos, "the channel to ''tty2'' ") end else digipad.new_line(pos, cmd .. ": command not found") end end local on_digiline_receive = function (pos, node, channel, msg) digipad.new_line(pos, msg) end digipad.new_line = function(pos, text) local max_chars = 40 local max_lines = 10 local meta = minetest.env:get_meta(pos) local lines = meta:get_int("lines") if lines > max_lines then -- clear screen before printing the line - so it's never blank digipad.clear(pos) lines = meta:get_int("lines") --update after clear end local formspec = meta:get_string("formspec") local offset = lines / 4 line = string.sub(text, 1, max_chars) -- take first chars local new_formspec = formspec .. "label[0," .. offset .. ";" .. line .. "]" meta:set_string("formspec", new_formspec) lines = lines + 1 meta:set_int("lines", lines) meta:set_string("formspec", new_formspec) if string.len(text) > max_chars then -- If not all could be printed, recurse on the rest of the string text = string.sub(text,max_chars) digipad.new_line(pos, text) end end -- ================ -- Node declarations -- ================ minetest.register_node("digipad:keyb", { description = "Digiline keyboard", paramtype = "light", paramtype2 = "facedir", sunlight_propagates = true, walkable = true, digiline = { receptor={}, effector={}, }, tiles = { "keyb.png", "digicode_side.png", "digicode_side.png", "digicode_side.png", "digicode_side.png", "digicode_side.png" }, drawtype = "nodebox", selection_box = { type ="fixed", fixed = {-0.500000,-0.500000,-0.000000,0.500000,-0.3,0.5}, -- Keyboard }, node_box = { type ="fixed", fixed = {-0.500000,-0.500000,-0.000000,0.500000,-0.3,0.5}, -- Keyboard }, groups = {dig_immediate = 2}, on_construct = function(pos) local meta = minetest.env:get_meta(pos) meta:set_string("formspec", digipad.keyb_formspec) meta:set_string("Infotext", "Keyboard") -- set default channel (base + default extension) : meta:set_string("channel", digipad.keyb_base_chan .. digipad.keyb_def_chan) end, on_receive_fields = function(pos, formname, fields, sender) local meta = minetest.env:get_meta(pos) local channel = meta:get_string("channel") local text = fields.input if (fields.chan ~= "") and (fields.chan ~= nil) then local chan_num = fields.chan meta:set_string("chan_num", chan_num) -- save user's channel suffix choice channel = digipad.keyb_base_chan .. chan_num meta:set_string("channel", channel) -- save resulting channel end if text ~= nil then digiline:receptor_send(pos, digiline.rules.default, channel, text) end meta:set_string("formspec", digipad.get_keyb_formspec(pos))-- generate new formspec end, }) minetest.register_node("digipad:terminal", { description = "Interactive Terminal", paramtype = "light", paramtype2 = "facedir", sunlight_propagates = true, walkable = true, drawtype = "nodebox", selection_box = { type = "fixed", fixed = { {-0.5, -0.5, -0.5, 0.5, -0.3, 0}, -- Keyboard {-0.5, -0.5, 0, 0.5, 0.5, 0.5}, --Screen } }, node_box = { type = "fixed", fixed = { {-0.5, -0.5, -0.5, 0.5, -0.3, 0}, -- Keyboard {-0.5, -0.5, 0, 0.5, 0.5, 0.5}, --Screen } }, tiles = { "terminal_top.png", "digicode_side.png", "digicode_side.png", "digicode_side.png", "digicode_side.png", "terminal_front.png" }, digiline = { receptor={}, effector = { action = on_digiline_receive }, }, groups = {dig_immediate = 2}, on_construct = function(pos) local meta = minetest.env:get_meta(pos) meta:set_string("formspec", digipad.terminal_formspec) meta:set_string("Infotext", "Terminal") meta:set_int("lines", 0) -- set default channel (base + default extension) : meta:set_string("channel", digipad.term_base_chan .. digipad.term_def_chan) digipad.new_line(pos, "/help for help") -- print welcome text end, on_receive_fields = function(pos, formname, fields, sender) local meta = minetest.env:get_meta(pos) local text = fields.input local channel = meta:get_string("channel") print(channel) if text ~= nil then digipad.new_line(pos, "> " .. text) if string.sub(text,1,1) == "/" then -- command is for terminal text = string.sub(text, 2) -- cut off first char digipad.parse_cmd(pos, text) else digiline:receptor_send(pos, digiline.rules.default, channel, text) end end local formspec = meta:get_string("formspec") --minetest.show_formspec("singleplayer", "terminal", formspec) doesn't allow submit anyway end, }) -- ================ --Crafting recipes -- ================ minetest.register_craft({ output = "digipad:keyb", recipe = { {"mesecons_button:button_off", "mesecons_button:button_off", "mesecons_button:button_off"}, {"mesecons_button:button_off", "mesecons_button:button_off", "mesecons_button:button_off"}, {"default:steel_ingot", "digilines:wire_std_00000000", "default:steel_ingot"} } }) minetest.register_craft({ output = "digipad:terminal", recipe = { {"", "digilines_lcd:lcd", "default:steel_ingot"}, {"digipad:keyb", "mesecons_luacontroller:luacontroller0000", "default:steel_ingot"}, {"default:steel_ingot", "digilines:wire_std_00000000", "default:steel_ingot"} } })
b906e89b9aba9a2b0a12d02c7a201cedd206ef54
[ "Text", "Lua" ]
3
Text
lordcirth/minetest-digipad
9182584ffcc80e351efaf4337c52f1ba8bf40f74
351b23c3361ae50c461999f12bdd9ce4c6e73729
refs/heads/main
<file_sep>let userScore=0; let compScore=0; const userScore_span=document.getElementById("userscore"); const compScore_span=document.getElementById("computerscore"); const scoreboard_div=document.querySelector(".scoreboard"); const result_p=document.querySelector(".result > p"); const rock_div=document.getElementById("r"); const paper_div=document.getElementById("p"); const scissors_div=document.getElementById("s"); function getComputerChoice(){ const choices=['r','p','s']; const randomNumber = Math.floor((Math.random()*3)); return choices[randomNumber]; } function convertToWord(letter){ if(letter === "r") return "Rock"; if(letter === "p") return "Paper"; if(letter === "s") return "Scissors"; } function win(user, comp) { userScore++; userScore_span.innerHTML=userScore; compScore_span.innerHTML= compScore; const smallUserWord="(user)".fontsize(3).sub(); const smallCompWord="(comp)".fontsize(3).sub(); result_p.innerHTML= `${convertToWord(user)}${smallUserWord} Beats ${convertToWord(comp)}${smallCompWord}. You Win`; } function lose(user, comp) { compScore++; userScore_span.innerHTML=userScore; compScore_span.innerHTML= compScore; const smallUserWord="user".fontsize(3).sub(); const smallCompWord="comp".fontsize(3).sub(); result_p.innerHTML= `${convertToWord(comp)}${smallCompWord} Beats ${convertToWord(user)}${smallUserWord}. You Lose`; } function draw(user, comp) { result_p.innerHTML= "Its a draw"; } function gain(userChoice){ const computerChoice = getComputerChoice(); switch(userChoice + computerChoice){ case "rs": case "pr": case "sp": win(userChoice, computerChoice); break; case "rp": case "ps": case "sr": lose(userChoice, computerChoice); break; case "rr": case "pp": case "ss": draw(userChoice, computerChoice); break; } } gain("c"); function main(){ rock_div.addEventListener("click", function(){ gain("r"); }) paper_div.addEventListener("click", function(){ gain("p"); }) scissors_div.addEventListener("click", function(){ gain("s"); }) } main();
fbd8bb2d33ceeebd0b85fdb0fdb5540be84e5a18
[ "JavaScript" ]
1
JavaScript
ashishmaithani17/ROCK_PAPER_SCISSORS
d7f44fb89661be203d66717f48604221e0b7f760
d2f634c31b72e13557cbfd527fbfd38455332d76
refs/heads/master
<repo_name>stephanwlee/mendel<file_sep>/packages/mendel-config/src/helpers/validator.js const chalk = require('chalk'); const _errors = []; function maybeThrowIfError() { if (!_errors.length) return; throw new Error('Configuration Errors\n' + _errors.join('\n')); } module.exports = function createValidator(schema) { return function(instance, injected = {}) { var error = []; Object.keys(schema).forEach(function(schemaKey) { var criteria = schema[schemaKey]; var value = instance[schemaKey]; var curError = []; if (criteria.required && typeof value === 'undefined') { curError.push('Required field "' + chalk.red(schemaKey) + '" is not present.'); } var type = Array.isArray(value) ? 'array' : typeof value; if (criteria.type && type !== criteria.type) { curError.push('Requires `' + chalk.red(schemaKey) + '` to be of type [' + criteria.type + '] but is [' + type + ']'); } if (Array.isArray(value)) { if (criteria.minLen && criteria.minLen > value.length) { curError.push('Expected `' + chalk.red(schemaKey) + '` to be at least ' + criteria.minLen + ' long'); } if (criteria.maxLen && criteria.maxLen < value.length) { curError.push('Expected `' + chalk.red(schemaKey) + '` to be below ' + criteria.maxLen + ' long'); } } if (curError.length) { if (criteria.errorMessage) { const message = Object.keys(injected) .reduce((msg, key) => { const regex = new RegExp('\\$' + key, 'g'); return msg.replace(regex, injected[key]); }, criteria.errorMessage); error.push(message + '\n ' + curError.join('\n ')); } else { error = error.concat(curError); } } }); if (instance.options && Array.isArray(schema.supportedOptionFields)) { const unsupportedOptionFields = Object.keys(instance.options).filter(field => { return schema.supportedOptionFields.indexOf(field) === -1; }); if (unsupportedOptionFields.length > 0) { error.push('Found unsupported options `' + unsupportedOptionFields.join('`, `') + '`'); } } if (error.length) { _errors.push( error.filter(Boolean).reduce(function(reduced, error) { return reduced += chalk.red('x ') + error + '\n'; }, '') // Figure out better way of debugging // JSON.stringify(instance, null, 2) ); } }; }; module.exports.maybeThrowIfError = maybeThrowIfError; <file_sep>/docs/Design.md Mendel Design ============= # Principles Mendel has some opinionated design principles that serve as strict guidelines on the remainder of this document and on its implementation. Some of those principles are what makes Mendel different from other experimentation or A/B testing frameworks. * **Variation Performance** * **No payload overhead**: no client-side code for any non-active or alternative variation should be transfered to the client * **Synchronous and fast variation resolution**: no http or file-system access during runtime in order to resolve bundle URLs or bundle payload. * **Variation Maintainability** * **Immediately disposable**: disposing of variations should be simple, straightforward - specially for bulk disposal * **No maintenance overhead: **keep variations updated with minimal developer effort * **Mnemonic source-code**: only human-readable and meaningful variation names should be committed to the source-code repository * **Analyzable**: comparison between variations code is essential. Developers should be able to `diff` variations easily – without guesswork or source code parsers * **Variation Security** * client-side compiled code should not contain variation information * client-side asset URI should not contain variation information # Additional Goals Those are not mission critical, but go into details of aforementioned principles and add some extra requirements that are also very valuable to be covered. ## Development Environment When possible, development environment should be the same as production environment, but there are additional challenges and features that need to be supported on development. Here are some highlights: ### Development time Mendel features * Source Maps are required in development * Might be useful in production if we can have it be external and separate routes that can have extra security in case consumer don't want to be available for visiting users * Fast code reload: once one file is saved, regardless of how many implemented variations there are in the project, one should be able to see changes in browser (including server-side rendered markup) in under a second * Select/override which variation (as any other configuration) to be loaded in browser via many different methods, including (but not restricted to) query string, developer box local configuration and cookies * "Development only variations": When creating a variation, a developer should not need access or try out his new code without resorting to external configuration systems ### Expected differences when inspecting code in production or development * In development it should be easy and straightforward to spot variation code as opposed to __base variation__ (the code that exists in all variations) * In production we should obscure variations as much as possible, for security and privacy reasons, but this should not happen in development ## Performance requirements ### Production Performance Production performance is non-negotiable — we should not make trade-offs sacrificing production performance. Therefore, Mendel implementation should aim to have zero bytes added to client-side code when a variation is created. Any new code or code changes a variation contain should be only delivered to users on this variation and not to the __base variation__. Also we should not have latency increased for users on any variation and any performance optimizations, like SSR (server-side rendering). Those are the important performance goals for client side: * No byte size overhead * No extra network requests when the user is on a variation Those are the important goals for server-side: * Close to zero milliseconds variation resolution time in production * no network or file system operations after application startup/warm up * any runtime configuration update should be done with background polling/fetching/push to not impact request time * Server-side rendering should work correctly when switching variations * server needs to serve isomorphic code on a per-request basis ### Development Performance Developer Productivity is also important for any team and is proportionally more important with team size — The more people, the greater saves for the company if we invest in build-time and other quality of life improvements for developers. Here are some important goals for development cycle: * Mendel should avoid slowing down development server startup time * It is OK to increase CI/CD timings, although it would be ideal to keep the same * When saving a file, it is expected that the developer is able to see the changes within 300 milliseconds or less, be it client-side or server side changes. * Also, although a full automated refresh is not required, in case the developer reloads the page manually, server-side rendering must match and work as intended within this boundary * Live-reload or hot-loading is desirable, as well as keeping application state if possible * When using the Web-Inspector (browser tools) it is desirable to be able to tell apart code that is default from code that is on a given experiment ## Security The main goal for security is to make sure a user is not able to understand the extent of experiments she is assigned to. Although hiding the variation completely is impossible, the user, or intentional bad actors on the network, should not be able to tell the differences apart from each variation and infer business goals from it. So avoiding conditionals and mnemonic IDs to be part of the source code will be the main goal for security. Avoiding variation names on URLs will prevent sizable download of different bundles by scripts, so hashing will be used instead of variation names/numbers. # Methodology Mendel uses file system folders for variation resolution. The first part of this section is a preamble to why we reached this design, and the second part is dedicated to how the resolution should work. ## Conditional versus separate built packages There are different cases in which code may differ from the __base variation__ or "default" experience: * Experiments, also know as variations (ofter referred as "buckets" or A/B tests) * Conditional features (configuration based "feature flipper") * Partners customization (white labeling) There are mainly two ways of creating this differences for such variations: Conditionals to be evaluated in runtime and code selection at build time. **Conditional versus separate built packages flowchart** ``` +------------------+ +----------+ +---------------+ |Production Package| | | | | | | | Codebase +---> | Build Process +-------> +------+ +------+ | | | | |Code A| OR |Code B| +----------+ +---------------+ | | | | +------+----+------+ +-----------+ | | +---> | Package A | +----------+ +---------------+ | | | | | | | | +-----------+ | Codebase +---> | Build Process +---+ | | | | | +-----------+ +----------+ +---------------+ | | | +---> | Package B | | | +-----------+ ``` There is also two parts of Front-End responsibilities for an isomorphic project to serve features to users, the server-side and client-side portions. In React applications we have a lot of code that is isomorphic and will be used in both environments. ### Client-side Design > Important note: This section is outdated. Mendel design was conceived before we decided to have manifests with each file as a module. We expected to have some sort of grouping of those modules on the initial design and this section needs to be revised to convey the actual implementation. None of the principles changed. For client-side transferring (downloading) the code is very costly to user perceived performance. Shipping conditional code would mean client downloading code-paths that are impossible to be executed in the client given the variation a user is assigned to, adding unnecessary payload overhead. Therefore, the only viable approach is to have separate bundles (or modules) for each variation. For performance reasons each client might receive more than one bundle, usually optimized for caching. A bundle with modules that rarely changes provides more cache-hits than the main application bundle in CI/CD environments. So for each experiment, all bundles that have code differences will need a new bundle version. **Simplified Client-side packaging flowchart** ``` "BUCKET A" (or variation A) has files that only affect "Bundle D" +-------------------+ +---> | Default Bundle A | | +-------------------+ | +-------------------+ +---> | Default Bundle B | +----------+ +---------------+ | +-------------------+ | | | | | +-------------------+ | Codebase +---> | Build Process +--+---> | Default Bundle C | | | | | | +-------------------+ +----------+ +---------------+ | +-------------------+ +---> | Default Bundle D | | +-------------------+ | +-------------------+ +---> | BUCKET A Bundle D | +-------------------+ Colors: * Code shipped to all users * Code shipped to users in control (default) variation * Code shipped only to users in BUCKET A Notes: The above flowchart does not discuss transport. This simplification allows for better understanding of how the build process separates bundles/modules for each user variation. Also important to note is the fact that "BUCKET A Bundle D" most likely include some of the code on "Default Bundle D", but it is bundled together for performance. During implementation we might also choose to have a common package that does not contain any conditionals or any experiment code. The only benefit of this approach is caching, allowing a user that is assigned to a bucket to be unassigned and avoiding a whole application package to be re-fetched. Since we have continuous deployment, this will be a minor consideration, since every deploy will invalidate a number of packages. We will aim for being able to deploy daily and experiments usually run for at least 5 days, any performance improvements regarding deployment cache will benefit bucket testing caching strategies directly. ``` ### Server-side Design Performance concerns for server-side are different from client side. Server-side is about how much time application spend in memory and CPU or internal networking/file system operations before it flushes results to the client. For this reason, server side performance is split into two parts: #### Isomorphic Code and Server Side Rendering (SSR) Since client-side code will be separated in build time in different bundles, the isomorphic part of the server-side code should match exactly the client-side code and will need to follow the same strategy. For isomorphic code, we need to adopt the same source code design as client-side code. For this reason Mendel provides a resolver so NodeJS applications can "require" the modules with the same variations. #### Server only code Mendel is not opinionated for server only code. Any application using Mendel can continue to use their configuration systems and resolve variations in their own way. ## Isomorphic Source Code: Variations as file system folders On the source code, we will aim to fulfill all maintainability goals. To understand how a developer would create, maintain and remove variations, let's assume the following application structure: **Sample application file system tree** ``` bash> tree . ├── BuildToolFile.js ├── lib │ └── crypto.js ├── package.json ├── src │ ├── server │ │ ├── app.js │ │ ├── index.js │ │ ├── middleware.js │ │ └── utils.js │ └── ui │ ├── controllers │ │ ├── main.js │ │ ├── settings.js │ │ └── sidebar.js │ ├── main_bundle.js │ ├── vendor │ │ ├── calendar_widget.js │ │ ├── ember.js │ │ ├── jquery.js │ │ └── react.js │ └── views │ ├── admin.js │ ├── ads.js │ ├── list-item.js │ ├── list.js │ ├── login.js │ ├── new_item.js │ └── sidebar_item.js └── tests ├── server │ └── app.test.js └── ui └── views ├── admin.test.js ├── ads.test.js └── list.test.js ``` For each client-side (or isomorphic) file that will have code differences between control and a particular variation, we will create a folder with duplicate of files for each file that we need differences. For this particular application, all isomorphic code is on the /ui/ folder, therefore we will replicate the /ui/ folder structure and only controllers/sidebar.js and views/ads.js will have differences, we will create the following tree: **Sample new bucket filesystem tree** ``` bash> tree ... ├── experiments │ └── new_ad_format │ ├── controllers │ │ └── sidebar.js │ └── views │ └── ads.js ... ``` Note: "experiments" is just an arbitrary name, but “features”, “buckets” or “variations”, etc are good choices as well. **IMPORTANT**: No files that will be exactly the same as the default experience will need to be duplicated. The build process and development server will take care of reusing the files. ### File system variation tree resolution Since the experiments tree should follow exactly the same folder structure as the reference tree, any missing file is used from the default folder. **Schema for filesystem experiments tree resolution** ``` src/ui/ experiments/new_ad_format/ resolved/new_ad_format/ ├── controllers ├── controllers +-+ ├── controllers │ ├── main.js │ │ | │ ├── main.js │ ├── settings.js │ │ | │ ├── settings.js │ └── sidebar.js -----> X│ └── sidebar.js | │ └── sidebar.js ├── main_bindle.js │ | ├── main_bindle.js ├── vendor │ | ├── vendor │ ├── calendar_widget.js │ | │ ├── calendar_widget.js │ ├── ember.js │ | │ ├── ember.js │ ├── jquery.js │ +--> │ ├── jquery.js │ └── react.js │ | │ └── react.js └── views └── views | └── views ├── admin.js │ | ├── admin.js ├── ads.js -------------> X└── ads.js | ├── ads.js ├── list-item.js | ├── list-item.js ├── list.js | ├── list.js ├── login.js | ├── login.js ├── new_item.js | ├── new_item.js └── sidebar_item.js +-+ └── sidebar_item.js ``` Notice that all files that don’t exist on the /experiments/new_ad_format/ folder will be used from the default paths. The /resolved/ tree is not part of the code base, it only exists during runtime. ### Fulfilling the Maintainability goals Let’s go over our Design Principles to understand why this design achieves all the required traits so far. * **Immediately disposable:** Delete the /new_ad_format/ folder and the experiment is gone. * **Upfront costs:** It is possible to write tests against different variations (more on that later on this document). Also conflicts can be detected and solved at development time, as opposed to runtime exceptions and combinations developers forgot, or were time constrained to test * **Mnemonic source-code:** The folder name can be mnemonic (new_ad_format as example above or logo_short below) * **Analyzable:** * There are many folder diff tools available (and we can include some on our build tools) * By spotting the number of files in a folder any developer can have a grasp of how complex this experiment is. ![visualization of development tree and source maps in different browsers](design_0.png) The above image was taken from a real production variation on Yahoo Mobile Search code base (experiment run mid 2015) and developer environment using source maps. Also, there are additional developer benefits of using this pattern. On the developer tools you can open/list all the files that affect the experiment: ![source maps auto completion in chrome based on mnemonic variation name](design_1.png) Also, here is a window comparison viewing default experience (base, or control variation) versus the implementation of a different logo. ![visual outcome of a variation and source maps tree comparison](design_2.png) And here is a diff comparison of one variation to the other. ```diff diff src/client/default/less/searchbox.less src/client/logo_short/less/searchbox.less 7,9c7,9 < @YlogoIconWidth: 0; < @YlogoIconHeight: 0; < @YlogoWidth: @YlogoIconWidth; --- > @YlogoIconWidth: 36px; > @YlogoIconHeight: 36px; > @YlogoWidth: @YlogoIconWidth + 4px; 15a16,26 > .logo { > position: absolute; > background-size: @YlogoIconWidth @YlogoIconHeight; > width: @YlogoIconWidth; > height: @YlogoIconHeight; > background-repeat: no-repeat; > background-image: url('../../client/img/logo.png'); > opacity: 1; > z-index: 1; > user-select:none; > } 149,150c160,161 < 30% { width:@sboxwidth; } < 100% { width:@sboxwidth; } --- > 30% { transform: translateX(0);width:@sboxwidth; } > 100% { transform: translateX(0);width:@sboxwidth; } ``` ### Extra benefits of file system folder based approach Besides or design principles, let’s go over some additional benefits of experiments on a folder: * **Separates complexity:** When understanding a component, source code will not be mixed up with different implementations, and permutations are kept away. * Decreases "fear of a file being complex" as compared to conditionals in the code * Decreases the "this component will be hard to maintain, as there are other combinations already" if we nest files in the same tree * **Composable experiments:** A large new feature might be implemented as a folder, and extra experiments can *inherit *code in a declarative chain. More on that on "Variation Inheritance" later. * **Friendly to developer tools:** Any developer can "grep" the main src/ui/ tree to find uses of a class, get ideas for refactor, and generally reason about the application without dealing with conditionals or duplicated similar files on the same tree. The experiment folder can be hidden in code editor when giving talks and many small quality of life sugar for developers. * **Any filetype:** Conditionals are great for Javascript, but CSS and other files would need extra syntax for creating variations, with the file system approach even JSON configuration can be tweaked per variation * **Predictable combinations:** When dealing with multiple variations, if the same file is used for many experiments, more than one conditional will be introduced and the order they are implemented might not be consistent with other files that also have multiple variations. With file system folders, there is always only one predictable file that will be used. ### Variation Inheritance (or: sharing experiment code) It is very often needed to introduce a new feature as an experiment so we can first measure engagement, fix immediate issues not detected during initial testing, and eventually enable to all users. But it is also becoming a best practice, to test small UI variations of the new feature in order to enable only the optimal version to the user. For example, let's assume our new_ads_format/ example above comes from a new provider and they have a library to fetch ads asynchronously. Our example now is slightly more complex: ``` bash> tree experiments/ experiments/ └── new_ad_format ├── controllers │ ├── more_money.js │ └── sidebar.js ├── vendor │ └── more_money_platform.js └── views └── ads.js ``` If we now want to make slight variations on top of this experiment, we should not need to duplicate again the new controller, the sidebar placement or the vendor library. We should be able for variations to declare only the differences over a main implementation variation. We will only need to duplicate the views/ads.js file across all variations, for that, lets rename the full implementation to "new_ad_format_main": ``` bash> tree experiments/ experiments/ ├── new_ad_format_big │ └── views │ └── ads.js ├── new_ad_format_colorful │ └── views │ └── ads.js ├── new_ad_format_discreet │ └── views │ └── ads.js └── new_ad_format_main ├── controllers │ ├── more_money.js │ └── sidebar.js ├── vendor │ └── more_money_platform.js └── views └── ads.js ``` > Note: This section needs reviewing. This is now covered by .mendelrc file, package.json with "mendel" key or the browserify plugin command-line params. The resolution is unchanged. In order for this to work, we will need to configure the chain of inheritance, which can be done in application level configuration or in a Mendel configuration file, but eventually we want to achieve the following combination: * default (baseline) * new_ad_format_main → default * new_ad_format_big → new ad_format_main → default * new_ad_format_colorful → new ad_format_main → default * new_ad_format_discreet → new ad_format_main → default Tree resolution would work the same way, where all files present on each step of inheritance takes precedence over files on the folder it is inheriting from: ```yaml # Initial design { "new_ad_format_discreet": { folders: ["new_add_format_discreet", "new_ad_format_main", "default"] }, } # .mendelrc implementation: base: default variations: new_ad_format_discreet: - new_add_format_discreet - new_ad_format_main # base is assumed as last item in all variations ``` As explained before, since inheritance order is declared explicitly, there is no inconsistency for resolving which file is being loaded, as opposed to conditionals that can be implemented in different order across different files. A more complex example: ```yaml # as originally designed { "new_ads" { folders: ["new_ads"] }, "sports": { folders: ["sports", "new_news_module", "new_video_module", "new_ads"], }, "news_only": { folders: ["new_news_module", "new_ads"], }, "video_only": { folders: ["new_video_module"], }, "news_and_video": { folders: ["new_news_module", "new_video_module"], }, } # # variations resolution schema: # sports = sports -> new_news_module -> new_video_module -> new_ads -> default # new_news_module = new_news_module -> new_ads -> default # new_video_module = new_video_module -> default # news_and_video = new_news_module -> new_video_module -> default # # .mendelrc format base: default variations: new_ads: - new_ads sports: - sports - new_news_module - new_video_module - new_ads news_only: - new_news_module - new_ads video_only: - new_video_module news_and_video: - new_news_module - new_video_module ``` Notice that news_and_video won't receive new_ads implicitly. This is very important to create complex scenarios, and the above example is a simplification of real use cases that happened in Yahoo Search products before. This is a code sharing pattern intended for developers, it was a consequence of multivariate test requirements that had this complex graph as outcome. ### Comparison to other strategies and designs > Note: This was a bullet list compiled from a series of Q&A sessions internally held at Yahoo. This section is here for historical purposes and will be removed once this design is revised to convey the current architecture in Mendel * conditional in the code * would deliver more code to the client * even conditionals with async loaders would have some more code (including the loader) and then add more requests for scripts/css async. with 20 layers, 20 small files/requests would be required * unmanageable in the long run * not immediately disposable * scary to open 1 file with dozens of conditionals because of buckets * conditional precedence is not predictable and consistent across files, with file system tree merge, it is impossible to have any ambiguity, since even with bucket inheritance, there is no way a developer will be able to change precedence arbitrarily in different files * conditional removal (Esprima or other Javascript parsers and transformations) * same drawbacks as above maintainability wise, but would achieve "no payload overhead" * harder build system to implement * build times increase * it is not easily disposable (unless the same parser/exclusion is used for disposal, but this would increase even more how hard it is to implement) * not easy to analyze differences, since searching the codebase with grep and similar tools is harder with conditionals * lead to implicit precedence per file, where declarative merge/inheritance is consistent (example of if block, some statements execution, followed by another if block) * might be overridden "if(foo) feature2 = true" * branches for each experiment * get outdated for every single commit on master while duplicating files on folders only potentially get outdated for the handful of forked files * which means the cost is not paid upfront, but also maintained over time * can’t be used for server-side, only for client-side (or isomorphic) and code that is required per-request on the server * can diff branches but it’s not easy to grep the codebase and see that a given function is also used on an experiment, among other analysis problems * regular branches would need to be disambiguated with experiment branches, confusion, naming convention, dirty codebase * inheritance problems * cannot have multiple inheritance by declarative configuration, only direct inheritance * if parent branch is rebased, child branch is still outdated or will incur extra development time to update ## Multivariate and Multi Layer Testing When implementing multiple experiments, the most simple and naive approach would be: all tests are mutually exclusive, meaning, a user can only be part of one experiment at a time (or no experiment at all). A more complex approach is to allow permutations of experiments to happen. ### Multivariate > Multivariate testing is a technique for testing a hypothesis in which multiple variables are modified. The goal of multivariate testing is to determine which combination of variations performs the best out of all of the possible combinations. > > [Comparing a Multivariate Test to an A/B Test](https://www.optimizely.com/resources/multivariate-test-vs-ab-test/) There is two approaches for multivariate testing: 1. Build all experiments combinations upfront and allocate users evenly to each experiment 2. Have runtime resolution in order to make possible to allocate users to 2+ different experiments that were developed separately ### Multilayer One of the tools we use at Yahoo to do Multivariate experiments is the use of "Layers". A user is always present in all active layers, and all layers can divide 100% of the users as it sees fit. In the example below, there are two layers and one particular user is assigned to two different experiments, each experiment in one layer. ``` +------------------+-----------------+------------------+ | Bucket L1-A | Bucket L1-B | Bucket L1-C | | 30% of L1 | 30% of L1 | 30% of L1 | Layer 1 +------------------+-----------------+------------------+ +-------------+-------------+-------------+-------------+ | Bucket L2-A | Bucket L2-B | Bucket L2-C | Bucket L2-C | | 25% of L2 | 25% of L2 | 25% of L2 | 25% of L2 | Layer 2 +-------------+-------------+-------------+-------------+ Note: all permutations are possible ``` Layers can be used to create multivariate tests, but at Yahoo this is rarely (or never) the case. **The main goal of implementing layers is to increase experiment space for parallel experimentation.** A secondary goal is to assign different components of a complex application to different teams. This means that the combination of experiments L1B and L2C (or any permutation for that matter) will not be analyzed as the combination being the factor of success, but instead, each variation will usually be compared to it's own control set of users. In Mendel we implement layers because it allows different teams to work on different components, UI areas or responsibilities of the application independently. Multivariate experiments are usually developed on the same layer for measurement accuracy. **Without multi-layer support, all experimentation teams must work together to wisely divide 100% of users into experiments and control groups.** ### Multilayer complexity As we stated before, multilayer support can be used for multivariate testing. One could implement variable A (i.e. button color) and variable B (i.e. button placement) and allocate all variations of each variable in one layer (i.e. Layer 1: A1, A2, A3, A4; Layer 2: B1, B2, B3, B4). Permutation would happen evenly assuming all experiments have the same size. Dynamic allocation for experiments targeting the same subset of components of an application imposes interesting technical challenges: * Are all combinations thoroughly tested? * How to automate such a combination of builds? * How to automate tests? * Is is easy to monitor errors in production? * Does it lead to a chaotic code base in the long run? Multi Layer increases exponentially the number of ****potential errors**** a developer can inadvertently cause in production. It brings Testability and Maintainability issues to the project. With 40 experiments in production, organized in 5 layers there are 6,720 permutations to be accounted for. At built time, it is not practical to run integration/UI tests against 40 experiments (in 3 browsers), let alone the 6,720 permutations. We can add a few specific tests to each isolated experiment, but there is no practical way of automating tests for all permutations. Therefore, most Multi Layer errors are only caught by monitoring production. Thrown programmatic errors are easy to catch and fix, but UI errors are virtually undetectable and costly to fix if they are ever detected. From all the research and design we did before creating Mendel, it becomes clear it's a question to where we want the long term continuous cost to go: 1. We enable Multi Layer, we have higher **development costs** in the long run as we progress, with potential of affecting real users inadvertently, and increasing FE architecture complexity and maintainability significantly. 2. We go back to the ****product management costs***** of having teams competing and organizing to use smaller experiments space. Mendel does not choose for you. If you decide to use Mendel only at build time, it will generate all variations of bundles, you can upload to your CDN and use the bundles as is, with no multi-layer support. If you want to support multi-layering (or an array of variations enabled in production for a single user), you can use mendel-middleware and the exported manifests and server generated files to achieve all the combinations in an isomorphic fashion, while keeping all performance traits discussed above. ## Implementation: Build tools and runtime libraries Mendel is implemented using Browserify. Regardless of recent popularity of WebPack as a front-end build tool, Browserify is still state of the art and provided a stable foundation that is way more modular than WebPack and allowed the team to develop Mendel with high quality standards and in a timely manner. ### Mendel Manifest: Building Front-End assets with thousands of possible permutations in each deployment In previous iterations of this bucket system design, used in the Mobile Search codebase, for each experiment a single client-side bundle was generated. This practice becomes prohibitive for multi-layer scenarios where thousands of permutations are created per deployment (i.e. 40 experiments evenly distributed in 5 layers generate 6.700 permutations). During the **Browserify pipeline**, there is an internal package format that contains source-code and extra metadata. When creating the Mendel manifest, we decided to reuse this representation, wrapped in a Mendel specific object. Here is a simplified manifest: ```json { "indexes": { "components/button.js": 0, ... }, "bundles": [ { "variations": [ "src/base", "src/variations/new_add_button", "sec/variations/new_add_button_red" ], "data": [ { /* browserify payload for base */ }, { /* browserify payload for new_add_button */ }, { /* browserify payload for new_add_button_red */ } ], "id": "components/button.js", "index": 0 }, ... ] } ``` The manifest is generated at build time, and based on entry points for an application, will traverse the dependency graph based on Javascript `import` or `require` statements. All javascript payload is already transformed, and minified at this point. At runtime, the manifest is loaded in memory once, and we are now able to dynamically serve all possible permutations in request time, which we explain in the following sections. ### Mendel Hash - Resolving bundles at runtime Once the manifest is loaded by a production server, Mendel runtime libraries will be able to serve all permutations required for a particular deployment. Our hash algorithm takes caching into consideration. If a small deployment changes only one particular file inside a variation, only a subset of users users should receive a new bundle. All other users should continue to use their cached versions -- even across multiple deployments. Since Mendel is based on file system we can understand the potential bundles and how hashing needs to be done, by analyzing the following scenario: #### 4 experiments, divided in 2 layers, 2 experiments in each layer [![4 experiments in 2 layers graph](https://cdn.rawgit.com/yahoo/mendel/master/docs/Mendel-4-buckets-2-layers.svg)](Mendel-4-buckets-2-layers.svg) The image above can be used to understand a number of Mendel responsibilities. Here are the ones relevant to bundle hashing and caching: 1. With 4 experiments in those layers Mendel can potentially generate 9 bundles. 2. If file `F6` is changed in your application between one version and the other, it should only affects 3 bundles This scenario is easy to understand, but large applications can yield a huge number of variations, for instance, 40 experiments evenly distributed in 8 layers will yield 6.700 permutations. Those permutations are not static at build time. Enabling and disabling permutations, organizing variations into layers are responsibilities of campaign management tools and external systems, so creating all permutations in build time would not only be slow, but also impossible by the nature of A/B testing best practices. Also, in order to cache and serve those bundles, we need consistent URLs: * URLs must be the same to multiple users * URLs must be cookie-less, so we can use CDN caching * URLs should benefit from enhanced security, by obfuscating experiment names * URLs should be small enough For that reason, `mendel-core` generates a hash for each bundle. The hash is based in the file list for a bundle (or what we call a tree representation), and the content of each file. This is very similar to how `git` works internally -- each blob has a hash, and each tree has a hash based on file names and blob hashes -- but it is meant to be evaluated dynamically in production. Using hashes guarantees that we will cache bust only the required bundle on every deployment. It is very common for large applications to split the logic into multiple bundles and also common to do heavy development in variations. This allows developers to use Continuous Integration, Continuous Deployment and Continuous Delivery and rest assured that most users are not getting cache busted constantly. Source code and details on Mendel Hashing is available at: https://github.com/yahoo/mendel/tree/master/packages/mendel-core #### **A) Resolving bundle URL on HTML request:** 1. Request comes in for regular routes (Inbox, Compose, etc) with a bucket-cookie 1. bucket-cookie is an opaque blob, further represented as `[bucket-cookie-hash]` 2. Resolve bucket-cookie to a list of experiments 1. `parse([bucket-cookie-hash]) → ['experimentA', 'experimentB']` 3. Mendel gets an array of experiments, walks the manifest and outputs a hash to be used to generate a URL 1. `mendel(manifest, ['experimentA', 'experimentB']) → [Mendel-hash]` 2. Example mendel hash: `bWVuZGVsAQAA_woAXorelKkTdpi858lasbIQRS6SCfw` 4. Application will have a route to serve this asset (using mendel-middleware): 1. `/mendel/bWVuZGVsAQAA_woAXorelKkTdpi858lasbIQRS6SCfw/main_app.js` 2. On-demand bundles will have similar URLs and a list of potential bundles is served to the user 5. We get a CDN URL to cache this resource and serve in the HTML 1. `cdnFunction(/mendel/bWVuZGVsAQAA_woAXorelKkTdpi858lasbIQRS6SCfw/mail_app.js) → https://your.cdn/some_route/some_hash.js` 2. `<head><script src="https://your.cdn/some_route/some_hash.js” />` 3. `<script>/* on-demand bundles */ var lazyBundles = {…}` 4. `lazyBundles` object contains an map for entry points on the app and URLs like 4.1. above. #### **B) Serving the bundle:** 1. User browser requests CDN url 1. `https://your.cdn/some_route/some_hash.js` 2. CDN fetch contents from Application URL 1. `https://yourapp.com/mendel/bWVuZGVsAQAA_woAXorelKkTdpi858lasbIQRS6SCfw/main_app.js` 3. Mendel uses manifest and hash to generate a list of dependencies for this user 1. `[Mendel-hash] + [Manifest] → [dep1, dep2, dep3, …]` 2. Current implementation gives a `404` if the hash is not a Mendel hash and `404` if the hash don’t match and validates against the current manifest. 4. Mendel packages a bundle for this user 1. `[dep1, dep2, dep3, ...] → [javascript payload]` (with `browser_pack`) 5. CDN gets the response, caches the URL for a period of time (based on headers and how frequently the asset is requested). and serves to any user requesting the same combination of experiments <file_sep>/packages/mendel-config/src/helpers/util.js exports.undash = function undashObject(dashedObj) { return Object.keys(dashedObj).reduce((undashed, key) => { const dashRegexp = /\-([a-z])/i; if (dashRegexp.test(key)) { const newKey = key.replace(dashRegexp, (dash, letter) => { return letter.toUpperCase(); }); undashed[newKey] = dashedObj[key]; } else { undashed[key] = dashedObj[key]; } return undashed; }, {}); }; <file_sep>/packages/mendel-loader/resolver.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ var path = require('path'); var Module = require('module'); var natives = Object.keys(process.binding('natives')).reduce(function(res, name){ res[name] = true; return res; }, {}); var NativeModule = { exists: function(name) { return natives[name] === true; }, require: require, }; function MendelResolver(parentModule, variations, outdir) { if (!(this instanceof MendelResolver)) { return new MendelResolver(parentModule, variations, outdir); } this._parentModule = parentModule || module.parent; this._variations = variations; this._serveroutdir = outdir; this._resolveCache = {}; this._mendelModuleCache = {}; } MendelResolver.prototype.require = function (name) { if (NativeModule.exists(name)) { return NativeModule.require(name); } var that = this; var parent = that._parentModule; var modPath = that.resolve(name); var modExports = that._mendelModuleCache[modPath]; if (modExports) { return modExports; } var mod = Module._cache[modPath]; if (!mod) { mod = new Module(modPath, parent); Module._cache[modPath] = mod; var hadException = true; try { mod.load(mod.id); hadException = false; } finally { if (hadException) { delete Module._cache[modPath]; delete that._resolveCache[name]; } } } modExports = mod.exports; if (modExports.__mendel_module__) { var mendelFn = modExports; var mendelMod = { parent: parent, exports: {}, require: that.require.bind(that), }; // this is the 'incomplete' module to avoid infinite loops on circular dependencies // similar to: https://nodejs.org/api/modules.html#modules_cycles that._mendelModuleCache[modPath] = modExports; mendelFn.apply(that, [mendelMod.require, mendelMod, mendelMod.exports]); modExports = mendelMod.exports; // this is the 'complete' module that._mendelModuleCache[modPath] = modExports; } return modExports; }; MendelResolver.prototype.resolve = function(name) { var parent = this._parentModule; if (!this._resolveCache[name]) { var variation = this._variations[name]; if (variation) { name = path.resolve(path.join(this._serveroutdir, variation, name)); } this._resolveCache[name] = Module._resolveFilename(name, parent); } return this._resolveCache[name]; }; module.exports = MendelResolver; <file_sep>/packages/mendel-deps/test/js-fixtures/es6/index.js import {hi} from './foo'; function foo() { global.console.log(process.env.NODE_ENV); } console.log(hi); <file_sep>/packages/mendel-config/src/shim-config.js const path = require('path'); function ShimConfig({projectRoot, shim, defaultShim}) { const ret = Object.assign({}, defaultShim, shim); Object.keys(ret).forEach(moduleName => { if (!ret[moduleName]) return; ret[moduleName] = path.relative(projectRoot, ret[moduleName]); if (ret[moduleName].indexOf('./') !== 0) ret[moduleName] = './' + ret[moduleName]; }); return ret; } module.exports = ShimConfig; <file_sep>/packages/mendel-pipeline/src/multi-process/protocol.js module.exports = { START: 'start', ERROR: 'error', DONE: 'done', }; <file_sep>/packages/karma-mendel/README.md This is a fork of https://github.com/karma-runner/karma-commonjs/ with modifications to use in mendel projects. <file_sep>/packages/mendel-pipeline/src/step/initialize.js const BaseStep = require('./step'); class Initialize extends BaseStep { /** * @param {MendelCache} toolset.cache */ constructor({cache}) { super(); this.cache = cache; } start() { this.cache.on('entryAdded', id => { // The reason for setImmediate: // There can be a quick succession of adding and source adding // if we pushEntryId right away, it will trigger next steps // literally immediately without having a chance to add the source. setImmediate(() => this.pushEntryId(id)); }); this.cache.entries() .filter(Boolean) .forEach(entry => this.pushEntryId(entry.id)); } pushEntryId(entryId) { this.emit('done', {entryId}); } } module.exports = Initialize; <file_sep>/test/mendel-development-middleware.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ var tap = require('tap'); var sut = require('../packages/mendel-development-middleware'); var express = require('express'); var request = require('request'); var path = require('path'); var async = require('async'); var app = express(); app.use(sut({ basedir: path.join(__dirname, './app-samples/1/'), })); var server = app.listen('1337'); var host = 'http://localhost:1337'; var appBundle = host+'/mendel/app/app.js'; tap.tearDown(function() { server.close(process.exit); }); tap.test('mendel-development-middleware serves a bundle', function(t){ t.plan(2); request(appBundle, function(error, response, body) { if (error) t.bailout(error); t.match(response, { statusCode: 200, headers: { 'content-type': 'application/javascript' }, }, 'serves javascript'); t.contains(body, 'sourceMappingURL=data:application/json;', 'has source maps'); }); }); tap.test('serves cached bundles', function(t) { t.plan(1); function getVendor(done) { request(appBundle, function(error) { done(error); }); } // this would cause test to timeout if cache is disabled var requests = []; for (var i = 0; i < 1000; i++) { requests.push(getVendor); } async.series(requests, function(error) { if (error) t.bailout(error); t.pass('got 1000 of the same bundle'); }); }); <file_sep>/packages/mendel-pipeline/src/entry-proxy.js class EntryProxy { static getFromEntry(entry) { const proxy = new EntryProxy(); proxy.id = entry.id; proxy.filename = entry.id; proxy.normalizedId = entry.normalizedId; proxy.map = entry.istMap; proxy.source = entry.istSource; proxy.deps = entry.istDeps; return proxy; } } module.exports = EntryProxy; <file_sep>/README.md # Mendel Mendel is a framework for building and serving client side JavaScript bundles for A/B testing experiments in web applications. It is meant to be simple and easy to use on a daily basis. It works very well for small applications and small teams, but also scale for complex use cases that large applications or larger teams might need. ##### Example scenario of application A/B testing ``` +-------------------------------------------------------------------------+ | Shopping cart application | +------------------------------+--------------------+---------------------+ | 90% of users | 5% of users | 5% of users | +-------------------------------------------------------------------------+ | Base experience | Experiment A | Experiment B | +-------------------------------------------------------------------------+ | By default cart is a link | Live shopping cart | Live shopping cart | | in the horizontal navigation | as a sidebar | floating and docked | | menu with counter for number | | to the bottom of | | of items | | the page | +------------------------------+--------------------+---------------------+ ``` Mendel supports: * JavaScript bundle generation (similar to Webpack/Browserify) for each variation/experiment/bucket * Isomorphic applications (a.k.a. server side rendering, such as ReactDOMServer or Ember Fastboot) * Multivariate testing and/or Multilayer experimentation * Variation/experiment/bucket inheritance that enables code-reuse across different experiments. Mendel does not support: * Experiment resolution: Mendel does not provide [random assignment](https://en.wikipedia.org/wiki/Random_assignment) of users into experiments * Experiments measurement: Mendel does not provide a way to track performance of experiments based on user actions Both of the above are covered by existing open source tools, such as [PlanOut](http://facebook.github.io/planout/), [Open Web Analytics](http://www.openwebanalytics.com), [Piwik](https://piwik.org) and [many others](https://www.google.com/#q=open+source+web+analytics). ## Advantages of using Mendel Mendel is built on top of solid [design principles](docs/Design.md) and is hardened by years of using the same strategy inside Yahoo, from teams ranging from 3 to 30+ developers contributing daily to large applications. Here are a few of the advantages of using Mendel: * **Maintainability**: All variation/experimentation code is organized and compiled in a way to be immediately disposable, impose no maintenance overhead, and be very easy to debug and analyze. * **Performance**: Server side resolution is synchronous and fast, and client side code will have no payload overhead. * **Security**: Bundle URL and client-side compiled code does not contain variation/experiment information. Only the packages that are absolutely needed are included in the bundle. Mendel also has a clear development flow. All other experimentation we could find lacked built in support for a smooth development workflow. In Mendel, fast development cycles are a first-class citizen. ## How to use Mendel Mendel uses files to create differences for each experiment you want to run for your users. With Mendel you don't create conditionals such as `if(myExperimentRunning) { /* do something different */ }`. You just copy the file you need to be slightly different and change your code. For example, let's say your application has a `controllers` directory and a `views` directory, and for a given experiment you will change how display ads are rendered. You then create the following structure **in addition** to your application code. ``` bash> tree ... ├── experiments │ └── new_ad_format │ ├── controllers │ │ └── sidebar.js │ └── views │ └── ads.js ... ``` Next, you add the experiment to your configuration. Each experiment is called a "variation" in Mendel, and each variation is a list of folders. Here is the newly added `new_ad_format` variation: ```yaml variationsdir: experiments variations: new_ad_on_sidebar: ## experiment id is inferred from this key - new_ad_format ## directory name (if not same as id) ``` That's it, with two simple steps, you now have have an experiment ready to run. The default code is usually called `base` and does not need to be declared. Mendel will then generate bundles for each of your variations. ### File system resolution To understand which files you need to create is very straightforward. Mendel just merges the directory tree in runtime. **The resulting tree is not written to disk**, but the following diagram explains how your files will be combined for a given experiment: ``` Bundle "base" Bundle "new_add_format" ^ ^ | resolution direction | | -----------------------------------------> | src/ experiments/new_ad_format/ resolved/new_ad_format/ ├── controllers ├── controllers ├── controllers │ ├── main.js │ │ │ ├── main.js │ ├── settings.js │ │ │ ├── settings.js │ └── sidebar.js -----> X│ └── sidebar.js ------------>└── sidebar.js ** ├── main_bindle.js │ ├── main_bindle.js ├── vendor │ ├── vendor │ ├── calendar.js │ │ ├── calendar.js │ ├── ember.js │ │ ├── ember.js │ ├── jquery.js │ │ ├── jquery.js │ └── react.js │ │ └── react.js └── views └── views └── views ├── admin.js │ ├── admin.js ├── ads.js -------------> X└── ads.js ---------------->├── ads.js ** ├── list-item.js ├── list-item.js ├── list.js ├── list.js ├── login.js ├── login.js ├── new_item.js ├── new_item.js └── sidebar_item.js └── sidebar_item.js ** Files marked with ** in the "resolved" tree are used from the "experiments/new_ad_format/" tree, all other files are used from "src/" tree. ``` ## Stability and Roadmap The way Mendel experiments are built has been quite stable since mid 2014, and Mendel implementation just improves how it is compiled and adds several features, like multi-layer. Mendel 1.x can be considered stable and is used by production applications at Yahoo. We are also [building Mendel 2.x](docs/Roadmap.md), in which experiment/variations creation will be exactly the same, production middleware API is also considered stable and only file configuration format and development middleware will have breaking changes in 2.0. Since documentation is still short of ideal, we recommend you start with the "examples" directory. It is a sample application and there is a [small Readme file](examples/README.md) to get you started. ## Why is is Mendel so different? Mendel is the result of extensive research done by Yahoo on how to achieve not only the aforementioned performance goals, but also on how to effectively address development across large teams. We found that conditionals in the code base resulted in experiments which were hard to dispose of after they had run their course, which led to [technical debt](https://en.wikipedia.org/wiki/Technical_debt) and poor performance in our code bases. The main goal for Mendel is to be sustainable. Sustainability comes from being able to test the experiments correctly, keeping experiments up-to-date with our "base/master/default" application code, and keeping front-end performance unchanged throughout experimentation and adoption of experiment results. There is a full [design document](docs/Design.md) available if you are curious about the details. ## Why is it called "Mendel"? [Gregor Mendel](https://en.wikipedia.org/wiki/Gregor_Mendel) is considered one of the pioneers in genetics. His famous experiments include identifying phenotypes such as seed shape, flower color, seed coat tint, pod shape, unripe pod color, flower location, and plant height on different breeds of pea plants. We find that in many ways, we are doing similar experiments with our software applications. We want to know what "application phenotypes" will be most fitting for the relationship between our products and our users, hence the homage to Gregor Mendel. ### Developing Mendel and Contributions Mendel is a monorepo. In order to develop for Mendel you will need to create a lot of `npm link`s. To make it easier, we created a small script. You can run `npm run linkall` to link all packages to your node installation and cross-link all Mendel packages that depend on each other. This will also run `npm install` in all places that you need to. Mendel follows Browserify's plugin pattern and NPM small packages style. Whitespace conventions are on `.editorconfig` file, please use [editor config plugin for your code editor](http://editorconfig.org). We also have some [test documentation](docs/Tests.md) in case you want to make a pull request. ## License Mendel is [MIT licensed](LICENSE). <file_sep>/packages/mendel-pipeline/src/multi-process/base-master.js const analyticsCollector = require('../helpers/analytics/analytics-collector'); const analyzeIpc = require('../helpers/analytics/analytics')('ipc'); const {fork} = require('child_process'); const debug = require('debug'); const RECOMMENDED_CPUS = require('os').cpus().length; const Protocol = require('./protocol'); const path = require('path'); // Deallocate unused child process after 10 seconds. const CHILD_PROCESS_DEALLOC_PERIOD = 7.5e3; class BaseMasterProcess { static get Protocol() { return Protocol; } constructor(workerFileName, options={}) { this._name = options.name || 'unamed_multi_process'; this._workerArgs = [this._name, workerFileName] .concat(options.workerArgs); this._maxChildCount = options.numWorker || RECOMMENDED_CPUS; // Queues this._workers = new Map(); this._idleWorkers = []; this._jobs = []; // Get Listeners from subclass this._subscribers = this.subscribe(); // debug related this._debug = debug(`mendel:${this._name}:master`); } _exit() { this._workers.forEach(({process}) => this.dealloc(process)); } canAlloc() { return this._workers.size < this._maxChildCount; } alloc() { const child = fork(path.join(__dirname, 'worker.js'), this._workerArgs); const {pid} = child; analyticsCollector.connectProcess(child); child.once('error', () => { console.error('[ERROR] Worker process unexpectedly exited.'); this.dealloc(child); }); this._workers.set(pid, { process: child, timer: this._setChildTTL(child), }); this._idleWorkers.push(pid); this._debug(`[${this._name}:${pid}] alloced`); } _setChildTTL(child) { return setTimeout( () => this.dealloc(child), CHILD_PROCESS_DEALLOC_PERIOD ); } dealloc(child) { if (child.connected) { child.send({ type: Protocol.DONE, args: {}, }); child.kill(); } const {pid} = child; this._workers.delete(pid); this._idleWorkers.splice(this._idleWorkers.indexOf(pid), 1); this._debug(`[${this._name}:${pid}] dealloced`); } getIdleProcess() { const workerId = this._idleWorkers.shift(); const desc = this._workers.get(workerId); clearTimeout(desc.timer); desc.timer = this._setChildTTL(desc.process); return desc.process; } onExit() { this._exit(); } onForceExit() { this._exit(); } subscribe() { throw new Error( 'Required "subscribe" method is not implemented for ' + this.constructor.name ); } dispatchJob(args) { setImmediate(() => this._next()); return new Promise((resolve, reject) => { this._jobs.push({ args, promise: {resolve, reject}, }); }); } sendAll(type, args) { this._workers.forEach(worker => worker.send({type, args})); } _next() { if (!this._jobs.length) return; if (!this._idleWorkers.length) { if (this.canAlloc()) { this.alloc(); setImmediate(() => this._next()); } return; } const self = this; const {args, promise} = this._jobs.shift(); const worker = this.getIdleProcess(); worker.on('message', function onMessage({type, message}) { setImmediate(() => self._next()); if (type === Protocol.ERROR || type === Protocol.DONE) { // No longer needed worker.removeListener('message', onMessage); self._idleWorkers.push(worker.pid); } if (type === Protocol.ERROR) { promise.reject(message); } else if (type === Protocol.DONE) { promise.resolve(message); } else { if (!self._subscribers[type]) return; self._subscribers[type](message, (type, sendArg) => { analyzeIpc.tic(this._name); worker.send({ type, args: sendArg, }); analyzeIpc.toc(this._name); }); } }); analyzeIpc.tic(this._name); worker.send({ type: Protocol.START, // entry properties args, }); analyzeIpc.toc(this._name); setImmediate(() => this._next()); } } module.exports = BaseMasterProcess; <file_sep>/packages/mendel-outlet-server-side-render/transform-require.js const path = require('path'); const falafel = require('falafel'); const wrapper = [ 'module.exports = function(__mendel_require__, module, exports) {\n', '\n};\nmodule.exports.__mendel_module__ = true;\n', ]; function _wrap(src) { return wrapper[0] + src + wrapper[1]; } function isRequire(node) { var c = node.callee; return c && node.type === 'CallExpression' && c.type === 'Identifier' && c.name === 'require' && node.arguments[0] && node.arguments[0].type === 'Literal'; } // isAbsolutePath copied from browserify MIT licenced source code function isAbsolutePath(file) { var regexp = process.platform === 'win32' ? /^\w:/ : /^\//; return regexp.test(file); } function isNonNpmModule(file) { return /^\.{1,2}\//.test(file); } function replaceRequiresOnSource(destinationPath, entry, getDepPath) { const opts = { allowReturnOutsideFunction: true, }; const _src = falafel(entry.source, opts, function(node) { if (isRequire(node)) { var module = node.arguments[0].value; if (isAbsolutePath(module)) { node.update( "require('" + path.relative(path.dirname(destinationPath), module) + "')" ); } else if (isNonNpmModule(module)) { module = getDepPath(entry, module); node.update(`__mendel_require__('${module}')`); } } }).toString(); return _wrap(_src); } module.exports = replaceRequiresOnSource; module.exports.wrapper = wrapper; module.exports.wrap = _wrap; <file_sep>/packages/mendel-development-middleware/index.js const pathToRegExp = require('path-to-regexp'); const parseConfig = require('mendel-config'); const resolveVariations = require('mendel-development/resolve-variations'); const MendelClient = require('mendel-pipeline/client'); const Stream = require('stream'); const {execWithRegistry} = require('mendel-exec'); const path = require('path'); module.exports = MendelMiddleware; function MendelMiddleware(opts) { const client = new MendelClient(Object.assign({}, opts, {noout: true})); client.run(); const config = parseConfig(opts); const {variations: varsConfig} = config.variationConfig; const route = config.routeConfig.variation || '/mendel/:variations/:bundle'; const getPath = pathToRegExp.compile(route); const keys = []; // Populates the key with name of the path variables // i.e., "variations", "bundle" const bundleRoute = pathToRegExp(route, keys); const bundles = new Set(); config.bundles.forEach(bundle => bundles.add(bundle.id)); return function(req, res, next) { req.mendel = req.mendel || {variations: false}; req.mendel.getBundleEntries = function getBundleEntries(bundleId) { const bundleConfig = config.bundles.find(({id}) => id === bundleId); if (!bundleConfig) throw new Error(`No bundle with id ${bundleId} found`); // Without bundling yet, we need to get normalizedIds of entries/entrances const normIds = new Set(); client.registry.getEntriesByGlob(bundleConfig.entries || []) .forEach(entry => normIds.add(entry.normalizedId)); return Array.from(normIds.keys()); }; req.mendel.setVariations = function setVariations(variations) { // You can set variation only once if (req.mendel.variations === false) { let validVars = variations.filter(variation => { return varsConfig.some(({id}) => id === variation); }); if (config.verbose && validVars.length !== variations.length) { console.log([ `[WARN] Certain variations in ${variations}`, 'does not exist. Defaulted to base variation.', ].join(' ')); } if (!validVars.length) { validVars = [config.baseConfig.id]; } req.mendel.variations = validVars; } else { console.error('You cannot set variation more than once per request'); //eslint-disable-line max-len } return req.mendel.variations; }; req.mendel.getURL = function getURL(bundleId) { const variations = req.mendel.variations.join(',') || config.baseConfig.id; return getPath({bundle: bundleId, variations}); }; req.mendel.resolver = function(bundles, variations) { return { require: function mendelRequire(entryId) { variations = variations || req.mendel.variations || [config.baseConfig.dir]; return execWithRegistry( client.registry, entryId, variations.map(variation => { return varsConfig.find(({id}) => id === variation); }).filter(Boolean) ); }, }; }; req.mendel.isSsrReady = () => client.isSynced(); // Match bundle route const reqParams = bundleRoute.exec(req.url); // If it is not a bundle route, move on to next so application // can do SSR or whatever if (!reqParams) return next(); // This is a bundle route. Return a bundle and end const params = namedParams(keys, reqParams); const bundle = params.bundle ? path.parse(params.bundle).name : ''; if (!bundle || !bundles.has(bundle)) return next(); const vars = resolveVariations( varsConfig, // %2C is comma done in getURL above (params.variations || []).split(/(,|%2C)/i) ); // If params.variations does not exist or it does not resolve to // proper chain. if (!vars.length) return next(); // Serve bundle // req.accepts cannot be used since JS request accepts "*.*" if (req.headers.accept.indexOf('text/css') >= 0) { res.header('content-type', 'text/css'); } else { res.header('content-type', 'application/javascript'); } client.build(bundle, vars) .then(bundle => { if (bundle instanceof Stream) return bundle.pipe(res); else if (typeof bundle === 'string') return res.send(bundle).end(); console.error( 'Build is imcompatible with middleware.', 'Bundle: "' + bundle + '"', 'Output is: ' + typeof bundle ); res.status(500) .send('console.error("Error compiling client bundle. Please check Mendel output")') // eslint-disable-line max-len .end(); }) .catch(e => { console.error(e.stack); res.status(500) .send('console.error("Error compiling client bundle",' + JSON.stringify({stack: e.stack}, null, 2) + ')') // eslint-disable-line max-len .end(); }); }; } function namedParams(keys, reqParams) { return keys.reduce((params, param, index) => { params[param.name] = reqParams[index + 1]; return params; }, {}); } <file_sep>/packages/mendel-config/src/helpers/resolve-plugin.js var nodeResolveSync = require('resolve').sync; var path = require('path'); function resolvePlugin({plugin, basedir}, packageResolver=noop) { const pluginPackagePath = _resolve(path.join(plugin, 'package.json'), { basedir, }); const pluginPath = _resolve(plugin, {basedir}); const resolved = { plugin: pluginPath, }; [pluginPackagePath, pluginPath].forEach(path => { try { const packageOrModule = require(path); packageResolver(resolved, packageOrModule); } catch (e) { // Nice try, but we don't need to do anything yet // ¯\_(ツ)_/¯ } }); return resolved; } function noop() {} function modeResolver(resolved, packageOrModule) { if (resolved.mode) return; resolved.mode = packageOrModule.mode || 'ist'; } function _resolve(pluginPath, opt) { try { return nodeResolveSync(pluginPath, opt); } catch (e) { return false; } } module.exports = resolvePlugin; module.exports.modeResolver = modeResolver; <file_sep>/test/app-samples/2/src/base/get_late.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ function getter() { return require('./late.js'); } if (module.parent) { module.exports = function(callback) { setTimeout(function() { callback(getter()()); }, 10); }; } else { var ajaxLib = require('prentent-this-is-an-ajax-lib'); module.exports = function() { ajaxLib(getter); }; } <file_sep>/packages/mendel-pipeline/src/step/fs-reader/index.js const BaseStep = require('../step'); const path = require('path'); const fs = require('fs'); const analytics = require('../../helpers/analytics/analytics')('fs'); const debugError = require('debug')('mendel:reader:error'); class FileReader extends BaseStep { constructor({registry, depsResolver}, {projectRoot, types}) { super(); this.depsResolver = depsResolver; this.projectRoot = projectRoot; this.registry = registry; this._types = types; this.sourceExt = new Set(); } perform(entry) { // raw can exist without read step in case of virtual files and others. if (entry.rawSource) return this.emit('done', {entryId: entry.id}); const filePath = path.resolve(this.projectRoot, entry.id); const {type} = entry; const {isBinary} = (this._types.get(type) || {isBinary: true}); analytics.tic('read'); fs.readFile(filePath, isBinary ? 'binary' : 'utf8', (error, source) => { analytics.toc('read'); if (error) { console.error([ `[CRITICAL] while reading "${filePath}".`, ].join(' ')); debugError(`Error message for ${filePath}: ${error.stack}`); // We need to exit in such case.. process.exit(1); } this.registry.addSource({id: entry.id, source, deps: {}}); this.emit('done', {entryId: entry.id}); }); } } module.exports = FileReader; <file_sep>/packages/mendel-pipeline/src/helpers/analytics/analytics.js class Analytics { constructor(groupName) { this.groupName = groupName; this.dataMap = new Map(); } tic(name, value) { name = name || '-'; this.dataMap.set(name, Date.now()); return value; } toc(name, value) { name = name || '-'; // Needs to no-op if there were tic before if (!this.dataMap.has(name)) return; const before = this.dataMap.get(name, Date.now()); const after = Date.now(); this.record(name, before, after); return value; } record(name, before, after) { // Analytics cannot be done without a collector if (!global.analytics) return; global.analytics.record({ type: 'analytics', name: `main:${this.groupName}:${name}`, before, after, }); } } module.exports = function(name) { return new Analytics(name); }; module.exports.constructor = Analytics; <file_sep>/test/tree-serializer.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ var t = require('tap'); var TreeSerialiser = require('../packages/mendel-core/tree-serialiser'); var sut = TreeSerialiser(); t.equal(sut.constructor, TreeSerialiser, 'correct constructor'); sut = createPredictable(); sut.pushBranch(2); sut.pushFileHash(new Buffer('f8968ed58fa6f771df78e0be89be5a97c5d3fb59', 'hex')); var expected = 'bWVuZGVsAQAC_wIACwymnXS-hyyRSwbove5neRfo6fI'; t.equal(sut.result(), expected, 'Hash matches'); t.equal(sut.result(), expected, 'Can call result multiple times'); t.throws( function() { sut._metadata(); }, 'Can\'t re-init _metadata'); t.throws( function() { sut.pushBranch(1); }, 'Throws if pushBranch after result'); t.throws( function() { sut.pushFileHash( new Buffer('f790b83d19df02e79d50eeb84590a32b966f8e13', 'hex')); }, 'Throws if pushFileHash after result'); function createPredictable() { var sut = new TreeSerialiser(); sut.pushBranch(0); sut.pushFileHash( new Buffer('6310b41adf425242c338afc1d5f4fbf99cdccf47', 'hex') ); return sut; } sut = createPredictable(); var bogus = createPredictable(); bogus.pushFileHash('not a Buffer'); t.equal(sut.result(), bogus.result(), 'Don\'t pushFileHash if it\'s not a Buffer'); var sut1 = createPredictable(); var sut2 = createPredictable(); sut1.pushBranch(1); sut2.pushBranch(1); sut1.pushFileHash(new Buffer('f790b83d19df02e79d50eeb84590a32b966f8e13','hex')); sut2.pushFileHash(new Buffer('f790b83d19df02e79d50eeb84590a32b966f8e13','hex')); t.equal(sut1.result(), sut2.result(), 'Consistent result if same files pushed'); sut1 = createPredictable(); sut2 = createPredictable(); sut1.pushBranch(1); sut2.pushBranch(1); sut1.pushFileHash(new Buffer('f790b83d19df02e79d50eeb84590a32b966f8e13','hex')); sut2.pushFileHash(new Buffer('b84590a32b966f8e13f790b83d19df02e79d50ee','hex')); t.notEqual(sut1.result(), sut2.result(), 'different result if different hahses pushed'); <file_sep>/test/manifest-extract.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ var test = require('tap').test; var fs = require('fs'); var path = require('path'); var tmp = require('tmp'); // Since this file re-writes stuff, lets work on a copy var realSamples = path.join(__dirname, './manifest-samples/'); var copySamples = tmp.dirSync().name; var postProcessManifests = require( 'mendel-development/post-process-manifest'); var extract = require('../packages/mendel-manifest-extract-bundles'); test('postProcessManifests applying post-processors', function (t) { copyRecursiveSync(realSamples, copySamples); t.plan(4); postProcessManifests({ // verbose: true, // remember to use this for debug manifestProcessors:[ [extract, { from: 'bad-sort', external: 'foo-is-children', }], ], outdir: copySamples, bundles: [{ // just re-using, important part is that are some files there bundleName: 'bad-sort', manifest: 'bad-sort.manifest.json', }, { bundleName: 'foo-is-children', manifest: 'foo-is-children.manifest.json', }], }, function(error) { t.error(error); var resultFrom = require( path.join(copySamples, 'bad-sort.manifest.json')); var resultExternal = require( path.join(copySamples, 'foo-is-children.manifest.json')); t.equals(resultExternal.bundles.length, 2, 'removed external bundles'); t.equals(resultFrom.bundles[1].expose, 'foo', 'exposed bundle'); t.equals(resultFrom.bundles[1].data[0].expose, 'foo', 'exposed variation'); }); }); function copyRecursiveSync(src, dest) { var exists = fs.existsSync(src); var stats = exists && fs.statSync(src); var isDirectory = exists && stats.isDirectory(); if (exists && isDirectory) { try{fs.mkdirSync(dest);} catch(e) {/**/} fs.readdirSync(src).forEach(function(childItemName) { copyRecursiveSync(path.join(src, childItemName), path.join(dest, childItemName)); }); } else { fs.writeFileSync(dest, fs.readFileSync(src)); } } <file_sep>/packages/mendel-pipeline/src/client/build-all.js const BaseClient = require('./base-client'); const Bundle = require('../bundles/bundle'); class BuildAll extends BaseClient { onSync() { const bundles = this.config.bundles.map(opts => new Bundle(opts)); Promise.resolve() .then(() => this.generators.performAll(bundles)) .then(bundles => this.outlets.perform(bundles)) .then(() => this.emit('done')) .catch(e => this.emit('error', e)); } } module.exports = BuildAll; <file_sep>/packages/mendel-pipeline/docs/DEVELOPMENT-README.md # Mendel v2 developer documentation In this version, Mendel became a build system instead of being a plugin to a bundler that happened to build. The highlights are: - Variation or A/B testing is a first class citizen - Utilize multiple cores for speed - Pluggable: transformer, dependency graph mutator (generator), and build output ## Introduction ![Architecture Image](./diagram.png) Mendelv2 introduces new architecture that optimizes in preventing redundant operations and leverages parallelism of independent tasks. Moreover, in the new architecture, we ensure there is no chain reaction when a file changes which can happen to, often, Grunt-based system where filesystem is a mode of integrating different build systems. The largest benefit of the new architecture comes from the daemon/client design. Because large portion of transformations can be reused for different outputs, the daemon contains bank of caches where files after heavy transformations are stored. Clients, then, can choose any bundling strategy or even opt to execute out of replica of an instance of a cache. In this document, we will take bottom-up approach where we discuss building blocks first then tie them together later. ## Building blocks ### Entry An entry is a primary unit of Mendel that maps 1-to-1 to every file in a source directory. It contains information like source, file path, dependencies, and other metadata. An entry only holds a single version of a source and its dependencies, which creates interesting restrictions. Depending on which bundle requires an entry, an entry may need different set of transforms done which can yield wildly different source (imagine minification that also removes `require` statements). However, it was found from Mendel v1 that configuration varying bundles are mostly needed for different environment/context which will be further discussed in the __Environment__ section below. ### Type A type is an abstraction on top of entry and an entry always belongs to a type based on user’s configuration. A type of entry determines which transforms will be done, how a type will translate to another type, and how an entry will be outputted at the end. ### Environment Environment, or more specifically `MENDEL_ENV`, is the most important environment variable for users of Mendel. The invariable configuration restriction for entry transformations can be cumbersome. For a JavaScript entry, one may want to instrument for testing and minify or remove development-related code for production. In order to support such use case, entry needs to either store different versions of transformed source, which may widely differ by transform applied (order of same set of transforms also impacts how code generates), or have to create different entries when transforms differ. Mendel chose the latter approach and implemented it by having storage for entries (called "cache") *per environment*. Using environment, you can change: - transform configuration - outlet configuration - TODO; there are others. ### Pipeline Most bundlers have variants of pipeline (needs citation). Mendel's pipeline operates in largely two modes: per-entry and all-entries. All files found in source directory are added to the pipeline. Without concerning others, each file creates an entry, populates metadata, and transforms according to their respective types. Along each step of the pipeline, when source is altered, dependencies of an entry are detected. When a dependency outside of the source directory is found, the new dependency is added to the pipeline dynamically and continues recursively. It is important to note that an entry _cannot step backwards_ in the pipeline but it _can add more entries to the pipeline_. When a pipeline step starts to concern graph of dependencies, it must wait for all entries to be ready with all the respective transformations done (this is important as a transformation can add/remove dependencies and mutate the dependency graph). From this point on, all entries are considered as a unit and move together in the pipeline. ## Pipeline Steps FileReader<sup>\*</sup> → IST<sup>\*</sup> → GST<sup>\*</sup> → Generator → Outlet (\* denotes steps that does dependency resolver at the end) ### Independent Source Transform An Independent Source Transform (IST) is a transform that does not take any other source into account when transforming, and most source transforms fall into this category. For instance, when transforming ES2016 source code into ES5 compatible code, it is simply done by parsing the Abstract Syntax Tree (AST) and doing transformation on the tree; the most popular tool at the moment is [babel-preset-es2016](https://babeljs.io/docs/plugins/preset-es2016/). Do note that IST does not have to be confined to [babel](https://babeljs.io/) or, as a matter of fact, JavaScript. A special type of IST is a parser. Parser is a source transform that mutates an entry's type from one to another. For example, SASS compiler transforms a SASS type to a CSS type. When parser exists for a type, IST first transforms from an originating type, then parses, and, finally, transforms for a destination type. ### Graph Source Transform ``` transformedEntrySource = IST(entry); [transformedEntrySource, virtualEntry] = GST(entry, dep_1, dep_2, dep_1_1, ...); ``` Graph Source Transform (GST) differs from IST in its input: it not only takes an entry, but also its dependencies. Without concerning variations, conceptually, this is trivial. However, complexity increases rapidly when multiple variations exist in its dependencies and their sub-dependencies. Since a different set of dependencies and sub-dependencies can result in different source, GST has to explore multiple combinations of variations (combination because the order of variation dictates the order of variational resolution). Moreover, those combinational transform results have to be stored for correct resolution, which will be discussed more in depth later. As of January of 2017, to avoid complexity, GST does not concern with all combination of variations but only a combination of a variation and a base variation. ### Generators Generator is a step that understands the concept of bundle (output) and graph of dependencies. To describe this in more jovial words, let's imagine being in a grocery store. Every entry transformation up-to this step is now up for grab in shelves, and bundles are shopping carts. It is the job of the generators to walk the dependency graph (with a helper method) and collect entries from the shelves. However, unlike grocery shopping in real life, hopefully, generators are allowed to peek into others' shopping cart and claim entries as his/hers! It is possible to do interesting operations when this is allowed. For example, `mendel-generator-node-modules` peeks into other bundles, and grabs every entry that is an npm package and is part of the application, and creates a separate bundle. This technique is favorable since, unless dependencies change often, the node_modules bundle is highly cacheable. ## Putting things together ### Daemon As mentioned in earlier section, in a given environment or a given context, it is unlikely that one wants different set of transformations operated on an entry. The assumption allows entry to be highly reusable that Mendel has created a common cache multiple bundles can use. Mendel Daemon is process that performs such highly reusable operations and holds caches (caches are where entries are stored) for all environments. More specifically, Daemon process watches file systems, reads, transforms (IST and GST), and resolves dependencies. One important aspect of Mendel daemon is its pipeline. Unlike other pipeline implementations, Mendel’s pipeline allows entries to move independent of other entries unidirectionally -- when an entry is created, it goes through reader, IST, and GST in order. An entry, while moving through the pipeline, can add other entries in its dependency graph and those entries will start from the beginning. Although daemon greatly benefits from the independence, it cannot be leveraged when operation involves dependency graphs of entries. As a result, starting from Graph source transform (GST), Mendel expects necessary transformations to have been done to all entries. It is true that GSTs are generally done on subset of entries and Mendel requires sub-depgraph to have been done, a GST can mutate dependency which impacts next GSTs that Mendel willfully avoided such implementation. ### Client Mendel Client runs in separate process and is used when one tries to accomplish a task based on transformed entries. Few examples of the tasks are generation of JavaScript bundle or executing test. Based on environment variable and context, a client connects to daemon process using socket (can be replaced with WebSocket; Mendel is network agnostic) and syncs with a cache. Upon sync, a client performs generator and outlet which generates bundles (or grouping of entries) and outputs the bundles, respectively. ## Advanced Topic ### normalizedId ##### Simple case ```js require('./foo/bar'); // resolves to // related, `node-resolve`: https://github.com/substack/node-resolve // related, `browser-resolve`: https://github.com/defunctzombie/node-browser-resolve './foo/bar/index.js' './foo/bar/index.es6' './foo/bar.js' './foo/bar/randomDir/randomMain.js' // in case of package.json's `main` property './foo/bar/randomDir/randomBrowser.js' // in case of package.json's `browser` property ``` ##### Variational case ```js require('./foo/bar'); // resolves to './src/baseVarDir/foo/bar/index.js' './src/baseVarDir/foo/bar.js' './src/baseVarDir/foo/bar/randomDir/randomMain.js' './src/baseVarDir/foo/bar/randomDir/randomBrowser.js' './src/varDirs/var1/foo/bar/index.js' './src/varDirs/var1/foo/bar.js' './src/varDirs/var1/foo/bar/randomDir/randomMain.js' './src/varDirs/var1/foo/bar/randomDir/randomBrowser.js' ``` Amongst these combinations, it is possible for source code to have below like directory structure: ``` src ├── baseVarDir │ └── foo │ └── bar │ └── index.js └── varDirs/var1 ("varDirs/var1" collapsed for visual ease) └── foo └── bar.js ``` For every variation, `require('./foo/bar')` will resolves to very different file which can cause cognitive overhead and very buggy code. If you thought above was not too hard, below should be more complex: ``` src ├── baseVarDir │ ├── dep.js │ └── index.js └── varDirs ├── var1 │ └── index.js │ └── dep.js └── var2 └── dep └── package.json └── moreDir/.../whatever.js # index.js depends on dep.js ``` In single variational case, above is easy. Dependency resolving as follows: - base: src/baseVarDir/index.js → src/baseVarDir/dep.js - var1: src/varDirs/var1/index.js → src/varDirs/var1/dep.js - var2: src/baseVarDir/index.js → src/varDirs/var2/dep/moreDir/.../whatever.js However, if you imagine multivariate variation, it becomes: - var2,var1: <font color=red>conflict</font> src/varDirs/var1/index.js → src/varDirs/var2/dep/moreDir/.../whatever.js Above ambiguity is called a "conflict" as it is virtually impossible for variation developer to conceive or account for all combinations to be correct and safe. A `normalizedId` is generated by stripping out extension, file name "index", and inspecting package.json pointers. The example folder structure will have following normalizedIds: ``` src ├── baseVarDir │ ├── dep.js -> ./dep │ └── index.js -> ./ └── varDirs ├── var1 │ └── index.js -> ./ │ └── dep.js -> ./dep └── var2 └── dep └── package.json ``` This allows Mendel to group entries that is possible to be `require`d by the same literal (this also imposes restriction to the file names in a codebase; more on this later) and it allows us to catch conflicts while resolving whose algorithm is depicted in pseudocode below. ```js var entries = getEntriesByNormalizedId(normId); assert(entries, [Entry_var1, Entry_var2]) // conflict assert(entries, [Entry_var1]) // not a conflict ``` ## Virtual Entries TBD # Package structure ## Core packages - **mendel-resolver**: Although default resolve is wonderful, it lacks for two features -- it lacks “browser” property support which is covered by another package but also misses variational support. In variational world, how modules get resolved needs to look into variational directory - **mendel-deps**: AST parse a source to detect ES6 import and CommonJS require and do variational resolve their path. ## Others - **mendel-transform-babel**: IST for babel - **mendel-transform-less**: IST for LESS - **mendel-generator-node-modules**: Extracts node_modules from bundles and create separate node_modules bundle. - **mendel-generator-extract**: Allows you to code split by declaring which paths need to be bundled separately away from designated bundle. The technique is widely known as code-splitting. - **mendel-outlet-css**: Outputs CSS based on glob of entry ids defined in configuration # Appendix ## Glossary - Source: Any form of source including JS, CSS, binary file, images, and etc… - Daemon: Long-running process that watches file-system and do computation intensive transformations - Clients: Often, short lived process that consumes transformed entries to do something useful with them - Independent Source Transform (IST): transforms that can be done without considering any other source - Graph Source Transform (GST): transforms that must be done with other entries - Generator: Bundle collection step. Grabs entries into a “basket” - Outlet: Outputs a bundle created by a generator. I.e., mendel-outlet-browser-pack - Runtime: Place where code will execute. Currently, node or browser. This concept is used in modules where, in package.json, one declares “main” and “browser” property. <file_sep>/packages/mendel-outlet-browser-pack/script.js var bp = require('browser-pack'); const pack = bp({raw: true}); pack.write( { "id": "a1b5af78", "source": "console.log(require('./foo')(5))", "deps": { "./foo": "b8f69fa5" }, "entry": true } ); pack.write( { "id": "b8f69fa5", "source": "module.exports = function (n) { return n * 111 }", "deps": {} } ); pack.end(); pack.on('data', (buf) => console.log(buf.toString())); <file_sep>/packages/mendel-transform-babel/README.md # mendel-transform-babel Mendel transforms that uses babel-core ## API WIP <file_sep>/test/app-samples/1/app/number-list.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ var oneNumber = require('./some-number'); module.exports = function() { var a = [oneNumber()]; return Array.isArray(a) ? a : []; }; <file_sep>/packages/mendel-pipeline/src/step/ist/defaults-js/global/index.js const TransformBabel = require('mendel-transform-babel'); const path = require('path'); function transform(src, options) { options = Object.assign({}, options, { plugins: [path.resolve(__dirname, 'transform.js')], }); return TransformBabel(src, options); } const config = { id: '_mendel_internal-global', options: {}, plugin: __filename, mode: 'ist', exec: 'js', }; module.exports = transform; module.exports.config = config; <file_sep>/packages/mendel-exec/index.js const vm = require('vm'); const path = require('path'); const m = require('module'); const resolve = require('resolve'); // https://github.com/nodejs/node/blob/master/lib/internal/module.js#L54-L60 const builtinLibs = Object.keys(process.binding('natives')); const _require = require; const errorMapper = require('./source-mapper'); function runEntryInVM(filename, source, sandbox, require) { if (require.cache[filename]) { return require.cache[filename].exports; } const exports = {}; const module = {exports}; // Put the cache first so if return something even in the case when // cycle of dependencies happen. require.cache[filename] = module; // the filename is only necessary for uncaught exception reports to point to the right file try { const unshebangedSource = source.replace(/^#!.*\n/, ''); const nodeSource = vm.runInContext( m.wrap(unshebangedSource), sandbox, {filename} ); // function (exports, require, module, __filename, __dirname) nodeSource( exports, require.bind(null, filename), module, filename, path.dirname(filename) ); } catch (e) { delete require.cache[filename]; throw e; } return module.exports; } function matchVar(norm, entries, variations, runtime) { // variations are variation configurations based on request. // How entries resolve in mutltivariate case is a little bit different // from variation inheritance, thus this flattening with a caveat. const multiVariations = variations.reduce((reduced, {chain}, index) => { if (variations.length === index + 1) return reduced.concat(chain); // remove base which is part of every chain return reduced.concat(chain.slice(0, chain.length - 1)); }, []); for (let i = 0; i < multiVariations.length; i++) { const varId = multiVariations[i]; const found = entries.find(entry => { return entry.variation === varId && ( entry.runtime === 'isomorphic' || entry.runtime === runtime || entry.runtime === 'package' ); }); if (found) return found; } throw new RangeError([ `Could not find entries with norm "${norm}" that matches`, `"${JSON.stringify(variations)}"`, 'in the list of entries', `[${entries.map(({id}) => id)}]`, ].join(' ')); } function exec(fileName, source, {sandbox = {}, resolver}) { if (!sandbox) sandbox = {}; if (!sandbox.cache) sandbox.cache = {}; vm.createContext(sandbox); if (!sandbox.global) sandbox.global = sandbox; if (!sandbox.process) sandbox.process = require('process'); if (!sandbox.Buffer) sandbox.Buffer = global.Buffer; if (!sandbox.setTimeout) sandbox.setTimeout = global.setTimeout; if (!sandbox.clearTimeout) sandbox.clearTimeout = global.clearTimeout; if (!sandbox.setInterval) sandbox.setInterval = global.setInterval; if (!sandbox.clearInterval) sandbox.clearInterval = global.clearInterval; // Let's pipe vm output to stdout this way sandbox.console = console; function varRequire(parentId, literal) { if (builtinLibs.indexOf(literal) >= 0) return _require(literal); const entry = resolver(parentId, literal); if (entry) { return runEntryInVM(entry.id, entry.source, sandbox, varRequire); } // In such case, it is real node's module. const dependencyPath = resolve.sync(literal, { basedir: path.dirname(parentId), }); return _require(dependencyPath); } // We allow API user to use older version of cache if it passes the same // instance of sandbox. If not, we create a new one and make it // last one exec execution. varRequire.cache = sandbox.cache; return runEntryInVM(fileName, source, sandbox, varRequire); } module.exports = { execWithRegistry(registry, mainId, variations, sandbox, runtime='main') { function resolve(norm) { const entries = registry.getExecutableEntries(norm); if (!entries) return null; return matchVar( norm, Array.from(entries.values()), variations, runtime ); } const mainEntry = resolve(mainId); if (!mainEntry) return require(mainId); try { return exec(mainEntry.id, mainEntry.source, { sandbox, runtime, resolver(from, depLiteral) { const parent = registry.getEntry(from); if (!parent.deps[depLiteral]) throw new Error(`Any form of dynamic require is not supported by Mendel. ${from} -> ${depLiteral}`); // eslint-disable-line max-len let normId = parent.deps[depLiteral][runtime]; if (typeof normId === 'object') normId = normId[runtime]; // If we get _noop from cache, this depLiteral doesn't exist if (normId === '_noop') throw new Error(`Cannot find ${depLiteral} from ${mainEntry.id}`); // eslint-disable-line max-len return resolve(normId); }, }); } catch (e) { e.stack = errorMapper(e.stack, registry); console.log('Error was thrown while evaluating.'); console.log(e.stack); throw e; } }, exec, }; <file_sep>/packages/mendel-pipeline/docs/README.md # Mendel Pipeline ## Lesson from V1 <file_sep>/packages/mendel-development-middleware/README.md # mendel-development-middleware Mendel middleware that executes and builds based on a Mendel client appropriate for during development. <file_sep>/packages/mendel-outlet-manifest/src/index.js const debug = require('debug')('mendel:outlet:manifest'); const babelCore = require('babel-core'); const manifestUglify = require('mendel-manifest-uglify'); const fs = require('fs'); const shasum = require('shasum'); // Manifest module.exports = class ManifestOutlet { constructor(config, options) { // Mendel config this.config = config; // outlet options this.options = Object.assign({ envify: true, uglify: true, runtime: 'browser', }, options); this.runtime = this.options.runtime; } perform({entries, options}) { const manifestFileName = options.manifest; // We are going to mutate this guy; make sure we don't change the original one entries = new Map(entries.entries()); if (this.options.envify) this.removeProcess(entries); let manifest = this.getV1Manifest(entries); if (this.options.envify) manifest = this.envify(manifest); if (this.options.uglify) manifest = this.uglify(manifest); fs.writeFileSync( manifestFileName, JSON.stringify(manifest, null, 2) ); debug(`Outputted: ${manifestFileName}`); } dataFromItem(item) { const deps = {}; Object.keys(item.deps).forEach(key => { const dep = item.deps[key][this.runtime]; deps[key] = dep; }); const data = { id: item.normalizedId, normalizedId: item.normalizedId, deps, file: item.id, variation: item.variation || this.config.baseConfig.dir, source: item.source, sha: shasum(item.source), }; if (item.expose) data.expose = item.expose; if (item.entry) data.entry = item.entry; return data; } removeProcess(entries) { Array.from(entries.keys()).forEach(key => { const entry = entries.get(key); if (!entry) return; if (entry.normalizedId === 'process') entries.delete(key); }); } envify(manifest) { manifest.bundles.map(row => { row.data.forEach(data => { if (!data.deps.process) return; const {code} = babelCore.transform(data.source, { plugins: ['transform-inline-environment-variables'], }); data.source = code; delete data.deps.process; }); }); return manifest; } uglify(manifest) { manifestUglify([manifest], { // `compress` and `mangle` are set to `true` on uglifyify // just making sure we have the same defaults uglifyOptions: { root: this.config.baseConfig.dir, compress: this.options.compress ? this.options.compress : true, mangle: this.options.mangle ? this.options.mangle : true }, }, ([uglifiedManifest]) => { // happens immediately manifest = uglifiedManifest; }); return manifest; } getV1Manifest(entries) { const manifest = { indexes: {}, bundles: [], }; Array.from(entries.keys()).sort() .forEach(key => { const item = entries.get(key); const id = item.normalizedId; if (!manifest.indexes[id]) { const data = this.dataFromItem(item); const newEntry = { id: item.normalizedId, index: null, variations: [data.variation], data: [data], }; if (data.entry) newEntry.entry = data.entry; if (data.expose) newEntry.expose = data.expose; manifest.bundles.push(newEntry); const index = manifest.bundles.indexOf(newEntry); manifest.indexes[id] = index; newEntry.index = index; } else { const index = manifest.indexes[id]; const existing = manifest.bundles[index]; const newData = this.dataFromItem(item); if (existing.variations.includes(newData.variation)) { return debug( `${existing.file}|${existing.variations} `, `${item.id}|${item.variation}`, 'WARN: normalizedId and variation collision' ); } existing.variations.push(newData.variation); existing.data.push(newData); if (newData.entry) existing.entry = newData.entry; if (newData.expose) existing.expose = newData.expose; } }); return manifest; } }; <file_sep>/packages/mendel-generator-node-modules/generator-node-modules.js function isNodeModule(id) { return id.indexOf('node_modules') >= 0; } module.exports = function generatorNodeModule(bundle, doneBundles, registry) { const {entries} = bundle.options; const nodeModules = new Map(); const nodeModulesNorm = new Map(); bundle.entries = nodeModules; // TODO factor this out to separate sharable component registry.getEntriesByGlob(entries).forEach(entry => { const {normalizedId, type} = entry; registry.walk(normalizedId, {types: [type]}, (dep) => { if (nodeModules.has(dep.id)) return false; if (dep === entry) dep.entry = true; nodeModules.set(dep.id, dep); }); }); const from = bundle.options.options.from || 'all'; const fromBundle = Array.isArray(from) ? from : [from]; const fromFilter = fromBundle.find(id => id === 'all') ? () => true : ({id}) => fromBundle.some(bundleId => id === bundleId); doneBundles .filter(fromFilter) .forEach(doneBundle => { const {entries} = doneBundle; Array.from(entries.values()) .filter(({id}) => isNodeModule(id) || nodeModules.has(id)) .forEach(entry => { // Remove it from main bundle entries.delete(entry.id); // and add it to the node module bundle; nodeModules.set(entry.id, entry); nodeModulesNorm.set(entry.normalizedId, entry); entry.expose = null; }); Array.from(entries.values()) .filter(({id}) => !isNodeModule(id)) .forEach(entry => { const {deps} = entry; Object.keys(deps) .forEach(depLiteral => { const dep = deps[depLiteral]['browser']; if (!nodeModulesNorm.has(dep)) return; const depEntry = nodeModulesNorm.get(dep); // Only node modules that are being used by main bundle // should be expose or "required" in browserify sense. // Unncessary but congruent to ManifestV1 depEntry.expose = depEntry.normalizedId; }); }); }); return bundle; }; <file_sep>/packages/mendel-exec/source-mapper.js const {SourceMapConsumer} = require('source-map'); const regex = /(at \S* |\S*@)[\(]{0,1}(\S+)\:(\d+)\:(\d+)[\)]{0,1}$/; function parseStackTrace(rawStackTrace) { return rawStackTrace.split('\n').map(stackLine => { const match = stackLine.match(regex); if (!match || match.length !== 5) return stackLine; let description = match[1]; if (description.indexOf('at ') === 0) { // This is the Chrome's "At desc " case description = description.slice(3).trim(); } else { // This is the Firefox's "desc@" case description = description.slice(0, description.length - 1).trim(); } return { raw: stackLine, description, file: match[2], line: parseInt(match[3], 10), column: parseInt(match[4], 10), }; }); } function mapper(rawSourceMap, line, column) { // From https://github.com/mozilla/source-map/ const smc = new SourceMapConsumer(rawSourceMap); return smc.originalPositionFor({ line, column, }); } module.exports = function stackTraceMapper(stackTrace, registry) { const parsed = parseStackTrace(stackTrace); return parsed.map(stackLine => { // In case it is not a line with source number if (typeof stackLine !== 'object') return stackLine; const entry = registry.getEntry(stackLine.file); // In case of no map (files without transform) or v8 native code if (!entry || !entry.map) return stackLine.raw; const mapped = mapper(entry.map, stackLine.line, stackLine.column); const {source, line, column, name} = mapped; // Output stacktrace in v8 style return ` at ${name || stackLine.description} (${source}:${line}:${column})`; // eslint-disable-line max-len }).join('\n'); }; <file_sep>/test/tree-variation-walker.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ var t = require('tap'); var MendelVariationWalker = require('../packages/mendel-core/tree-variation-walker'); t.equals(MendelVariationWalker().constructor, MendelVariationWalker, 'constructor'); var stub1 = { index: 0, id: 'first', variations: ['a', 'b', 'special'], data: [{id:'a', sha:'ba'},{id:'b'},{id:'special'}], }; var walker = MendelVariationWalker([['a'],['special']], 'special'); var ret = walker._resolveBranch(stub1); t.match(ret, {index:0, resolved:{id:'a'}}, 'returns first match'); t.match(walker.conflicts, 0, 'no conflicts with base'); walker = new MendelVariationWalker([['nope'], ['b'],['special']], 'special'); ret = walker._resolveBranch(stub1); t.match(ret, {index:1, resolved:{id:'b'}}, 'returns first match'); t.equals(walker.conflicts, 0, 'no conflicts with base'); walker = new MendelVariationWalker([['a', 'b'],['special']], 'special'); ret = walker._resolveBranch(stub1); t.equals(walker.conflicts, 0, 'Two variations on the same level don\'t conflict'); walker = new MendelVariationWalker([['a'], ['b'],['special']], 'special'); ret = walker.find(stub1); t.equals(walker.conflicts, 1, 'detects conflicts'); t.match(walker.conflictList, {'first':true}, 'conflicts map'); t.match(walker.found(), { deps: [ { id: 'a', sha: 'ba' } ], hash: 'bWVuZGVsAQD_AQAGH7IIQx23k7vTZFt6FgWKHiokEg', conflicts: 1, conflictList: { first: true } }, 'full result inherits from MendelWalker'); <file_sep>/packages/mendel-config/legacy/index.js /* Copyright 2015, Yahoo Inc. Inspired by https://github.com/babel/babel/blob/d06cfe63c272d516dc4d6f1f200b01b8dfdb43b1/packages/babel-cli/src/babel-doctor/rules/has-config.js Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ var path = require("path"); var xtend = require("xtend"); var defaultConfig = require('./defaults'); module.exports = function(config) { var defaults = defaultConfig(); // merge by priority config = xtend(defaults, config); config.basedir = config.basedir || defaults.basedir; // merge environment based config var environment = process.env.MENDEL_ENV || process.env.NODE_ENV; if (environment) { config.environment = environment; } var envConfig = config.env[config.environment]; if (envConfig) { config = mergeRecursive(config, envConfig); } delete config.env; // Final parsing if (!path.isAbsolute(config.basedir)) { config.basedir = path.resolve(config.basedir); } if (!path.isAbsolute(config.outdir)) { config.outdir = path.join(config.basedir, config.outdir); } if (!path.isAbsolute(config.bundlesoutdir)) { config.bundlesoutdir = path.join(config.outdir, config.bundlesoutdir); } if (!path.isAbsolute(config.serveroutdir)) { config.serveroutdir = path.join(config.outdir, config.serveroutdir); } config.bundles = parseBundles(config.bundles); return config; }; function parseBundles(bundles) { // istanbul ignore if if (!bundles) return bundles; var bundlesArray = Object.keys(bundles).filter(Boolean); if (!bundlesArray.length) return bundlesArray; return bundlesArray.map(function(bundleName) { var bundle = bundles[bundleName]; bundle.id = bundleName; bundle.bundleName = bundleName; bundle.manifest = bundleName + '.manifest.json'; flattenFilenameArrays(bundle); return bundle; }).filter(Boolean); } function mergeRecursive(dest, src) { for (var key in src) { // istanbul ignore else if (src.hasOwnProperty(key)) { if (isObject(dest[key]) && isObject(src[key])) { dest[key] = mergeRecursive(dest[key], src[key]); } else { dest[key] = src[key]; } } } return dest; } function flattenFilenameArrays(bundle) { ['entries', 'require', 'external', 'exclude', 'ignore'] .forEach(function(param) { var inputArray = bundle[param]; if (!Array.isArray(inputArray)) return; var i = 0; while (i <= inputArray.length) { var item = inputArray[i]; if (Array.isArray(item)) { Array.prototype.splice.apply( inputArray, [i, 1].concat(item) ); } i++; } }); } function isObject(obj) { return ({}).toString.call(obj).slice(8, -1).toLowerCase() === 'object'; } <file_sep>/examples/README.md ## Examples All examples are small applications that you can go to it's root directory and run `npm install` to have it all setup. For Mendel 1.x (`planout-example`), you can run: $ npm run build $ npm run development For Mendel 2.x (`full-example`), you can run: $ npm run daemon $ npm run development To start the server in development mode. In this mode every source maps are enabled and bundle compilation is done on demand. The first time you load the application is slow, but once you save a file, the full bundle, and all the bundle combinations, should have changes propagated almost immediately. All examples also support running in production mode: $ npm run build $ npm run production Notice that in production mode bundles will load super fast, even with combinations, but in order to see code changes you will need to stop the server, run the build step again and start the server again. <file_sep>/docs/Roadmap.md ## Mendel 2.0 Roadmap The main goal for 2.0 is being able to deliver bundles compiled by more compilers, rollupjs being the main goal we want to achieve. This would enable Mendel to have smaller bundles. But Mendel has a lot more features than rollup has right now, experimentation/variation bundling and external/expose/splitting bundles. We also want to change internally how bundles are compiled so we have build time reduction by not running transformations more than once. #### Goals breakdown for 2.0 development * Mendel Advocating / Documentation * Update Mendel documentation for * CLI use * .mendelrc capabilities * Cookbook recipe for “creating a variation” * Instalation guide * Mendel 2.0 - Fix Mendel isomorphic requires (package.json:[browser/main]) * Mendel server-side bundling needs to be removed from client bundle pipeline * Mendel 2.0 - New manifest with client and server specific transforms * Should have: * Common transforms * Server transforms * Client transforms * Must support browserify transforms * **Will not** support browserify plugins * Might support Rollup (transform only) plugins * Might support WebPack (transform only) plugins * Mendel 2.0 - Multicore support * Mendel execution time cut by the number of available processors * Ideally in both development and production bundling process * Mendel 2.0 - Rollup like compilation for production * smaller bundles * external bundles * extract bundles <file_sep>/packages/mendel-parser-json/index.js function JSONParser({source} /*, options */) { return { source: `module.exports = ${source}`, }; } JSONParser.parser = true; JSONParser.extensions = ['.json']; JSONParser.compatible = '.js'; module.exports = JSONParser; <file_sep>/examples/full-example/isomorphic/base/components/toolbar.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ import React from 'react'; import Button from './button'; class Toolbar extends React.Component { render() { return ( <div> <div>Toolbar</div> <nav className="toolbar"> <Button onClick={this.handleClick}>Button</Button> <Button onClick={() => { throw new Error('I was thrown'); }}>Throw me</Button> <Button>Button</Button> </nav> </div> ); } } export default Toolbar; <file_sep>/packages/mendel-manifest-extract-bundles/manifest-extract.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ module.exports = manifestExtractBundles; var debug = require('debug')('mendel-manifest-extract-bundles'); function manifestExtractBundles(manifests, options, next) { var fromManifest = manifests[options.from]; var externalManifest = manifests[options.external]; var fromFiles = function() { return Object.keys(fromManifest.indexes); }; var externalFiles = function() { return Object.keys(externalManifest.indexes); }; // Modules that are exposed on "external" should be removed from main filterFilesFromManifest(fromManifest, function(file) { var modIndex = externalFiles().indexOf(file); var isExposedOnExternalBundle = false; if (-1 !== modIndex) { var externalMod = externalManifest.bundles[modIndex]; if (externalMod.expose) { isExposedOnExternalBundle = true; } } return !isExposedOnExternalBundle; }, options.from); // Cleanup potetial sub-dependencies of removed files removeOrphans(fromManifest, options.from); // Files that exist on main should be removed from external var removedFromExternal = []; filterFilesFromManifest(externalManifest, function(file) { if (fromFiles().indexOf(file) >= 1) { removedFromExternal.push(file); return false; } return true; }, options.external); // Cleanup potetial sub-dependencies of removed files removeOrphans(externalManifest, options.external); // Files that exist on main and were removed from external bundle // should be exposed on main fromFiles().forEach(function(file) { var moduleIndex = fromManifest.indexes[file]; var bundle = fromManifest.bundles[moduleIndex]; if (removedFromExternal.indexOf(file) > -1) { bundle.expose = bundle.id; bundle.variations.forEach(function(variation, index) { bundle.data[index].expose = bundle.id; }); debug(bundle.id + ' exposed on ' + options.from); } }); debug([ fromFiles().length, 'files remaining in', options.from, 'after extraction', ].join(' ')); debug([ externalFiles().length, 'files remaining in', options.external, 'after extraction', ].join(' ')); next(manifests); } /* receives a manifest and a "selector" function modifies manifest indexes to include only files that selector returns truthy */ function filterFilesFromManifest(manifest, selector, logName) { // By removing files from the index, when the manifest is sorted and // validated, unreachable modules are removed. var removedFiles = []; manifest.indexes = Object.keys(manifest.indexes) .reduce(function(indexes, file) { if (selector(file)) { indexes[file] = manifest.indexes[file]; } else { removedFiles.push(file); debug(file + ' removed from ' + logName); } return indexes; }, {}); // Also, we need to make sure deps are updated to "false", which marks // the dep as external Object.keys(manifest.indexes).forEach(function(file) { var bundle = manifest.bundles[manifest.indexes[file]]; bundle.data.forEach(function(module) { Object.keys(module.deps).forEach(function(key) { var value = module.deps[key]; if (removedFiles.indexOf(value) >=0) { module.deps[key] = false; } }); }); }); } /* walks the manifest dependencies and remove indexes that are unreachable */ function removeOrphans(manifest, logName) { var originalIndexes = Object.keys(manifest.indexes); // hashtable for number of time a bundle was visited var visitedIndexes = originalIndexes.reduce(function(indexes, file) { indexes[file] = false; return indexes; }, {}); // recursive function to visit bundle and it's deps function visitBundle(file) { if (visitedIndexes[file]) { return; } visitedIndexes[file] = true; // walk deps var bundle = manifest.bundles[manifest.indexes[file]]; bundle.data.forEach(function(module) { Object.keys(module.deps).forEach(function(key) { var value = module.deps[key]; if (visitedIndexes.hasOwnProperty(value)) { visitBundle(value); } }); }); } // start visiting from entries and exposed originalIndexes.forEach(function(file) { var bundle = manifest.bundles[manifest.indexes[file]]; if (bundle.expose || bundle.entry) { visitBundle(file); } }); filterFilesFromManifest(manifest, function(file) { return visitedIndexes.hasOwnProperty(file) && visitedIndexes[file]; }, logName); } <file_sep>/packages/mendel-middleware/index.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ var pathToRegexp = require('path-to-regexp'); var mbpack = require('mendel-browser-pack'); var MendelTrees = require('mendel-core'); var MendelLoader = require('mendel-loader'); var debug = require('debug')('mendel:middleware'); module.exports = MendelMiddleware; function MendelMiddleware(opts) { var trees = MendelTrees(opts); var route = trees.config.routeConfig.hash || '/mendel/:hash/:bundle.js'; var getPath = pathToRegexp.compile(route); var keys = []; var bundleRoute = pathToRegexp(route, keys); var bundles = trees.config.bundles.reduce(function(acc, bundle) { acc[bundle.id] = bundle; return acc; }, {}); var loader = new MendelLoader(trees, { parentModule: module.parent, }); return function(req, res, next) { req.mendel = req.mendel || { bundleCache: {}, variations: false, }; req.mendel.getBundleEntries = function(bundleId) { const bundleDeps = trees.bundles[bundleId].bundles; return bundleDeps .filter(dep => !!dep.expose || !!dep.entry) .map(dep => dep.expose || dep.id); }; req.mendel.setVariations = function(variations) { if (req.mendel.variations === false) { var varsAndChains = trees.variationsAndChains(variations); req.mendel.variations = varsAndChains.matchingVariations; req.mendel.lookupChains = varsAndChains.lookupChains; } return req.mendel.variations; }; req.mendel.getBundle = function(bundle) { if (!req.mendel.variations) { throw new Error('Please call req.mendel.setVariations first'); } if(!req.mendel.bundleCache[bundle]) { var tree = trees.findTreeForVariations( bundle, req.mendel.lookupChains); req.mendel.bundleCache[bundle] = tree; } return req.mendel.bundleCache[bundle]; }; req.mendel.getURL = function(bundle, variations) { if (!req.mendel.variations && variations) { console.warn( '[DEPRECATED] Please replace use of '+ 'mendel.getURL(bundle, variations).'+ '\nUse mendel.setVariations(variations) followed by'+ ' mendel.getURL(bundle) instead.' ); req.mendel.setVariations(variations); } var tree = req.mendel.getBundle(bundle); return getPath({ bundle: bundle, hash: tree.hash }); }; req.mendel.resolver = function(bundles, variations) { if (!req.mendel.variations && variations) { console.warn( '[DEPRECATED] Please replace use of '+ 'mendel.resolver(bundle, variations).'+ '\nUse mendel.setVariations(variations) followed by'+ ' mendel.resolver(bundle) instead.' ); req.mendel.setVariations(variations); } return loader.resolver(bundles, req.mendel.lookupChains); }; req.mendel.isSsrReady = loader.isSsrReady.bind(loader); // Match bundle route var reqParams = bundleRoute.exec(req.url); if (!reqParams) { return next(); } var params = namedParams(keys, reqParams); if (!( params.bundle && params.hash && bundles[params.bundle] )) { return next(); } var decodedResults = trees.findTreeForHash(params.bundle, params.hash); if (!decodedResults || decodedResults.error) { return bundleError(res, 404, decodedResults && decodedResults.error, params); } var modules = decodedResults.deps.filter(Boolean); if (!modules.length) { // Something wrong, modules shouldn't be zero return bundleError(res, 500, { code: 'EMPTYBUNDLE', message: 'Tree contents are empty', }, params); } // Serve bundle res.set({ 'Content-Type': 'application/javascript', 'Cache-Control': 'public, max-age=31536000', }); var pack = mbpack(modules); pack.pipe(res); }; } /****** Here is a non-functional but more performant implementation of the same transformation above. I don't think it would pay off in performance, but I am keeping it here since I didn't benchmark. The above should be more maintainable. function indexedDeps(mods) { var i, key, deps, index, newId, newDeps, newMod, map, newMods; // indexes can't start with 0 because 0 is false for browserify runtime map = ['']; // stores indexes for (i = 0; i < mods.length; i++) { if (mods[i].expose) continue; map.push(mods[i].id); } // create new mods newMods = []; for (i = 0; i < mods.length; i++) { // shallow copy original deps newMod = {}; for(key in mods[i]) { newMod[key] = mods[i][key]; } // create new deps deps = mods[i].deps; newDeps = {}; for(key in deps) { index = map.indexOf(deps[key]); if (index > -1) { newDeps[key] = index; } else { newDeps[key] = deps[key]; } } // replace props on new mod newId = map.indexOf(newMod.id); if (newId > -1) newMod.id = newId; newMod.deps = newDeps; newMods.push(newMod); } return newMods; } ****/ function bundleError(res, statusCode, error, params) { var message = "Mendel: "; if (!error) { message += (statusCode === 404 ? 'Bundle not found' : 'Unable to create Bundle'); } else { message += error.code + ' - ' + error.message; } debug([(error ? error.code : 'UNKNOWN'), 'hash=' + params.hash, 'bundle=' + params.bundle].join(' ')); res.status(statusCode).send(message); } function namedParams(keys, reqParams) { return keys.reduce(function(params, param, index) { params[param.name] = reqParams[index+1]; return params; }, {}); } <file_sep>/packages/mendel-development/README.md ### Mendel Development `mendel-development` is an internal package so we can share code across multiple packages on the Mendel monorepo. Those files are not needed for production, therefore it will only be added as sub-dependencies of mendel packages meant to be `package.json:devDependencies`. <file_sep>/docs/Tests.md ## Mendel Tests For the moment, Mendel relies on some private repositories for integration tests. Make sure you have the appropriate access in order to run integration tests. ### Unit tests **File organization:** * All tests are in the test/ directory * Each test files corresponds to exactly one source file * Only stubs and fixtures use subdirectories * All build/ directories are ignored via the .gitignore to prevent generated output from being committed #### Running tests. If you have not already, please link all your local npm packages npm run linkall To run tests quickly, please use: npm test # all tests npm run unit # only unit tests npm run lint # only linter If you want a quick coverage report of files and classes we already wrote tests, you can run: npm run coverage This will run coverage with command line output only and will only cover files that are required by tests. To run full coverage you can: npm run coverage-html This will find all files in the application and report coverage in both the command line and HTML formats. If possible, it will as open your browser to view the report. To run tests against a single file you can: npm run unit-file test/testname.js #### Single file coverage We avoid mocking too much, so coverage might be biased when running the full suite. To make sure coverage is 100% on each file, you can run coverage on a single test file, but listing all files that were covered: npm run coverage-file test/testname.js Tests are written to target a single file, so when running the single test file, look for the corresponding source file, even though many files may show up in the result. Finally, if you want to find out if your changes are impacting those individual files coverage, there is a helper to loop through each test file running coverage and outputting summary to the terminal. npm run coverage-all-individualy <file_sep>/packages/mendel-config/variations.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ var fs = require('fs'); var path = require('path'); module.exports = function(config) { var projectRoot = config.projectRoot || config.basedir || process.cwd(); var variationConfig = config.variationConfig || {}; var variations = config.variations || variationConfig.variations || {}; var baseVariationDir = config.basetree || config.base; if (config.variationConfig) { var dirs = [].concat(variationConfig.variationDirs).filter(Boolean); baseVariationDir = config.baseConfig.dir; return dirs.reduce(function(allVariations, dir) { return allVariations.concat(variationsForDir(variations, dir)); }, []); } else { // legacy var dir = config.variationsdir || config.vasriations_root || ""; return variationsForDir(variations, dir); } function variationsForDir(vars, variationRoot) { return Object.keys(vars).map(function(varId) { if(varId === '_') return; if (Array.isArray(vars[varId] && vars[varId]._)) { vars[varId] = vars[varId]._; } var chain = [varId] .concat(Array.isArray(vars[varId]) ? vars[varId] : []) .map(relativeRoot) .filter(existsInProjectRoot); return { id: varId, dir: path.join(variationRoot, (vars[varId] || [varId])[0]), chain: chain.concat(baseVariationDir || projectRoot), }; }).filter(function(variation) { return variation // we add base automatically, user can't add base on .mendelrc && variation.id !== 'base' && variation.chain.length > 1; }); function relativeRoot(dir) { return path.join(variationRoot, dir); } } function existsInProjectRoot(dir) { return fs.existsSync(path.join(projectRoot, dir)); } }; <file_sep>/packages/mendel-pipeline/src/deps/index.js const path = require('path'); const MultiProcessMaster = require('../multi-process/base-master'); const mendelDeps = require('mendel-deps'); /** * Knows how to do all kinds of trasnforms in parallel way */ class DepsManager extends MultiProcessMaster { /** * @param {String} config.projectRoot */ constructor({projectRoot, baseConfig, variationConfig, shim}, mendelCache) { // For higher cache hit rate, do not utilize "all cores". super(path.join(__dirname, 'worker.js'), {name: 'deps', numWorker: 2}); this._mendelCache = mendelCache; this._projectRoot = projectRoot; this._baseConfig = baseConfig; this._variationConfig = variationConfig; this._shim = shim; this._mendelCache.on('entryRemoved', () => { this.sendAll('clearCache'); }); } detect(entryId, source) { if (!mendelDeps.isSupported(path.extname(entryId))) { // there are no dependency return Promise.resolve({id: entryId, deps: {}}); } return this.dispatchJob({ filePath: entryId, source, // config properties projectRoot: this._projectRoot, baseConfig: this._baseConfig, variationConfig: this._variationConfig, }).then(({filePath, deps}) => this.resolve(filePath, deps)); } resolve(entryId, rawDeps) { const deps = Object.assign({}, rawDeps); // When a shim is present in one of the deps: // main: false so we don't include node packages into Mendel pipeline // browser: path to the shim -- this will make pipeline include such shims Object.keys(deps) .filter(literal => this._shim[literal]) .forEach(literal => { deps[literal] = { main: deps[literal].main || this._shim[literal], browser: this._shim[literal], }; }); return {id: entryId, deps}; } /** * @override */ subscribe() { return { has: ({filePath}, sender) => { const value = this._mendelCache.hasEntry(filePath); sender('has', {value, filePath}); }, }; } } module.exports = DepsManager; <file_sep>/packages/mendel-pipeline/src/transformer/worker.js const analytics = require('../helpers/analytics/analytics-worker')('transform'); module.exports = function() { const debug = require('debug')('mendel:transformer:slave-' + process.pid); return { start({source, transforms, filename}) { debug(`[Slave ${process.pid}] Starting transform.`); let promise = Promise.resolve({source}); transforms.forEach(transform => { promise = promise .then(analytics.tic.bind(analytics, transform.id)) .then(({source, map}) => { const xform = require(transform.plugin); if (typeof xform !== 'function') { throw new Error(`Transform ${transform.id} is incompatible with Mendel.`); } return xform({filename, source, map}, transform.options); }) .then(analytics.toc.bind(analytics, transform.id)) .then(result => { debug(`[Slave ${process.pid}][${transform.id}] "${filename}" transformed`); return result; }); }); return promise; }, }; }; <file_sep>/packages/mendel-resolver/bisource-resolver.js const VariationalModuleResolver = require('./variational-resolver'); const path = require('path'); class CachedBisourceVariationalResolver extends VariationalModuleResolver { constructor(options) { super(options); // Cache has to implement "has" method that returns Boolean when passed // a file path this.biSourceHas = options.has; this._cache = options.cache; } resolve(moduleName) { const cacheKey = CachedBisourceVariationalResolver.isNodeModule(moduleName) ? moduleName : path.resolve(this.basedir, moduleName); if (this._cache.has(cacheKey)) return Promise.resolve(this._cache.get(cacheKey)); return super.resolve(moduleName) .then(deps => { this._cache.set(cacheKey, deps); return deps; }); } fileExists(filePath) { // If biSourceHas has it, we know for sure it exists. // If biSourceHas says no, there is an ambiguity. Check with the FS. return Promise.resolve() .then(() => this.biSourceHas(filePath)) .then(result => { if (result) return filePath; return super.fileExists(filePath); }); } } module.exports = CachedBisourceVariationalResolver; <file_sep>/packages/mendel-config/src/types-config.js var createValidator = require('./helpers/validator'); var Minimatch = require('minimatch').Minimatch; function TypesConfig(typeName, type) { this.name = typeName; // We ignore extensions if type declaration has both extensions and glob if (type.extensions && type.glob) { console.log([ '[Config][WARN] Type declaration has both `extensions` and `glob`.', 'Ignoring the `extensions`.', ].join(' ')); } if (!type.extensions && !type.glob) { throw new Error([ `[Config][ERROR] Type declaration "${this.name}" requires either`, '`extensions` or `glob`.', ].join(' ')); } // TODO: figure out how to test this properlly, the regular tap/match // was not working well: const globStrings = type.glob || type.extensions.map(function(ext) { return ext[0] !== '.' ? '.' + ext : ext; }).map(function(ext) { return '**/*' + ext; }); const globs = this.globs = globStrings.map(glob => { if (glob instanceof Minimatch) return glob; if (glob instanceof RegExp) { glob.match = function(str) { return str.match(this); }; return glob; } return new Minimatch(glob); }); this.test = function(id) { if (id.startsWith('./')) id = id.slice(2); return globs.filter(({negate}) => !negate).some(g => g.match(id)) && globs.filter(({negate}) => negate).every(g => g.match(id)); }; this.isBinary = type.binary || type.isBinary || false; this.isResource = type.resource || type.isResource || false; this.parser = type.parser; this.parserToType = type['parser-to-type']; this.transforms = type.transforms || []; this.includeNodeModules = Boolean(type['include-node_modules']); TypesConfig.validate(this); } TypesConfig.validate = createValidator({ globs: {type: 'array', minLen: 1}, // transforms can be empty in case of simple outlet }); module.exports = TypesConfig; <file_sep>/packages/mendel-pipeline/src/cache/network/unix-socket.js const BaseNetwork = require('./base-network'); const net = require('net'); const fs = require('fs'); const {resolve} = require('path'); const chalk = require('chalk'); function patchSocket(socket) { const realWrite = net.Socket.prototype.write; // Consistent API as WS or others this way. const realEmit = net.Socket.prototype.emit; const CONTENT_DELIMITER = '\u0004'; let buffer = ''; socket.send = function(str) { if (typeof str === 'object') str = JSON.stringify(str); this.write(str); }; socket.write = function(str) { // end of transmission realWrite.call(this, str + CONTENT_DELIMITER); }; socket.emit = function(name, content) { if (name !== 'data') return realEmit.apply(this, arguments); let delimitInd; while ((delimitInd = content.indexOf(CONTENT_DELIMITER)) >= 0) { realEmit.call(this, 'data', buffer + content.slice(0, delimitInd)); content = content.slice(delimitInd + CONTENT_DELIMITER.length); buffer = ''; } buffer += content; }; } class UnixSocketNetwork extends BaseNetwork { static _serverPrecondition(path) { path = resolve(path); try { fs.statSync(path); } catch (err) { // File descriptor does not exist. Good to go! return Promise.resolve(); } return new Promise((resolve, reject) => { const client = this.getClient({path}); client.unref(); client.once('connect', () => { client.end(); reject(); }); client.once('error', resolve); }) // If connection was not made, try to delete the ipc file. .then(() => fs.unlinkSync(path)) // If connection was made OR unlink was unsuccessful // throw and exit -- cannot recover. .catch(() => { console.error(chalk.red([ '==================================================', 'Server cannot start when another server is active.', 'If no server process is active, ', `please remove or kill "${chalk.bold(path)}" manually.`, '==================================================', ].join('\n'))); throw new ReferenceError('Other Daemon Active'); }); } // @override static getServer(connectionOptions) { const {path} = connectionOptions; return this._serverPrecondition(path) .then(() => { const server = net.createServer().listen({path}); let isClosed = false; let close = server.close; server.on('connection', socket => { patchSocket(socket); socket.setEncoding('utf8'); }); server.on('close', () => isClosed = true); server.close = function closeHelper() { // Cannot close already closed socket. // Socket should tell us instead :( if (isClosed) return; close.call(server); }; server.once('error', (err) => { console.error('Unrecoverable Server Error', err); process.exit(1); }); return server; }); } // @override static getClient(connectionOptions) { const connection = net.connect(connectionOptions); patchSocket(connection); connection.setEncoding('utf8'); return connection; } } module.exports = UnixSocketNetwork; <file_sep>/packages/mendel-pipeline/src/registry/client.js const Minimatch = require('minimatch').Minimatch; const path = require('path'); class MendelOutletRegistry { constructor(config) { this._cache = new Map(); this._normalizedIdToEntryIds = new Map(); this._options = config; this._numInternalEntries = 1; // Because there is internal noop "module", we need to decrement the size. this.clear(); } clear() { this._cache.clear(); // noop module support this.addEntry({ id: './node_modules/_noop', normalizedId: '_noop', runtime: 'isomorphic', source: '', variation: this._options.baseConfig.dir, map: '', deps: {}, }); } get size() { return this._cache.size - this._numInternalEntries; } hasEntry(id) { return this._cache.has(id); } getEntry(id) { if (path.isAbsolute(id)) { id = './' + path.relative(process.cwd(), id); } return this._cache.get(id); } addEntry(entry) { if (!this._normalizedIdToEntryIds.has(entry.normalizedId)) { this._normalizedIdToEntryIds.set(entry.normalizedId, new Map()); } this._normalizedIdToEntryIds .get(entry.normalizedId) .set(entry.id, entry); // On client side, dep that resolves to "false" means noop and needs to // be bundlded or handled appropriately Object.keys(entry.deps) .forEach(mod => { Object.keys(entry.deps[mod]).forEach(runtime => { if (entry.deps[mod][runtime] === false) entry.deps[mod][runtime] = '_noop'; }); }); this._cache.set(entry.id, entry); } removeEntry(id) { const entry = this._cache.get(id); if (!entry) return; this._cache.delete(id); const map = this._normalizedIdToEntryIds.get(entry.normalizedId); map.delete(id); if (map.size === 0) { this._normalizedIdToEntryIds.delete(entry.normalizedId); } } getExecutableEntries(normId) { const fromMap = this._normalizedIdToEntryIds.get(normId); if (!fromMap) return null; const entries = Array.from(fromMap.entries()) .filter(([, value]) => { const type = this._options.types.get(value.type); return type && !type.isResource; }); return new Map(entries); } getEntriesByGlob(globStrings) { globStrings = Array.isArray(globStrings) ? globStrings : [globStrings]; const globs = globStrings.map(str => { const isNegate = str[0] === '!'; str = isNegate ? str.slice(1) : str; // Strip "./" in case it is prepended already. str = str.startsWith('./') ? str.slice(2) : str; // Have to prepend "./" because entry Ids starts with "./". const pattern = `${isNegate ? '!' : ''}./**/${str}`; return new Minimatch(pattern); }); const positives = globs.filter(({negate}) => !negate); const negatives = globs.filter(({negate}) => negate); return Array.from(this._cache.keys()) .filter(id => { return positives.some(g => g.match(id)) && negatives.every(g => g.match(id)); }) .map(id => this.getEntry(id)); } /** * Walks dependency graph of a specific type */ walk(normId, criteria, visitorFunction, _visited=new Set()) { let {types, runtime='browser'} = criteria; if (_visited.has(normId)) return; _visited.add(normId); const entryVariations = this._normalizedIdToEntryIds.get(normId); if (!entryVariations) { // throw new Error(`Entry ${normId} not found in registry`); // TODO figure out what to do about missing packages. // For instance, there is no shim for 'fs'. However, // this is totally valid dependency for server-side case but // not in the browser. Figure out what to do in case of missing deps. return; } types = types.concat('node_modules', '_others'); Array.from(entryVariations.values()) .filter(entry => { if (entry.normalizedId === '_noop') return true; if (types.indexOf(entry.type) < 0) return false; return entry.runtime === 'isomorphic' || entry.runtime === 'node_modules' || entry.runtime === runtime; }) .some(entry => { const isContinue = visitorFunction(entry); // If visitor function returns false, stop walking if (isContinue === false) return true; const allDeps = Object.keys(entry.deps) .reduce((reducedDeps, depName) => { const dep = entry.deps[depName][runtime]; reducedDeps.push(dep); return reducedDeps; }, []).filter(Boolean); allDeps.forEach(normId => { this.walk(normId, criteria, visitorFunction, _visited); }); }); } } module.exports = MendelOutletRegistry; <file_sep>/packages/mendel-pipeline/src/deps/worker.js const analytics = require('../helpers/analytics/analytics-worker')('deps'); const debug = require('debug')('mendel:deps:slave-' + process.pid); const dep = require('mendel-deps'); const path = require('path'); const VariationalResolver = require('mendel-resolver/bisource-resolver'); const pendingInquiry = new Map(); const RUNTIME = ['main', 'browser']; const resolveCache = new Map(); let resolver; module.exports = function(done) { return { start(payload, sender) { const { filePath, source, projectRoot, baseConfig, variationConfig, } = payload; debug(`Detecting dependencies for ${filePath}`); analytics.tic(); if (!resolver) { resolver = new VariationalResolver({ cache: resolveCache, runtimes: RUNTIME, extensions: ['.js', '.jsx', '.json'], // entry related basedir: path.resolve(projectRoot, path.dirname(filePath)), // config params projectRoot, baseConfig, variationConfig, recordPackageJson: true, has(filePath) { return new Promise(resolve => { if (!pendingInquiry.has(filePath)) pendingInquiry.set(filePath, []); pendingInquiry.get(filePath).push(resolve); sender('has', {filePath}); }); }, }); } else { resolver.setBaseDir(path.resolve( projectRoot, path.dirname(filePath) )); } debug(`Detecting dependencies for ${filePath}`); dep({file: filePath, source, resolver}) // mendel-resolver throws in case nothing was found .catch(() => { return RUNTIME.reduce((reduced, name) => { reduced[name] = false; return reduced; }, {}); }) .then(deps => { analytics.toc(); debug(`Dependencies for ${filePath} found!`); done({filePath, deps}); }); }, has(payload) { const {value, filePath} = payload; const pendingResolves = pendingInquiry.get(filePath); pendingResolves.forEach(resolve => resolve(value)); }, onExit() { // Nothing to clean }, clearCache() { resolveCache.clear(); }, }; }; <file_sep>/packages/mendel-transform-less/index.js const postcss = require('postcss'); const less = require('postcss-less-engine'); function LessTransformer({source, filename, map}) { return postcss([less({})]) .process(source, { parser: less.parser, from: filename, map: { inline: false, prev: map || '', }, }) .then(({css, map}) => ({source: css, map: map})); } LessTransformer.parser = true; LessTransformer.extensions = ['.less']; LessTransformer.compatible = '.css'; module.exports = LessTransformer; <file_sep>/packages/mendel-outlet-server-side-render/index.js const mkdirp = require('mkdirp'); const fs = require('fs'); const mendelRequireTransform = require('./transform-require'); const path = require('path'); const ManifestOutlet = require('mendel-outlet-manifest'); module.exports = class ServerSideRenderOutlet extends ManifestOutlet { constructor(config, options) { options = Object.assign( {envify: true, uglify: false}, options, {runtime: 'main'} ); super(config, options); this.config = config; this.outletOptions = options; } perform({entries, options}) { const filterFn = (this.outletOptions.includeNodeModules || false) ? () => true : ({id}) => id.indexOf('/node_modules') <= 0; entries = new Map(entries.entries()); Array.from(entries.keys()).forEach(key => { const entry = entries.get(key); if (!entry) entries.delete(key); else if (!filterFn(entry)) entries.delete(key); }); super.perform({entries, options}); const promises = Array.from(entries.values()) .map(e => this.performFile(e, options)); return Promise.all(promises); } getDestination(entry) { const isSource = this.config.variationConfig.allDirs.some(dir => { return entry.id.indexOf(dir) >= 0; }); return path.join( this.config.baseConfig.outdir, this.outletOptions.dir, // In case id is out of the source dir, we put default // "variation" of base variation. // This can be quite confusing to the SSR isSource ? '' : this.config.baseConfig.dir, entry.id ); } performFile(entry, options) { return new Promise((resolve, reject) => { const dest = this.getDestination(entry); const source = this.transformFile(entry, dest, options); this.saveFileToDisk(dest, source) .then(resolve, reject); }); } transformFile(entry, dest, config) { const {runtime='main'} = config.options; let {id, source, rawSource, map} = entry; if (this.outletOptions.sourcemap === true) { source += map; } if (this.outletOptions.requireTransform === true) { source = mendelRequireTransform(dest, entry, (entry, mod) => { if (!entry.deps[mod]) return mod; return entry.deps[mod][runtime]; }); } // JSON is transformed by default in Mendel but // node has special way of evaluating JSON for SSR if (path.extname(id) === '.json') { source = rawSource; } return source; } saveFileToDisk(dest, source) { return new Promise((resolve, reject) => { mkdirp(path.dirname(dest), err => { if (err) return reject(err); fs.writeFile(dest, source, 'utf-8', err => { if (err) return reject(err); resolve(); }); }); }); } }; <file_sep>/test/tree-deserializer.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ var t = require('tap'); var deserialize = require('../packages/mendel-core/tree-deserialiser'); var expected = { 'decoded': { 'branches': [ 0, 2, ], 'files': 2, 'hash': '0b0ca69d74be872c914b06e8bdee677917e8e9f2', 'name': 'mendel', 'version': 1, }, 'error': null, }; var realHash = 'bWVuZGVsAQAC_wIACwymnXS-hyyRSwbove5neRfo6fI'; var result = deserialize(realHash); result.decoded.hash = result.decoded.hash.toString('hex'); // Avoid Buffer t.match(result, expected, 'Decodes valid hash'); var hashWitOtherBranches = 'bWVuZGVsAQEDAAEDBAD_AgALDKaddL6HLJFLBui97md5F-jp8g'; t.match( deserialize(hashWitOtherBranches).decoded.branches, [1,3,0,1,3,4,0], 'changing only brances changes hash'); var err; var notEvenAHash = null; err = deserialize(notEvenAHash).error; t.match(err, new Error(), 'this hash is bad'); t.match(err.message, 'bad base64 input'); var hashWithWrongName = 'dGVzdF9fAQAC_wIACwymnXS-hyyRSwbove5neRfo6fI'; err = deserialize(hashWithWrongName).error; t.match(err, new Error(), 'this hash is bad'); t.match(err.message, 'not generated by mendel'); var hashWithWrongVersion = 'bWVuZGVs-gAC_wIACwymnXS-hyyRSwbove5neRfo6fI'; err = deserialize(hashWithWrongVersion).error; t.match(err, new Error(), 'this hash is bad'); t.match(err.message, 'version mismatch'); var wrongHashSize = 'bWVuZGVsAQAC_wIACwymnXS-hyyRSwbove5neRfo6'; err = deserialize(wrongHashSize).error; t.match(err, new Error(), 'this hash is bad'); t.match(err.message, 'short or missing sha'); <file_sep>/packages/mendel-pipeline/src/step/ist/index.js const path = require('path'); const BaseStep = require('../step'); const _internalTransforms = [ require('./defaults-js/global'), ]; const execToDefaultTransforms = new Map(); ['js', 'css', 'html'].forEach(exec => { execToDefaultTransforms.set( exec, _internalTransforms .filter(({config}) => config.exec === exec) .map(({config}) => config.id)); }); class IndependentSourceTransform extends BaseStep { /** * @param {MendelRegistry} tool.registry * @param {Transformer} tool.transformer * @param {DepsManager} tool.depsResolver */ constructor({registry, transformer, depsResolver}, options) { super(); this._registry = registry; this._depsResolver = depsResolver; this._transformer = transformer; this._transforms = new Map(); options.transforms.forEach(transform => { this._transforms.set(transform.id, transform); }); _internalTransforms.forEach(({config}) => { this._transforms.set(config.id, config); this._transformer.addTransform(config); }); this._parserTypeConversion = new Map(); this._types = options.types; this._types.forEach(type => { if (!type.parserToType) return; // TODO better cycle detection: cannot have cycle if (type.parserToType === type.name) return; this._parserTypeConversion.set(type.name, type.parserToType); }); } getTransformIdsByTypeAndExec(typeName, optEntryId) { const type = this._types.get(typeName); // Secondary type can be also missing. if (!type) return []; let appendIds = []; if (optEntryId) { const exec = this.inferExec(optEntryId, type.transforms); appendIds = execToDefaultTransforms.get(exec) || []; } return type.transforms.concat(appendIds, [type.parser]).filter(Boolean); } inferExec(id, xformIds) { if (xformIds.length) { const transform = this._transforms.get(xformIds[0]); return transform.exec; } switch (path.extname) { case '.js': case '.jsx': case '.esnext': return 'js'; case '.css': return 'css'; case '.html': return 'html'; } } getTransform(entry) { const {type} = entry; let typeConfig = this._types.get(entry.type); // When current entry is a node modules, // it can be applied with more global configuration from // "includeNodeModules". As node_modules cannot have more than one // subtype, this property is used to, for instance, minify or // do transformations on the source. // Such global configuration will override any transformations configured // for the node_modules type. if (type !== entry._type && type === 'node_modules') { const config = this._types.get(entry._type); if (config && config.includeNodeModules) { typeConfig = config; } } if (!typeConfig) { return { type, ids: this.getTransformIdsByTypeAndExec(type, entry.id), }; } const ist = {type: typeConfig.name, ids: []}; let xformIds = this.getTransformIdsByTypeAndExec(ist.type, entry.id); // If there is a parser, do type conversion while (this._parserTypeConversion.has(ist.type)) { const newType = this._parserTypeConversion.get(ist.type); // node_modules cannot change its type if (ist.type !== 'node_modules') ist.type = newType; else ist._type = newType; xformIds = xformIds.concat(this.getTransformIdsByTypeAndExec(ist.type)); } ist.ids = xformIds .map(xformId => this._transforms.get(xformId)) .filter(Boolean) .filter(({mode}) => mode === 'ist') .map(({id}) => id); // console.log(entry.id, ist.ids); return ist; } perform(entry) { const entryId = entry.id; const {ids, type: newType} = this.getTransform(entry); const source = entry.rawSource; const map = entry.map; let promise = Promise.resolve({source, map}); if (ids.length) { promise = promise.then(() => { return this._transformer.transform(entryId, ids, source, map); }); } promise .then(({source, map}) => { return this._depsResolver.detect(entry.id, source) .then(({deps}) => { this._registry.addTransformedSource({ id: entryId, source, deps, map, }); if (entry.type !== newType) { this._registry.setEntryType(entryId, newType); } entry.istSource = entry.source; entry.istDeps = entry.deps; }) .then(() => this.emit('done', {entryId}, ids)) .catch(error => { error.message = `Errored while resolving deps for ${entryId}: ` + error.message; this.emit('error', {error, id: entryId}); }); }, error => { error.message = `Errored while transforming ${entryId}: ` + error.message; this.emit('error', {error, id: entryId}); }); } } module.exports = IndependentSourceTransform; <file_sep>/packages/mendel-development/apply-extra-options.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ var path = require('path'); var glob = require('glob'); module.exports = applyExtraOptions; function applyExtraOptions(b, options) { [].concat(options.ignore).filter(Boolean) .forEach(function (i) { b._pending ++; glob(i, function (err, files) { if (err) return b.emit('error', err); if (files.length === 0) { b.ignore(i); } else { files.forEach(function (file) { b.ignore(file); }); } if (--b._pending === 0) b.emit('_ready'); }); }) ; [].concat(options.exclude).filter(Boolean) .forEach(function (u) { b.exclude(u); b._pending ++; glob(u, function (err, files) { if (err) return b.emit('error', err); files.forEach(function (file) { b.exclude(file); }); if (--b._pending === 0) b.emit('_ready'); }); }) ; [].concat(options.external).filter(Boolean) .forEach(function (x) { var xs = splitOnColon(x); if (xs.length === 2) { add(xs[0], { expose: xs[1] }); } else if (/\*/.test(x)) { b.external(x); b._pending ++; glob(x, function (err, files) { files.forEach(function (file) { add(file, {}); }); if (--b._pending === 0) b.emit('_ready'); }); } else add(x, {}); function add (x, opts) { if (/^[\/.]/.test(x)) b.external(path.resolve(x), opts); else b.external(x, opts); } }) ; } function splitOnColon (f) { var pos = f.lastIndexOf(':'); if (pos == -1) { return [f]; // No colon } else { if ((/[a-zA-Z]:[\\/]/.test(f)) && (pos == 1)){ return [f]; // Windows path and colon is part of drive name } else { return [f.substr(0, pos), f.substr(pos + 1)]; } } } <file_sep>/packages/mendel-resolver/index.js const path = require('path'); const {stat, readFile} = require('fs'); function withPrefix(path) { if (/^\w[^:]/.test(path)) path = './' + path; return path; } class ModuleResolver { /** * @param {Object} options * @param {String} options.basedir * @param {String[]} options.runtimes */ constructor({ cwd=process.cwd(), basedir=process.cwd(), extensions=['.js'], runtimes=['main'], recordPackageJson=false, } = {}) { this.extensions = extensions; this.cwd = cwd; // in case basedir is relative, we want to make it relative to the cwd. this.basedir = path.resolve(this.cwd, basedir); this.runtimes = runtimes; this.recordPackageJson = recordPackageJson; } static pStat(filePath) { return new Promise((resolve, reject) => { stat(filePath, (err, result) => { if (err) reject(err); resolve(result); }); }); } static pReadFile(filePath, options={}) { return new Promise((resolve, reject) => { readFile(filePath, options, (err, result) => { if (err) reject(err); resolve(result); }); }); } static isNodeModule(name) { return !/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[\\\/])/.test(name); } setBaseDir(basedir) { this.basedir = path.resolve(this.cwd, basedir); } /** * @param {String} moduleName name of the module to resolve its path */ resolve(moduleName) { let promise; if (!ModuleResolver.isNodeModule(moduleName)) { const moduleAbsPath = path.resolve(this.basedir, moduleName); promise = this.resolveFile(moduleAbsPath) .catch(() => this.resolveDir(moduleAbsPath)); } else { promise = this.resolveNodeModules(moduleName); } return promise // Post process .then((deps) => { // Make the path relative to the `basedir`. Object.keys(deps) .filter(rt => deps[rt]) .forEach(rt => { if (typeof deps[rt] === 'string') { // It can be module name without real path for default // node modules (like "path") if (deps[rt].indexOf('/') < 0) return; deps[rt] = withPrefix(path.relative(this.cwd, deps[rt])); } else if (typeof deps[rt] === 'object') { const rtDep = deps[rt]; Object.keys(rtDep) .filter(key => rtDep[key]) .forEach(depKey => { const newKey = depKey.indexOf('/') < 0 ? depKey : withPrefix(path.relative(this.cwd, depKey)); const newValue = rtDep[depKey].indexOf('/') < 0 ? rtDep[depKey] : withPrefix(path.relative(this.cwd, rtDep[depKey])); delete rtDep[depKey]; rtDep[newKey] = newValue; }); } }); return deps; }) .catch(() => { throw new Error(`${moduleName} failed to resolve.`); }); } fileExists(filePath) { return ModuleResolver.pStat(filePath).then(stat => { if (stat.isFile() || stat.isFIFO()) return filePath; throw new Error({ message: `${filePath} is not a File.`, code: 'ENOENT', }); }); } resolveFile(moduleName) { let promise = this.fileExists(moduleName); this.extensions.forEach(ext => { promise = promise.catch(() => this.fileExists(moduleName + ext)); }); return promise.then(filePath => { const reduced = this.runtimes.reduce((reduced, name) => { reduced[name] = filePath; return reduced; }, {}); return reduced; }); } resolveDir(moduleName) { return this.resolvePackageJson(moduleName) .catch(() => this.resolveFile(path.join(moduleName, 'index'))); } readPackageJson(dirName) { return ModuleResolver.pStat(dirName) .then(stat => { if (stat.isFile()) return ModuleResolver.pReadFile(dirName, 'utf8'); throw new Error({ message: `${dirName} does not have package.json as a File.`, code: 'ENOENT', }); }) .then((packageStr) => { // if fails to parse, we will hit catch return JSON.parse(packageStr); }); } resolvePackageJson(moduleName) { const packagePath = path.join(moduleName, '/package.json'); return this.readPackageJson(packagePath) .then(pkg => { if (this.runtimes.every(name => !pkg[name])) throw new Error('package.json without "main"'); const consider = new Map(); // A "package.json" can have below data structure // { // "main": "./foo", // "browser": { // "./foo": "./bar", // "moduleA": "moduleB", // "./baz": false, // "./abc": "./xyz.js" // } // } // In case of the main, it should resolve to either "./foo.js" or "./foo/index.js" // In case of browser runtime, it should anything that requires "./foo" should map to "./bar.js" or "./bar/index.js" this.runtimes.filter(name => pkg[name]) .forEach(name => { if (typeof pkg[name] === 'string') consider.set(pkg[name]); else if (typeof pkg[name] === 'object') { Object.keys(pkg[name]).forEach(fromPath => { consider.set(fromPath); if (typeof pkg[name][fromPath] === 'string') consider.set(pkg[name][fromPath]); }); } }); const furtherPaths = Array.from(consider.keys()); const furtherResolve = furtherPaths.map(depPath => { let promise = this.resolve(path.join(moduleName, depPath)); if (ModuleResolver.isNodeModule(depPath)) promise = promise.catch(() => this.resolve(depPath)); return promise.catch(() => false); }); return Promise.all(furtherResolve).then(resolves => { if (resolves.every(resolve => resolve === false)) throw new Error('None of the path declared resolves'); resolves.forEach((resolved, index) => { consider.set(furtherPaths[index], resolved); }); return {deps: consider, pkg}; }); }) .then(({pkg, deps}) => { const resolved = this.runtimes.reduce((reduced, name) => { const runtimeVal = pkg[name] || pkg.main; if (deps.has(runtimeVal)) reduced[name] = deps.get(runtimeVal)[name]; else if (typeof runtimeVal === 'object') { const obj = reduced[name] = {}; Object.keys(runtimeVal).forEach(key => { const val = runtimeVal[key]; if (!deps.get(key) && !deps.get(val)) return; if (!deps.get(key) && deps.get(val)) return obj[key] = deps.get(val)[name]; if (deps.get(key) && typeof val !== 'string') return obj[deps.get(key)[name]] = false; obj[deps.get(key)[name]] = deps.get(val)[name]; }); } return reduced; }, {}); if (this.recordPackageJson) resolved.packageJson = packagePath; return resolved; }); } resolveNodeModules(moduleName) { const nodeModulePaths = this.getPotentialNodeModulePaths(this.basedir); let promise = Promise.reject(); nodeModulePaths.forEach((nodeModulePath) => { promise = promise.catch(() => { return ModuleResolver.pStat(nodeModulePath).then(stat => { if (!stat.isDirectory()) throw new Error({ message: `${nodeModulePath} is not a directory.`, code: 'ENOENT', }); const moduleFullPath = path.join(nodeModulePath, moduleName); return this.resolveFile(moduleFullPath) .catch(() => this.resolveDir(moduleFullPath)); }); }); }); return promise; } // From https://github.com/substack/node-resolve getPotentialNodeModulePaths(start) { const modules = 'node_modules'; // ensure that `start` is an absolute path at this point, // resolving against the process' current working directory start = path.resolve(start); let prefix = '/'; if (/^([A-Za-z]:)/.test(start)) { prefix = ''; } else if (/^\\\\/.test(start)) { prefix = '\\\\'; } const splitRe = process.platform === 'win32' ? /[\/\\]/ : /\/+/; const parts = start.split(splitRe); const dirs = []; for (let i = parts.length - 1; i >= 0; i--) { if (modules === parts[i]) continue; dirs.push(prefix + path.join(path.join.apply(path, parts.slice(0, i + 1)), modules)); } if (process.platform === 'win32'){ dirs[dirs.length - 1] = dirs[dirs.length - 1].replace(':', ':\\'); } return dirs; } } module.exports = ModuleResolver; <file_sep>/scripts/publish.js #!/usr/bin/env node const {execSync} = require('child_process'); const packages = require('./mendel-packages'); const origCwd = process.cwd(); packages.forEach(pkgPath => { process.chdir(pkgPath); console.log(execSync('npm publish').toString().trim()); process.chdir(origCwd); }); <file_sep>/packages/mendel-treenherit/README.md # Mendel tree inheritance `mendel-treenherit` is a browserify transform that resolves module dependencies using file system variations. In most cases, it is better to use `mendel-browserify` or the Mendel command line tool to generate your bundles, but if you just need to generate a bundle for a particular variation, you can use `mendel-treenherit` alone with browserify to accomplish that. You can find all about file system variations on the Mendel documentation, but here is quick recap as visual representation: ``` Bundle "base" Bundle "new_add_format" ^ ^ | resolution direction | | -----------------------------------------> | src/ experiments/new_ad_format/ resolved/new_ad_format/ ├── controllers ├── controllers ├── controllers │ ├── main.js │ │ │ ├── main.js │ ├── settings.js │ │ │ ├── settings.js │ └── sidebar.js -----> X│ └── sidebar.js ------------>└── sidebar.js ** ├── main_bindle.js │ ├── main_bindle.js ├── vendor │ ├── vendor │ ├── calendar.js │ │ ├── calendar.js │ ├── ember.js │ │ ├── ember.js │ ├── jquery.js │ │ ├── jquery.js │ └── react.js │ │ └── react.js └── views └── views └── views ├── admin.js │ ├── admin.js ├── ads.js -------------> X└── ads.js ---------------->├── ads.js ** ├── list-item.js ├── list-item.js ├── list.js ├── list.js ├── login.js ├── login.js ├── new_item.js ├── new_item.js └── sidebar_item.js └── sidebar_item.js ** Files marked with ** in the "resolved" tree are used from the "experiments/new_ad_format/" tree, all other files are used from "src/" tree. ``` To generate `base_bundle.js`, you don't need any transforms, plain old browserify should work: browserify src/main_bundle.js --output build/base_bundle.js In order to generate the new add format you can use `mendel-treenherit` as follows: ```bash browserify src/main_bindle.js \ --output build/new_add_format_bundle.js \ --transform [ mandel-treenherit \ --dirs [ experiments/new_ad_format/ src/ ] \ ] \ ``` If you pass in multiple directories you can also do multiple variation inheritance. Take the following source tree: [![multiple folder inheritance diagram](https://cdn.rawgit.com/yahoo/mendel/master/docs/Multiple-folder-inheritance-source-tree.svg)](../../docs/Multiple-folder-inheritance-source-tree.svg) This is the resulting resolution: [![multiple folder inheritance diagram](https://cdn.rawgit.com/yahoo/mendel/master/docs/Multiple-folder-inheritance-resolution.svg)](../../docs/Multiple-folder-inheritance-resolution.svg) <file_sep>/packages/mendel-config/src/outlet-config.js var createValidator = require('./helpers/validator'); var resolvePlugin = require('./helpers/resolve-plugin'); function OutletConfig({id, plugin, options={}}, {projectRoot: basedir}) { this.id = id; this._plugin = plugin; this.options = options; this.plugin = resolvePlugin({plugin, basedir}).plugin; if (this.options.plugin) { if (!Array.isArray(this.options.plugin)) { throw new Error(`Expect 'options.plugin' to be an Array.`); // eslint-disable-line } this.options.plugin = this.options.plugin.map((plugin, index) => { if (typeof plugin !== 'string' && !Array.isArray(plugin)) { throw new Error(`Expect 'options.plugin[${index}]' to be a String or an Array.`); // eslint-disable-line } if (typeof plugin === 'string') return resolvePlugin({plugin, basedir}).plugin; plugin[0] = resolvePlugin({plugin: plugin[0], basedir}).plugin; return plugin; }); } OutletConfig.validate(this); } OutletConfig.validate = createValidator({ id: {required: true}, plugin: {required: true}, }); module.exports = OutletConfig; <file_sep>/examples/planout-example/isomorphic/base/components/app.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. Contributed by <NAME> <<EMAIL>> See the accompanying LICENSE file for terms. */ import React from 'react'; import Header from './header'; import Body from './body'; import Footer from './footer'; import Docs from './docs'; const style = { border: "2px solid grey", padding: "20px", margin: "20px" } export default () => { return ( <div> <div style={style}> <b>app.js</b> <br/> from base/components.app.js <Header /> <Body /> <Footer /> </div> <Docs style={style} /> </div> ); } <file_sep>/packages/mendel-pipeline/src/client/base-client.js const EventEmitter = require('events').EventEmitter; const mendelConfig = require('mendel-config'); const CacheClient = require('../cache/client'); const MendelGenerators = require('./generators'); const MendelClientRegistry = require('../registry/client'); const Outlets = require('./outlets'); const DefaultShims = require('node-libs-browser'); process.title = 'Mendel Client'; class BaseMendelClient extends EventEmitter { constructor(options={}) { super(); this.debug = require('debug')('mendel:client:' + this.constructor.name); if (options.config === false) { this.config = options; } else { this.config = mendelConfig( Object.assign({defaultShim: DefaultShims}, options) ); } this._verbose = typeof options.verbose !== 'undefined' ? options.verbose : ( process.env.NODE_ENV === 'development' || typeof process.env.NODE_ENV === 'undefined' ); this.registry = new MendelClientRegistry(this.config); this.generators = new MendelGenerators(this.config, this.registry); this.outlets = new Outlets(this.config); this.synced = false; } _setupClient() { this.client = new CacheClient(this.config, this.registry); this.client.on('error', (error) => { if (error.code === 'ENOENT' || error.code === 'ECONNREFUSED') { console.error([ 'Please, use --outlet only when you have another', 'mendel process running on --watch mode.\n', ].join(' ')); process.exit(1); } }); this.client.on('sync', function() { clearTimeout(this.initSyncMessage); this.emit('ready'); this.synced = true; this.onSync.apply(this, arguments); if (this._verbose) console.log('[Mendel] Synced'); }.bind(this)); this.client.on('unsync', function() { if (this._verbose) console.log('[Mendel] File change detected. Waiting to sync again...'); // eslint-disable-line max-len this.emit('change'); this.synced = false; this.onUnsync.apply(this, arguments); }.bind(this)); } run(callback=()=>{}) { this._setupClient(); // Print a message if it does not sync within a second. if (this._verbose) { this.initSyncMessage = setTimeout(() => { this.initSyncMessage = null; console.log([ '[Mendel] Waiting for sync. Can take few moments', 'if an environment performs complex operations.', ].join(' ')); }, 3000); } // This will come after the sync listener that generates and outlets this.once('done', () => { this.exit(); callback.call(null); }); this.once('error', error => { console.log('[Mendel SEVERE] Outlet error', error); this.exit(); callback.call(null, error); }); this.client.once('error', error => { this.exit(); callback.call(null, error); }); this.client.start(); return this; } exit() { if (this.client) this.client.onExit(); } onUnsync(entryId) { // eslint-disable-line no-unused-vars } onSync() { } isReady() { return this.synced; } } module.exports = BaseMendelClient; <file_sep>/test/tree-hash-walker.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ var t = require('tap'); var MendelHashWalker = require('../packages/mendel-core/tree-hash-walker'); t.equal(MendelHashWalker().constructor, MendelHashWalker, 'constructor'); var validHash = 'bWVuZGVsAQD_AQAGH7IIQx23k7vTZFt6FgWKHiokEg'; var walker = new MendelHashWalker(validHash); t.equal(walker.error, null, 'Initialized without errors'); walker.decoded.branches = [3]; var module = {data:[null, null, null, {id:'3'}]}; t.match(walker._resolveBranch(module), { index: 3, resolved: module.data[3], }, 'pulls module based on decoded branches'); module = {data:[{id:'foo'}, {id:'bar'}]}; t.match(walker._resolveBranch(module), { index: undefined, resolved: {}, }, 'won\'t throw with wrong data'); t.match(walker.error, new Error()); t.equal(walker.error.message, 'Tree has more paths than hash', 'error message'); t.equal(walker.error.code, 'TRVRSL', 'error code'); walker.decoded.branches = [0,1,2,3,4]; walker._resolveBranch(module); t.equal(walker.error.message, 'Tree has more paths than hash', 'keep the first error'); walker = new MendelHashWalker(validHash); walker.decoded.branches = [4]; walker._resolveBranch(module); t.equal(walker.error.message, 'Hash branch not found in tree', 'different error message when different error'); var f = walker.found(); t.match(f, { error: new Error(), }, 'proper output whith error'); t.notEqual(f.hash, validHash, 'different hash when error present'); t.equal(f.error.code, 'TRVRSL', 'but same error code'); walker = new MendelHashWalker(validHash); module = {data:[null, null, null, {id:'3', index:3, sha:'99'}]}; walker.decoded.branches = [3]; walker.find(module); t.match(walker.found(), { error: new Error(), }, 'Parsed ok, but hash mismatch'); t.notEqual(f.error.code, 'HASHMISS', 'but same error code'); var stub1 = { index: 0, id: 'first', variations: ['a', 'b', 'special'], data: [{id:'a', variation:'a', sha:'ba'},{id:'b'},{id:'special'}], }; validHash = 'bWVuZGVsAQD_AQAGH7IIQx23k7vTZFt6FgWKHiokEg'; walker = new MendelHashWalker(validHash); module = {data:[null, null, null, {id:'3', index:3, sha:'99'}]}; walker.decoded.branches = [0]; walker.find(stub1); var expected = { deps: [{ id: 'a', variation: 'a', sha: 'ba', }], hash: 'bWVuZGVsAQD_AQAGH7IIQx23k7vTZFt6FgWKHiokEg', error: null, }; t.match(walker.found(), expected, 'full result matching hash'); <file_sep>/examples/full-example/bench.sh #!/bin/bash git status -sb echo "ab -n 1000 -c 1 -l http://localhost:3000/?variations=bucket_D" ab -n 1000 -c 1 -l http://localhost:3000/?variations=bucket_D <file_sep>/packages/mendel-pipeline/src/default-shims/global.js if (typeof global == 'undefined' && typeof window != 'undefined') { global = window; // eslint-disable-line } <file_sep>/examples/full-example/isomorphic/variations/bucket_D/components/dropdown.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ import React from 'react'; class Dropdown extends React.Component { render() { return ( <ul className="dropdown bucket_D"> <li>Option D one</li> <li>Option D two</li> <li>Option D three</li> </ul> ); } } export default Dropdown; <file_sep>/examples/full-example/isomorphic/variations/bucket_A/components/lazy_content.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ import React from 'react'; class Button extends React.Component { render() { return <span style={{ color: 'red' }}> Content inside lazy bucket_A </span>; } } export default Button; <file_sep>/packages/mendel-generator-prune/README.md # mendel-generator-prune This generator removes dangling files, such as files required initially and later not used because of some transformation (examples would be `requires` removed after `envify` and some CSS-in-JS dependency. It also assigns `NORMALIZED_ID` to files exposed in other bundles. `NORMALIZED_ID` is the relative path to either base or any variation. ## Example Assume that we have 2 bundles. First bundle(the main bundle) has 3 files ``` "foo.js":"1", "bar".js":"2", "foobar".js":"NORMALIZED_ID", ``` There is a second bundle(lazy) which has its own files as well as files from main bundle as dependencies. ``` "deps": { "dep1.js":"1", "dep2.js":"2", "foobar".js":"NORMALIZED_ID" } ``` Now, even if you update other files in `main` bundle and recreate this bundle, lazy bundle will always refer to `foobar.js` by it's NORMALIZED_ID. <file_sep>/packages/mendel-pipeline/src/client/build-ondemand.js const BaseClient = require('./base-client'); const Stream = require('stream'); const Bundle = require('../bundles/bundle'); class BuildOnDemand extends BaseClient { constructor(options) { super(options); this._bundles = null; this._bundleCache = new Map(); this._requests = []; } getCacheKey(bundleId, variations) { return `${bundleId}-${variations.join(':')}`; } build(bundleId, variations) { const bundle = this.config.bundles.find(({id}) => id === bundleId); if (!bundle) { throw new Error( `Could not find any bundle id ${bundleId} from mendelrc` ); } const key = this.getCacheKey(bundleId, variations); if (this._bundleCache.has(key)) { return Promise.resolve(this._bundleCache.get(key)); } return new Promise((resolve, reject) => { const request = { id: bundleId, variations, promise: {resolve, reject}, }; this._requests.push(request); if (this.synced) this._perform(); }); } isSynced() { return this.synced; } _perform() { if (!this._bundles) { // different from `this.config.bundles` which is configurations only // `this._bundles` are actual bundle // @see bundles/bundle.js this._bundles = this.generators.performAll( this.config.bundles.map(opts => new Bundle(opts)) ); } this._requests.forEach(({id, variations, promise}) => { const bundle = this._bundles.find(b => b.id === id); Promise.resolve() .then(() => this.outlets.perform([bundle], variations)) .then(([output]) => { const key = this.getCacheKey(bundle.id, variations); if (output instanceof Stream) { let data = ''; output.on('data', (d) => data += d.toString()); output.on('end', () => { this._bundleCache.set(key, data); }); } else { this._bundleCache.set(key, output); } promise.resolve(output); }) .catch(e => { promise.reject(e); throw e; }); }); this._requests = []; } onSync() { this._perform(); } onUnsync() { this._bundles = null; this._bundleCache.clear(); } } module.exports = BuildOnDemand; <file_sep>/packages/mendel-pipeline/src/step/end.js const BaseStep = require('./step'); class End extends BaseStep { constructor({registry}) { super(); this.registry = registry; } perform(entry) { this.registry.doneEntry(entry.id); this.emit('done', {entryId: entry.id}); } } module.exports = End; <file_sep>/examples/full-example/isomorphic/base/components/_test_/toolbar_test.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ import React from 'react'; // eslint-disable-line no-unused-vars import { findDOMNode } from 'react-dom'; // eslint-disable-line no-unused-vars import { renderIntoDocument, scryRenderedDOMComponentsWithTag } from 'react-addons-test-utils'; import Toolbar from '../toolbar'; import {expect} from 'chai'; describe("toolbar", function() { it("contains a button with correct label", function() { const toolbar = renderIntoDocument(<Toolbar />); const buttons = scryRenderedDOMComponentsWithTag(toolbar, 'button'); expect(findDOMNode(buttons[0]).innerText).to.equal('Button'); }); }); <file_sep>/examples/planout-example/README.md ## Planout Assignment Example This example uses [PlanOut.js](https://github.com/HubSpot/PlanOut.js), a JavaScript-based implementation of Facebook's [PlanOut](http://facebook.github.io/planout/), to provide variation assignments for Mendel. Note this should not be considered a full production implementation of experimentation with Mendel and PlanOut, but rather a simple reference example of combining the two. The example implements two layers, `layer_1` contains two variations (plus base), and `layer_2` consists of three variations (plus base). These can be seen in `/isomorphic`. ``` ├── base │   ├── components │   │   ├── app.js │   │   ├── body.js │   │   ├── docs.js │   │   ├── footer.js │   │   └── header.js │   └── main.js └── variations ├── layer_1_bucket_A │   └── components │   └── body.js ├── layer_1_bucket_B │   └── components │   └── body.js ├── layer_2_bucket_A │   └── components │   ├── footer.js │   └── header.js ├── layer_2_bucket_B │   └── components │   ├── footer.js │   └── header.js └── layer_2_bucket_C └── components ├── footer.js └── header.js ``` The script `PlanoutAssignment.js` implements a PlanOut uniform experiment and provides the assignment mechanism for these two layers. Planout uses deterministic hashing to choose assignments. This assures that the same visitorId will always get the same selection. In addition to the visitorId, Planout concatenates each parameter's name, in this case 'layer_1' or 'layer_2', with the visitorId. This assures that selections are not correlated across layers. While this example implements a simple uniform assignment, significantly more complex experimental designs can be created with PlanOut. Detailed examples and documentation can be found on the main [PlanOut](http://facebook.github.io/planout/) repo. Within this example a `uuid` is generated for each new visitor and saved to a cookie. Provided this cookie remains, PlanOut will continue to assign the same variations. PlanOut also provides logging of variation assignments. A single assignment will produce an event with the format shown below. By saving these events and passing the visitorID into your general analytics, outcomes can later be correlated with variation assignments. ``` { name: 'GenericExperiment', time: 1476884238.671, salt: 'GenericExperiment', inputs: { visitorId: '8417bb0e-d918-4807-b9a3-0339c6300d4f' }, params: { layer_1: 'layer_1_bucket_B', layer_2: 'layer_2_bucket_C' }, event: 'exposure' } ``` To get a new random assignment from Planout, either delete your cookies or add ?reset=true to your url. You may also append query parameters to request specific combinations directly from Mendel. In this example the server will not use Planout if the variations parameter is present. Note that in production you most likely do not want this feature, unless it is hidden behind some layer of internal authentication. The following is a complete list of all 12 valid permutations that can result from the two layers implemented in this example. - all from base - layer_1_bucket_A - layer_1_bucket_B - layer_2_bucket_A - layer_2_bucket_B - layer_2_bucket_C - layer_1_bucket_A, layer_2_bucket_A - layer_1_bucket_A, layer_2_bucket_B - layer_1_bucket_A, layer_2_bucket_C - layer_1_bucket_B, layer_2_bucket_A - layer_1_bucket_B, layer_2_bucket_B - layer_1_bucket_B, layer_2_bucket_C To run this example go to it's root directory and run `npm install`. For Mendel 1.x, you can run: $ npm run build $ npm run development *TBD: We should add .mendelrc_v2 file and update package.json for this example.* And view in your browser at `localhost:3000` <file_sep>/Mendel.md Mendel is a framework that acknowledge that any web application needs more than just a bundler. As application grows it will need at least one, but probably multiple of the following: 1. A/B testing bundling framework: Experimenting with different UI/UX variations is essential for building a successful, competitive application. Mendel provides a well rounded strategy to avoid [tech debt](1) and excessive bundle payload caused by experimentation. Mendel also supports multivariate/multilayer experiments and experiments can use [server-side rendering](2). 2. Many web applications need features that are contextual to certain users: [white-labeling](3), theme support and environment/settings based features can add unexpected complexity to your code base. Mendel architecture provides and easy mental model that reduce complexity and increase maintainability for such scenarios. 3. A more comprehensive feature-set bundler: Most build tools don't scale as your application grows. Mendel has specific features and a better configuration system to deal with bundle splitting rules, environment specific configuration. Incremental builds and multi-core support helps speed up development and production builds. <file_sep>/packages/mendel-pipeline/src/main.js const chalk = require('chalk'); const MendelPipelineDaemon = require('./daemon'); const MendelClient = require('./client/build-all'); class Mendel { static get Daemon() { return MendelPipelineDaemon; } static get Client() { return MendelClient; } constructor(config) { this.daemon = new Mendel.Daemon(config); this.client = new Mendel.Client(Object.assign({ verbose: false, }, config)); } run(callback) { this.daemon.run(error => { if (error) { if (error instanceof ReferenceError) { console.log(chalk.yellow([ 'Instance of Mendel daemon may be running.', 'Attemping to recycle...', ].join('\n'))); } else { console.error('Unknown daemon execution error: ', error); process.exit(1); } } this.client.run(error => { if (error) return callback(error); setImmediate(() => callback()); }); }); } onForceExit() { this.daemon.onForceExit(); } } module.exports = Mendel; <file_sep>/packages/mendel-config/src/defaults.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ module.exports = function() { const mendelEnv = process.env.MENDEL_ENV || process.env.NODE_ENV || 'development'; return { projectRoot: process.cwd(), 'base-config': { id: 'base', dir: process.cwd(), outdir: process.cwd(), }, 'build-dir': 'build', 'variation-config': { 'variation-dirs': [], variations: {}, }, 'cache-connection': { type: 'unix', // Host and port are used for TCP-based - e.g., WebSocket. host: '', port: 0, // Used for unix socket. path: '.mendelipc', }, 'environment': mendelEnv, 'route-config': { variation: '/mendel/:variations/:bundle', hash: '/mendel/:hash/:bundle', }, transforms: {}, types: { node_modules: { glob: [ /.*\/node_modules\/.*/, ], isResource: false, isBinary: false, }, }, outlets: [], generators: [], postgenerators: [], env: {}, bundles: {}, config: true, shim: { // Can pass any shim that would resolve modules differently. // For instance, you can pass "fs" and name of the package // to inject different implementation of "fs" instead of that of // the browser. // This would override "defaultShim" below. }, defaultShim: { // For Mendelv2, the default set of shim is listed in // https://github.com/webpack/node-libs-browser. }, ignores: [], // This controls whether outlet outputs to a file or a stream noout: false, // TODO re-evaluate whether we need this guy // In a large project, there are configuration/support/bootstrap code // that is not variational or should be bundled to browser. // Especially useful when the support code pulls in large dependency // that you do not want to process/transpile in all environments. // Takes (glob|path) as input. support: '', }; }; <file_sep>/packages/mendel-deps/test/js-fixtures/es6/foo/browser.js import {test} from 'glob'; <file_sep>/packages/mendel-development/falafel-util.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ function isRequire (node) { var c = node.callee; return c && node.type === 'CallExpression' && c.type === 'Identifier' && c.name === 'require' && node.arguments[0] && node.arguments[0].type === 'Literal'; } module.exports.isRequire = isRequire; <file_sep>/examples/planout-example/app.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ var ReactDOMServer = require('react-dom/server'); var express = require('express'); var logger = require('morgan'); var MendelMiddleware = require('mendel-middleware'); var uuid = require("node-uuid"); var PlanoutAssignment = require("./PlanoutAssignment"); var cookieParser = require('cookie-parser'); if (process.env.NODE_ENV !== 'production') { MendelMiddleware = require('mendel-development-middleware'); } var app = express(); app.use(logger('tiny')); app.use(MendelMiddleware()); app.set('query parser', 'simple'); app.use(cookieParser()); // set visitorId for Planout Assignment app.use(`*`, function (req, res, next) { if(req.cookies && req.cookies.visitorId && !req.query.reset){ req.visitorId = req.cookies.visitorId; } else{ req.visitorId = uuid.v4(); // create new userId } // set or reset the cookie res.cookie( 'visitorId', req.visitorId, { httpOnly: false, maxAge: 3600 * 1000 * 24 * 365 * 2 } ) next(); }); app.get('/', function(req, res) { var variations = []; if(req.query.variations){ variations = (req.query.variations||'').trim() .split(',').filter(Boolean); } else{ var assignments = new PlanoutAssignment({ visitorId: req.visitorId }).getParams(); variations = [assignments.layer_1, assignments.layer_2].filter(Boolean); } var serverRender = req.query.ssr !== 'false' && req.mendel.isSsrReady(); var optionalMarkup = ""; if (serverRender) { // To improve ssr performance, you need to pass // array of bundle ids you only need for ssr rendering var resolver = req.mendel.resolver(['main'], variations); var Main = resolver.require('main.js'); optionalMarkup = ReactDOMServer.renderToString(Main()) } var html = [ '<!DOCTYPE html>', '<html><head></head><body>', '<div id="main">'+optionalMarkup+'</div>', bundle(req, 'vendor', variations), bundle(req, 'main', variations), '</body></html>' ].join('\n'); res.send(html); res.end(); }); function bundle(req, bundle, variations) { var url = req.mendel.getURL(bundle, variations); return '<script src="'+url+'"></script>'; } module.exports = app; <file_sep>/packages/mendel-pipeline/src/cache/server.js /* Copyright 2015-2016, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ const network = require('./network'); const EventEmitter = require('events').EventEmitter; const debug = require('debug')('mendel:net:server'); const error = require('debug')('mendel:net:server:error'); const verbose = require('debug')('verbose:mendel:net:server'); class CacheServer extends EventEmitter { constructor(config, cacheManager) { super(); this.config = config; this._types = config.types; this.clients = []; this.cacheManager = cacheManager; this.initCache(); network.getServer(config.cacheConnection) .then(server => { this.server = server; this.initServer(); debug('listening', config.cacheConnection); this.emit('ready'); }).catch(err => { this.emit('error', err); debug('Cache server could not come up', err); }); } isReady() { return !!this.server; } onExit() { if (this.server) this.server.close(); } onForceExit() { if (this.server) this.server.close(); } send(client, data) { if (client.destroyed) return; try { client.send(data); } catch (e) { console.log(e.stack); } } initServer() { this.server.on('error', (e) => { console.log('Mendel Server Errored'); console.log(e.stack); process.exit(1); }); this.server.on('listening', () => this.emit('ready')); this.server.on('connection', (client) => { debug(`[${this.clients.length}] A client connected`); this.clients.push(client); client.on('close', () => { this.clients.splice(this.clients.indexOf(client), 1); debug(`[${this.clients.length}] A client disconnected`); }); client.on('error', () => {}); client.on('data', (data) => { try { data = typeof data === 'object' ? data : JSON.parse(data); } catch(e) { error(e); } if (!data || !data.type) return; switch (data.type) { case 'bootstrap': { this.emit('environmentRequested', data.environment); client.environment = data.environment; this.bootstrap(client); break; } default: return; } this.send(client, data); }); }); } initCache() { this.cacheManager.on('doneEntry', (cache, entry) => { const size = cache.size(); this.clients .filter(c => c.environment === cache.environment) .forEach(c => this._sendEntry(c, size, entry)); }); this.cacheManager.on('entryRemoved', (cache, entryId) => { this.clients .filter(client => client.environment === cache.environment) .forEach(client => this._signalRemoval(client, entryId)); }); this.cacheManager.on('entryErrored', (cache, desc) => { this.clients .filter(client => client.environment === cache.environment) .forEach(client => this._signalError(client, desc)); }); } bootstrap(client) { const cache = this.cacheManager.getCache(client.environment); cache.entries() .filter(entry => entry.done) .forEach(entry => this._sendEntry(client, cache.size(), entry)); } serializeEntry(entry) { const { deps, source, map, type, runtime, rawSource, id, normalizedId, } = entry; let variation = this.getVariationForEntry(entry); if (!variation) { variation = this.config.variationConfig.baseVariation; } variation = variation.chain[0]; return { id, normalizedId, // Metadata variation, type, runtime, // Dependency information // FIXME currently only puts dependencies in browser runtime deps, // Important source data source, map, rawSource, }; } getVariationForEntry(entry) { const variations = this.config.variationConfig.variations; return variations.find(({id}) => id === entry.variation); } _sendEntry(client, size, entry) { this.send(client, { totalEntries: size, type: 'addEntry', entry: this.serializeEntry(entry), }); verbose('sent', entry.id); } _signalRemoval(client, id) { const cache = this.cacheManager.getCache(client.environment); this.send(client, { totalEntries: cache.size(), type: 'removeEntry', id, }); } _signalError(client, {id, error}) { this.send(client, { error, type: 'errorEntry', id, }); } } module.exports = CacheServer; <file_sep>/packages/mendel-generator-prune/index.js const debug = require('debug')('mendel:generator:prune'); // First argument is not needed; just to make it look like normal generator API function pruneModules(bundle, doneBundles, registry, generator) { const {groups} = generator.options; groups.forEach(group => { const bundles = group.map(bundleId => { return doneBundles.find(b => b.id === bundleId); }).filter(Boolean); pruneGroup(bundles); }); } function pruneGroup(bundles) { const exposeNormToExposeId = new Map(); const allNorms = new Set(); bundles.forEach(({entries}) => { entries.forEach(entry => { const norm = entry.normalizedId; allNorms.add(norm); if (entry.expose && !exposeNormToExposeId.has(entry.expose)) { exposeNormToExposeId.set(entry.expose, norm); } }); }); bundles.forEach(({entries}) => { Array.from(entries.entries()).forEach(([key, entry]) => { const clone = Object.assign({}, entry); clone.deps = JSON.parse(JSON.stringify(entry.deps)); entries.set(key, clone); // Prune dependencies Object.keys(clone.deps).forEach(literal => { const deps = clone.deps[literal]; const remove = Object.keys(deps).every(runtime => { const dep = deps[runtime]; return !allNorms.has(dep); }); if (remove) { debug('[WARN] Removing ', literal, 'from', entry.id); delete clone.deps[literal]; } }); // Remap externals if (exposeNormToExposeId.has(entry.expose)) { clone.expose = exposeNormToExposeId.get(entry.expose); } Object.keys(clone.deps).forEach(literal => { const deps = clone.deps[literal]; Object.keys(deps).forEach(runtime => { const dep = deps[runtime]; if (exposeNormToExposeId.has(dep)) { deps[runtime] = exposeNormToExposeId.get(dep); } }); }); }); }); } module.exports = pruneModules; <file_sep>/test/app-samples/2/src/base/late.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ var complicator = require('./complicator'); module.exports = function() { return complicator('asyncronous'); }; <file_sep>/packages/mendel-resolver/test/index.js const test = require('tap').test; const Resolver = require('../'); const VariationalResolver = require('../variational-resolver'); const fs = require('fs'); const path = require('path'); const basePath = path.resolve(__dirname, './fixtures'); ['basic', 'package-json'].forEach(dir => { const dirPath = path.resolve(basePath, dir); test('resolve ' + dir, function(t) { const config = { extensions: ['.js'], runtimes: ['main', 'browser'], basedir: dirPath, cwd: __dirname, }; try { Object.assign(config, JSON.parse(fs.readFileSync(path.resolve(dirPath, 'config.json')))); } catch (e) { // Eslint hates empty block } return new Resolver(config).resolve('.') .then((resolved) => { const expected = JSON.parse(fs.readFileSync(path.resolve(dirPath, 'expect.json'))); t.same(resolved, expected); t.end(); }); }); }); test('resolve node-modules', function(t) { const dir = 'node-modules'; const dirPath = path.resolve(basePath, dir); const config = { extensions: ['.js'], runtimes: ['main', 'browser'], basedir: dirPath, cwd: __dirname, }; try { Object.assign(config, JSON.parse(fs.readFileSync(path.resolve(dirPath, 'config.json')))); } catch (e) { // Eslint hates empty block } return new Resolver(config).resolve('mendel-config') .then((resolved) => { const expected = JSON.parse(fs.readFileSync(path.resolve(dirPath, 'expect.json'))); t.same(resolved, expected); t.end(); }); }); ['easy-variational', 'hard-variational'].forEach(dir => { test('variational ' + dir, function(t) { const dirPath = path.resolve(basePath, dir); const config = { extensions: ['.js'], runtimes: ['main', 'browser'], basedir: dirPath, cwd: __dirname, }; try { Object.assign(config, JSON.parse(fs.readFileSync(path.resolve(dirPath, 'config.json')))); } catch (e) { // Eslint hates empty block } return new VariationalResolver(config).resolve('./variations/var1') .then((resolved) => { const expected = JSON.parse(fs.readFileSync(path.resolve(dirPath, 'expect.json'))); t.same(resolved, expected); t.end(); }); }); }); <file_sep>/test/outlet-css.js const path = require('path'); const test = require('tap').test; const rimraf = require('rimraf'); const fs = require('fs'); const MendelV2 = require('../packages/mendel-pipeline'); const appPath = path.join(__dirname, './css-samples'); const buildPath = path.join(appPath, 'build'); rimraf.sync(buildPath); test('mendel-outlet-css sanity test', function (t) { t.plan(4); process.chdir(appPath); process.env.MENDELRC = '.mendelrc'; const mendel = new MendelV2(); mendel.run(function(error) { if (error) { console.error(error); return t.bailout('should create manifest but failed'); } const css = fs.readFileSync(path.join(buildPath, 'main.css'), 'utf8'); t.doesNotHave(css, 'background: red'); t.include(css, 'padding: 0'); t.include(css, 'background: blue'); // From LESS t.include(css, 'background: #1111ff'); }); }); <file_sep>/packages/mendel-pipeline/src/registry/pipeline.js const EventEmitter = require('events').EventEmitter; const verbose = require('debug')('verbose:mendel:registry'); class MendelRegistry extends EventEmitter { constructor(config, cache) { super(); this._mendelCache = cache; // Parser can map a type to another type this._parserTypeConversion = new Map(); const {types, transforms} = config; this._transforms = transforms; this._types = types; this._types.forEach(type => { if (!type.parser || !type.parserToType) return; // TODO better cycle detection: cannot have cycle if (type.parserToType === type.name) return; this._parserTypeConversion.set(type.name, type.parserToType); }); } emit(eventName, entry) { if (entry && entry.id) { verbose(eventName, entry.id); } else if(entry) { verbose(eventName, entry); } else { verbose(eventName); } super.emit.apply(this, arguments); } addEntry(filePath) { this._mendelCache.addEntry(filePath); } removeEntry(filePath) { if (!this._mendelCache.hasEntry(filePath)) return; this._mendelCache.removeEntry(filePath); } getEntry(filePath) { return this._mendelCache.getEntry(filePath); } hasEntry(filePath) { return this._mendelCache.hasEntry(filePath); } addSource({id, source, deps, map}) { if (!this._mendelCache.hasEntry(id)) this._mendelCache.addEntry(id); this._mendelCache.setSource(id, source, deps, map); } addTransformedSource(obj) { this.addSource(obj); } invalidateDepedencies(filePath) { // TODO modify entries and its deps recursively if (!this._mendelCache.hasEntry(filePath)) return; } doneEntry(filePath, environment) { if (!this._mendelCache.hasEntry(filePath)) return; this._mendelCache.doneEntry(filePath, environment); } setEntryType(entryId, newType) { return this._mendelCache.setEntryType(entryId, newType); } /** * @param {String} norm normalizedId * @param {Function} dependencyGetter has to return correct normalizedId of dependency * based on environemnt, transform ids, and settings (browser/main). * @returns {Array<Entry[]>} In case a dependency have more than one variation * the Entry[] will have length greater than 1. */ getDependencyGraph(norm, dependencyGetter) { const visitedEntries = new Map(); const unvisitedNorms = [norm]; while (unvisitedNorms.length) { const normId = unvisitedNorms.shift(); if (visitedEntries.has(normId)) continue; const entryIds = this._mendelCache.getEntriesByNormId(normId); if (!entryIds) continue; const entries = entryIds .map(entryId => this.getEntry(entryId)) .filter(Boolean); entries.forEach(entry => { const depNorms = dependencyGetter(entry); Array.prototype.push.apply(unvisitedNorms, depNorms); }); visitedEntries.set(normId, entries); } return Array.from(visitedEntries.values()); } } module.exports = MendelRegistry; <file_sep>/packages/mendel-config/README.md # Mendel Config This is an internal package that helps Mendel normalize configuration defaults, on `.mendelrc` or on `package.json`. It is used by many Mendel packages to make sure all packages use the same defaults and same merging logic. ## API ```js var configParser = require('mendel-config'); // passing no options will lookup `.mendelrc` or `package.json` in the current // folder and parent folders recursively. If not found returns default config. var config = configParser(); // passing `basedir` as string or as property will make mendel lookup // `.mendelrc` or `package.json` in the target folder instead. var config = configParser('./sub/folder/config'); // which is equivalent to: var config = configParser({ basedir: './sub/folder/config' }); // programmatic config only var config = configParser({ config: false, // prevent looking for `.mendelrc` or `package.json` // any other valid config }); // Lookup `.mendelrc` or `package.json` and override a few params var config = configParser({ // any valid config, except config:false }); ``` Configuration parsing happens in 3 steps: #### 1. Merging by precedence: Configuration precedence is, from order to strongest to weakest: 1. Passing configuration as an JavaScript object 2. Configuration on `.mendelrc` or `package.json` 3. Mendel defaults The only exception is `basedir`. `basedir` has different meanings depending on where you declare it: 1. If `basedir` is passed programmatically it is meant as a configuration lookup folder 2. If any of `.mendelrc` or `package.json` is found, basedir is forced to be the folder that contains the config file, even if you provide one as property of the configuration object. 3. All other path entries that are not absolute will be relative to `basedir` ### 2. Merging by environment Either `process.env.MENDEL_ENV` or `process.env.NODE_ENV` values can be used to configure overrides on `.mendelrc`. ### 3. Resolving relative paths After parsing and merging all the configurations a number of path properties will be resolved relative to basedir or their "parent" configuration, for example `bundlesoutdir` is relative to `outdir` which is in place relative to `basedir`. Please refer to `.mendelrc` file configuration documentation to a full list. ### 4. Parsing bundles In `.mendelrc` or `package.json` the bundles entry is an object, we will transform bundles into an array and lastly the following arrays will be flattened: `entries`, `require`, `external`, `exclude`, `ignore`. Flattening is useful to use YAML references to manipulate the file lists. For example, the `logged_in_bundle` bellow will have all files from `vendor` and from `main`, since arrays are flattened: ```yml # Mendel v2 build-dir: ./build # Base/default variation configuration base-config: id: base dir: ./src/master variation-config: variation-dirs: - ./src/environments - ./src/settings - ./src/experiments - ./src/themes # dir names should be unique across all roots or mendel throws variations: # id of variation button_color: # name of the folder - blue_button route-config: variation: /mendel/:variations/:bundle hash: /mendel/:hash/:bundle transforms: # a list of all available transforms for all envs and types babelify-dev: plugin: mendel-babelify options: plugins: - - react-intl - messagesDir: ./tmp/strings/ enforceDescriptions: true babelify-prod: plugin: mendel-babelify options: plugins: - react-intl-remove-description - transform-react-remove-prop-types - - react-intl - messagesDir: ./tmp/strings/ enforceDescriptions: true custom-transform: plugin: ./transforms/custom.js envify-dev: options: NODE_ENV: development envify-prod: options: NODE_ENV: production minify: plugin: mendel-uglify-js coverage: plugin: mendel-istanbul post-css: plugin: mendel-post-css options: foo: bar # auto-prefixex, rtl-css types: css: transforms: - post-css outlet: plugin: mendel-css-pack javascript: outlet: plugin: mendel-bundle-browser-pack transforms: - envify-dev - babelify-dev extensions: - .js - .json - .jsx node_modules: transforms: - envify-dev env: production: types: javascript: outlet: plugin: mendel-bundle-rollup transforms: - envify-prod - babelify-dev - minify node_modules: - envify-prod - minify unit-test: types: javascript: transforms: - envify-dev - babelify-dev - coverage # Order is relevant. E.g., # if extract-bundles comes first, we can generate lazy bundle specific css # if css comes first, css file includes rules from files on lazy bundles # if node-modules is last, we can use lazy-bundle as optional input (see below) generators: # AKA graph transforms - or graph operations - id: extract-bundles plugin: mendel-extract-bundles - id: node-modules-generator plugin: mendel-extract-node-modules # "outfile" is optional and only needed for single layer generation bundles: main: outfile: app.js entries: - /apps/main lazy-group-1: outfile: lazy1.js generator: extract-bundles from: main extract-entries: - /apps/lazy deps: outfile: vendor.js generator: node-modules-generator all-bundles: true # expects only 1 bundle to apply this generator, or throws # look for node_modules in every other bundle # alternative configuration # if the array don't contain lazy, the node_modules only used on lazy would # be kept on lazy_bundle # bundles: # - mail_app # - compose_app css: outfile: app.css generator: atomic-css-generator entries: - /apps/main ``` <file_sep>/scripts/update-all.js #!/usr/bin/env node const {execSync} = require('child_process'); const packages = require('./mendel-packages'); const KEYWORDS = ['major', 'minor', 'patch', 'premajor', 'preminor', 'prepatch', 'prerelease']; const VERSION_REGEX = /^\d+\.\d+\.\d+(\.\S+|$)/; const version = process.argv[2]; if (typeof version === 'undefined') { throw new Error( 'Requires a version or one of the keywords (' + KEYWORDS.join() + ')' ); } else if (KEYWORDS.indexOf(version) < 0 && !VERSION_REGEX.test(version)) { throw new Error( 'Requires a version to conform to "[0-9]+.[0-9]+.[0-9]+".' ); } const origCwd = process.cwd(); packages.forEach(pkgPath => { process.chdir(pkgPath); try { console.log( pkgPath, execSync('npm version ' + version).toString().trim() ); } catch (e) { /* DO NOTHING */ } process.chdir(origCwd); }); <file_sep>/test/require-transform.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ var t = require('tap'); var requireTransform = require('../packages/mendel-development/require-transform'); var wrapper = requireTransform.wrapper; var variationDirs = ['variation1', 'variation2', 'base']; var src = [ 'var foo = require(\'foo\');', 'var bar = require(\'some/dir/variation1/bar\');', 'var baz = require(\'some/dir/variation2/baz\');', 'var qux = require(\'some/dir/base/qux\');', ].join('\n'); var mendelifiedModules = ['bar', 'baz', 'qux']; var out = requireTransform('./', src, variationDirs, false); mendelifiedModules.forEach(function(mod) { t.match(out, '__mendel_require__(\'' + mod + '\')', 'mendelified require'); t.notMatch(out, 'require(\'' + mod + '\')', 'node require'); }); t.match(out, 'require(\'foo\')', 'node require'); t.notMatch(out, '__mendel_require__(\'foo\')', 'mendelified require'); t.equal(out.indexOf(wrapper[0]), -1, 'wrapper prelude not present'); t.equal(out.indexOf(wrapper[1]), -1, 'wrapper epilogue not present'); out = requireTransform('./', src, variationDirs, true); t.equal(out.indexOf(wrapper[0]), 0, 'wrapper prelude pos'); t.equal(out.indexOf(wrapper[1]), out.length - wrapper[1].length, 'wrapper epilogue pos'); <file_sep>/examples/planout-example/isomorphic/base/components/docs.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. Contributed by <NAME> <<EMAIL>> See the accompanying LICENSE file for terms. */ import React from 'react'; export default ({ style }) => { return ( <div style={style}> To get a new random assignment from Planout, either delete your cookies or add <a href="/?reset=true">?reset=true</a> to your url.<br/><br/> You may also append query parameters to request specific combinations directly from Mendel. In this example the server will not use Planout if the variations parameter is present. Note that in production you most likely do not want this feature, unless it is hidden behind some layer of internal authentication. <br/><br/> The following is a complete list of all 12 valid combinations.<br/><br/> <a href="/?variations=">all from base</a><br/> <a href="/?variations=layer_1_bucket_A">layer_1_bucket_A</a><br/> <a href="/?variations=layer_1_bucket_B">layer_1_bucket_B</a><br/> <a href="/?variations=layer_2_bucket_A">layer_2_bucket_A</a><br/> <a href="/?variations=layer_2_bucket_B">layer_2_bucket_B</a><br/> <a href="/?variations=layer_2_bucket_C">layer_2_bucket_C</a><br/> <a href="/?variations=layer_1_bucket_A,layer_2_bucket_A">layer_1_bucket_A, layer_2_bucket_A</a><br/> <a href="/?variations=layer_1_bucket_A,layer_2_bucket_B">layer_1_bucket_A, layer_2_bucket_B</a><br/> <a href="/?variations=layer_1_bucket_A,layer_2_bucket_C">layer_1_bucket_A, layer_2_bucket_C</a><br/> <a href="/?variations=layer_1_bucket_B,layer_2_bucket_A">layer_1_bucket_B, layer_2_bucket_A</a><br/> <a href="/?variations=layer_1_bucket_B,layer_2_bucket_B">layer_1_bucket_B, layer_2_bucket_B</a><br/> <a href="/?variations=layer_1_bucket_B,layer_2_bucket_C">layer_1_bucket_B, layer_2_bucket_C</a><br/> </div> ); } <file_sep>/examples/full-example/isomorphic/variations/bucket_D/components/lazy.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ import React from 'react'; import Button from './button'; class Lazy extends React.Component { render() { return ( <p> Lazy (on bucket_D) Content with <Button>Lazy Button</Button> </p> ); } } export default Lazy; <file_sep>/test/app-samples/1/run.sh #!/bin/bash if [ -d build/ ] then rm -rf build/ fi if [ -d build-requirify/ ] then rm -rf build-requirify/ fi mkdir -p build mkdir -p build-requirify ../../../node_modules/.bin/browserify \ app/index.js -p ../../../packages/mendel-browserify \ -p ../../../packages/mendel-requirify \ -o build/app.js <file_sep>/test/mendel-loader.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ var path = require('path'); var temp = require('temp'); var test = require('tap').test; var Module = require('module'); var browserify = require('browserify'); var mendelify = require('../packages/mendel-browserify'); var requirify = require('../packages/mendel-requirify'); var Tree = require('../packages/mendel-core/trees.js'); var Loader = require('../packages/mendel-loader'); var srcDir = path.resolve(__dirname, './app-samples/1'); var buildDir = temp.mkdirSync('mendel-loader'); var mountDir = path.join(buildDir, 'server'); test('mendel-loader-server', function(t){ t.plan(12); temp.track(); var b = browserify({ entries: [ path.join(srcDir, 'app/index.js'), path.join(srcDir, 'app/throws.js'), ], outfile: path.join(buildDir, 'app.js'), basedir: srcDir, }); b.plugin(mendelify, { outdir: buildDir, }); b.plugin(requirify, { outdir: mountDir, }); b.bundle(function(err) { if (err) { return temp.cleanup(function() { t.fail(err.message || err); }); } //TODO: Remove setTimeout once mendel-browserify exposes its stream events. setTimeout(function() { var tree = new Tree({ basedir: srcDir, outdir: buildDir, serveroutdir: 'server', }); var loader = new Loader(tree); var inputs = [{ variations: ['test_B'], expect: 7, }, { variations: ['test_C'], expect: 11, }, { variations: ['test_B', 'test_C'], expect: 7, }, { variations: ['test_C', 'test_B'], expect: 7, }]; inputs.forEach(function (i) { var resolver = loader.resolver(['app'], tree.variationsAndChains(i.variations).lookupChains); var variation = i.variations.join(','); var someNumber = resolver.require('some-number.js'); t.equal(someNumber(), i.expect, 'some-number.js ' + variation + ' variation'); var numberList = resolver.require('number-list.js'); t.equal(numberList()[0], i.expect, 'number-list.js ' + variation + ' variation'); t.throws(function() { var throwyFile = resolver.require('throws.js'); // eslint-disable-line no-unused-vars }, { name: 'Error', message: 'Intentional error', }); }); temp.cleanup(function() { t.end(); }); }, 1000); }); }); test('mendel-loader-server-syntax-error', function(t){ t.plan(2); var prevDir = process.cwd(); process.chdir(srcDir); try { var tree = new Tree({ basedir: srcDir, outdir: buildDir, serveroutdir: 'server', }); // test without 'new' var loader = Loader(tree); var resolver = loader.resolver(['app'], tree.variationsAndChains(['test_B']).lookupChains); var invalidFile = path.join(srcDir, 'app/syntax-error.js'); t.throws(function() { resolver.require(invalidFile); }, { name: 'ReferenceError', message: 'yes is not defined', }); t.ok(Module._cache[invalidFile] === undefined); } finally { process.chdir(prevDir); t.end(); } }); <file_sep>/packages/mendel-development/mendelify-transform-stream.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ var nodePath = require('path'); var shasum = require('shasum'); var through = require('through2'); var variationMatches = require('./variation-matches'); var mendelifyRequireTransform = require('./mendelify-require-transform'); function mendelifyTransformStream(variations, bundle) { var externals = bundle._external; return through.obj(function mendelify(row, enc, next) { var avoidMendelifyRow = avoidMendelify(row.file); if (!avoidMendelifyRow) { var match = variationMatches(variations, row.file); if (match) { // Remove variations of externals from bundle if (someArrayItemEndsWith(externals, match.file)) { return next(); } // accept file and trasform for variation row.id = match.file; row.variation = match.dir; } } row.id = relativePath(row.id, bundle); if (typeof row.expose === 'string') { row.expose = relativePath( pathOrVariationMatch(row.expose, variations), bundle ); } Object.keys(row.deps).forEach(function (key) { var value = row.deps[key]; delete row.deps[key]; var newKey = key; var newValue = value; if (!avoidMendelify(value) || shouldExternalize(externals, key)) { newKey = keyValue(key, variations, bundle); } newValue = depsValue(value, newKey, variations, bundle); row.deps[newKey] = relativePath(newValue, bundle); }); row.rawSource = row.source; if (!avoidMendelifyRow) { row.source = mendelifyRequireTransform( row.file, row.source, function(requirePath) { return keyValue(requirePath, variations, bundle); } ); } row.sha = shasum(row.source); this.push(row); next(); }); } function keyValue(key, variations, bundle) { return relativePath(pathOrVariationMatch(key, variations), bundle); } function avoidMendelify(file) { var isExternal = file === false; var isNodeModule = -1 !== (file||'').indexOf("node_modules"); return isExternal || isNodeModule; } function pathOrVariationMatch(path, variations) { var match = variationMatches(variations, path); if (match) { return match.file; } return path; } function relativePath(filePath, bundle) { var basedir = bundle._options.basedir; var result = filePath; if (typeof filePath === 'string' && filePath.indexOf(basedir) !== -1) { result = nodePath.relative(basedir, filePath); } return relativeToNodeModules(result); } function relativeToNodeModules(filePath) { if (typeof filePath === 'string') { var index = filePath.indexOf('node_modules/'); if (index >= 0) { return filePath.slice(index); } } return filePath; } function depsValue(path, matchFile, variations, bundle) { if (typeof path !== 'string') { return path; } var expose = bundle._expose; var externals = bundle._external; var exposedModule = exposeKey(expose, path); if (exposedModule) { return pathOrVariationMatch(exposedModule, variations); } // remove externals from deps if (shouldExternalize(externals, matchFile)) { return false; } return pathOrVariationMatch(path, variations); } function shouldExternalize(externals, file) { return someArrayItemEndsWith(externals, file); } function someArrayItemEndsWith(stringArray, partialString) { for (var i = 0; i < stringArray.length; i++) { var position = stringArray[i].indexOf(partialString); if ( position >= 0 && position === stringArray[i].length - partialString.length ) { return true; } } return false; } function exposeKey(expose, file) { var exposedModule = false; Object.keys(expose).forEach(function(key) { var value = expose[key]; if (file === value) { exposedModule = key; } }); return exposedModule; } module.exports = mendelifyTransformStream; <file_sep>/packages/mendel-manifest-uglify/manifest-uglify.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ var UglifyJS = require("uglify-js"); var debug = require("debug")('mendel-manifest-uglify'); module.exports = manifestUglify; function manifestUglify(manifests, options, next) { var optBundles = [].concat(options.bundles).filter(Boolean); var uglifyOptions = Object.assign({}, options.uglifyOptions, {fromString: true}); function whichManifests(manifest) { // default to all bundles if (optBundles.length === 0) { return true; } return optBundles.indexOf(manifest) >= 0; } Object.keys(manifests).filter(whichManifests).forEach(function(name) { var manifest = manifests[name]; manifest.bundles.forEach(function(module) { module.data.forEach(function(variation) { var result = UglifyJS.minify( variation.source, Object.assign({ root: options.mendelConfig ? options.mendelConfig.basedir : '', }, uglifyOptions, { file: variation.file, sourceMaps: false, // TODO: sourcemaps support }) ); debug([ variation.id.replace(/^.*node_modules\//, ''), variation.source.length, '->', result.code.length, 'bytes' ].join(' ')); variation.source = result.code; }); }); }); next(manifests); } <file_sep>/test/extract-samples/app/util.js /* Copyright 2016, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ module.exports = { isArray: function isArray(obj) { return Array.isArray(obj); }, }; <file_sep>/packages/mendel-core/trees.js /* Copyright 2015, Yahoo Inc. Designed by <NAME> Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ var path = require('path'); var parseConfig = require('mendel-config'); var MendelVariationWalker = require('./tree-variation-walker'); var MendelServerVariationWalker = require('./tree-variation-walker-server'); var MendelHashWalker = require('./tree-hash-walker'); function MendelTrees(opts) { if (!(this instanceof MendelTrees)) { return new MendelTrees(opts); } var config = parseConfig(opts); this.config = config; this.variations = config.variationConfig.variations; this._loadBundles(); this.ssrOutlet = this.config.outlets.find(outletConfig => { return outletConfig._plugin === 'mendel-outlet-server-side-render'; }); if (this.ssrOutlet) { this.ssrBundle = this.config.bundles.find(bundleConfig => { return bundleConfig.outlet === this.ssrOutlet.id; }); } } MendelTrees.prototype.findTreeForVariations = function(bundle, lookupChains) { var finder = new MendelVariationWalker(lookupChains, this.config.baseConfig.id); this._walkTree(bundle, finder); return finder.found(); }; MendelTrees.prototype.findServerVariationMap = function(bundles, lookupChains) { if (!this.ssrBundle) throw new Error([ 'For a server-side render, you must use', '"mendel-outlet-server-side-render"', ].join(' ')); var base = this.config.baseConfig.dir; var finder = new MendelServerVariationWalker(lookupChains, base); this._walkTree(this.ssrBundle.id, finder); const variationMap = finder.found(); return variationMap; }; MendelTrees.prototype.findTreeForHash = function(bundle, hash) { var finder = new MendelHashWalker(hash); this._walkTree(bundle, finder); return finder.found(); }; MendelTrees.prototype._loadBundles = function() { var self = this; this.bundles = {}; var confBundles = self.config.bundles; confBundles .filter(bundle => bundle.manifest) .forEach(function(bundle) { var bundlePath = bundle.manifest; try { self.bundles[bundle.id] = require(path.resolve(bundlePath)); } catch (error) { var newError = new Error(); newError.code = error.code; if (error.code === 'MODULE_NOT_FOUND' || error.code === 'ENOENT') { newError.message = 'Could not find "' + bundle.id + '" bundle at path '+ bundlePath; } else { newError.message = 'Invalid bundle file at path '+ bundle.manifest; } throw newError; } }); }; MendelTrees.prototype._walkTree = function(bundle, finder) { var tree = this.bundles[bundle]; for (var i = 0; i < tree.bundles.length; i++) { var module = tree.bundles[i]; if (module.entry || module.expose) { walk(tree, module, finder); } } }; MendelTrees.prototype.variationsAndChains = function(lookFor) { var lookupChains = []; var matchingVariations = []; // perf: for loop instead of forEach for (var i = 0; i < this.variations.length; i++) { var variation = this.variations[i]; if (-1 !== lookFor.indexOf(variation.id)) { matchingVariations.push(variation.id); var lookupChain = []; for (var j = 0; j < variation.chain.length; j++) { var lookupVar = variation.chain[j]; if (lookupVar !== this.config.basetree) { lookupChain.push(lookupVar); } } lookupChains.push(lookupChain); } } matchingVariations.push(this.config.baseConfig.id); lookupChains.push([this.config.baseConfig.dir]); return { lookupChains: lookupChains, matchingVariations: matchingVariations, }; }; function walk(tree, module, pathFinder, _visited) { _visited = _visited || []; var dep = pathFinder.find(module); // perf: no hasOwnProperty, it is a JSON, lets shave miliseconds for (var key in dep.deps) { var index = tree.indexes[dep.deps[key]]; var subdep = tree.bundles[index]; if (subdep && !_visited[index]) { _visited[index] = true; // avoids infinite loop in circular deps walk(tree, subdep, pathFinder, _visited); } } } module.exports = MendelTrees; <file_sep>/packages/mendel-pipeline/src/transformer/index.js /** * Independent/Isolated file transform */ const MultiProcessMaster = require('../multi-process/base-master'); const path = require('path'); const debug = require('debug')('mendel:transformer:master'); /** * Knows how to do all kinds of trasnforms in parallel way */ class TransformManager extends MultiProcessMaster { constructor({transforms}) { super(path.join(__dirname, 'worker.js'), {name: 'transforms'}); this._transforming = []; this._transforms = new Map(); transforms.forEach(transform => { this._transforms.set(transform.id, transform); }); } addTransform(transform) { this._transforms.set(transform.id, transform); } /** * @override */ subscribe() { return {}; } transform(filename, transformIds, source, map) { debug(`Transforming "${filename}" with [${transformIds}]`); const transforms = transformIds.map(id => this._transforms.get(id)); const existing = this._transforming.find(exist => { return filename === exist.filename && transforms.every((transform, index) => { return transform === exist.transforms[index]; }); }); if (!transforms.length) return Promise.resolve({source, map}); if (existing) { return new Promise((resolve, reject) => { existing.additional.push({resolve, reject}); }); } const descriptor = {filename, transforms, additional: []}; return this.dispatchJob({ transforms, filename, source, map, }).then(result => { const jobInd = this._transforming.findIndex(t => t === descriptor); this._transforming.splice(jobInd, 1); descriptor.additional.forEach(({resolve}) => resolve(result)); return result; }).catch(error => { const jobInd = this._transforming.findIndex(t => t === descriptor); this._transforming.splice(jobInd, 1); descriptor.additional.forEach(({reject}) => { reject(error); }); throw error; }); } } module.exports = TransformManager; <file_sep>/test/app-samples/2/src/base/complicator.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ module.exports = function(easy) { var extra = (easy[easy.length-1] === 'l') ? '' : 'l'; return easy + extra + 'ly'; }; <file_sep>/examples/full-example/isomorphic/variations/bucket_A/components/button.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ import React from 'react'; var count = 0; class Button extends React.Component { render() { return ( <button {...this.props}> {this.props.children} A#{++count} </button> ); } } export default Button; <file_sep>/packages/mendel-development/validate-manifest.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ var path = require('path'); var fs = require('fs'); var tmp = require('tmp'); module.exports = validateManifest; function validateManifest(manifest, originalPath, stepName) { var errors = []; var requires = /require\(['"](.*?)['"]\)/g; var multilineComments = /\/\*(?:\n|.)*\*\//gm; var endOfLineComments = /\/\/\*.*/g; manifest.bundles.forEach(function(bundle) { bundle.data.forEach(function(row) { var depNames = Object.keys(row.deps); // Find require() on source that don't have a key in deps var noCommentsSource = row.source .replace(multilineComments, '') .replace(endOfLineComments, ''); var match; while ((match = requires.exec(noCommentsSource)) !== null) { if (-1 === depNames.indexOf(match[1])) { errors.push( "can't require '" + match[1] + "' from " + row.id ); } } // Find dependencies not included in the manifest depNames.forEach(function(key) { var externalModule = row.deps[key] === false; var existsInManifest = row.deps[key] in manifest.indexes; if (!externalModule && !existsInManifest) { errors.push( key + ":" + row.deps[key] + ' missing from '+ bundle.id); } }); }); }); if (errors.length) { console.log('\n'+stepName+' manifest errors: \n'); errors.forEach(function(log){ console.log(' ' + log); }); var tempDir = tmp.dirSync().name; var filename = 'debug.' + path.parse(originalPath).base; var destination = path.resolve(tempDir, filename); fs.writeFileSync(destination, JSON.stringify(manifest, null, 2)); console.log('\n' + destination + ' written \n'); var e = new Error('Invalid manifest'); e.code = "INVALID_MANIFEST"; throw e; } } <file_sep>/packages/mendel-generator-node-modules/README.md # mendel-generator-node-modules Mendel-generator that creates special bundle with only node_modules from a bundle. In a large application that changes rapidly, it is preferable to bifurcate a bundle into multiple bundles. When employing the strategy, it is preferable to put all node_modules into one bundle so the bundle caches better (unless you upgrade dependencies often). <file_sep>/test/extract-samples/app/throws.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ module.exports = (function() { throw new Error('Intentional error'); })(); <file_sep>/packages/mendel-core/tree-walker.js /* Copyright 2015, Yahoo Inc. Designed by <NAME> Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ var TreeSerialiser = require('./tree-serialiser'); function MendelWalker(_lookupChains, _base, _hash) { if (!(this instanceof MendelWalker)) { return new MendelWalker(_lookupChains, _base, _hash); } this.deps = []; if (_hash !== false) { this.serialiser = new TreeSerialiser(); } } MendelWalker.prototype.find = function(module) { var resolved; if (this.deps[module.index]) { return this.deps[module.index]; } else if (module.data.length === 1) { resolved = module.data[0]; } else { var branch = this._resolveBranch(module); resolved = branch.resolved; if (this.serialiser) { this.serialiser.pushBranch(branch.index); } } this.deps[module.index] = resolved; if (this.serialiser) { this.serialiser.pushFileHash(new Buffer(resolved.sha, 'hex')); } return resolved; }; MendelWalker.prototype._resolveBranch = function() { throw new Error('You should extend and implement _resolveBranch'); }; MendelWalker.prototype.found = function() { var found = { deps: this.deps, }; if (this.serialiser) { found.hash = this.serialiser.result(); } return found; }; module.exports = MendelWalker; <file_sep>/test/post-process-manifest.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ var test = require('tap').test; var fs = require('fs'); var path = require('path'); var tmp = require('tmp'); // Since this file re-writes stuff, lets work on a copy var realSamples = path.join(__dirname, './manifest-samples/'); var copySamples = tmp.dirSync().name; var postProcessManifests = require( '../packages/mendel-development/post-process-manifest'); test('postProcessManifests loads manifests', function (t) { copyRecursiveSync(realSamples, copySamples); t.plan(1); postProcessManifests({ outdir: copySamples, bundles: [{ bundleName: 'minimal', manifest: 'minimal.manifest.json', }], }, t.error); }); test('postProcessManifests sorts and cleans manifests', function (t) { copyRecursiveSync(realSamples, copySamples); t.plan(4); postProcessManifests({ outdir: copySamples, bundles: [{ bundleName: 'bad-sort', manifest: 'bad-sort.manifest.json', }], }, function(error) { t.error(error); var result = require(path.join(copySamples, 'bad-sort.manifest.json')); t.equal(result.bundles.length, 4, 'removed one unused bundle'); t.deepEqual(result.indexes, { bar: 0, foo: 1, root:2, zoo: 3 }, 'reordered indexes'); t.deepEqual(Object.keys(result.bundles[1].data[0].deps), ['bar', 'zoo'], 'reordered deps'); }); }); test('postProcessManifests validates manifests', function (t) { copyRecursiveSync(realSamples, copySamples); t.plan(1); postProcessManifests({ outdir: copySamples, bundles: [{ bundleName: 'bad', manifest: 'bad.manifest.json', }], }, function(err) { t.equal(err.code, 'INVALID_MANIFEST', 'should validate manifests'); }); }); test('postProcessManifests applying post-processors', function (t) { copyRecursiveSync(realSamples, copySamples); t.plan(4); var calls = []; function passThroughProcessor(manifests, config, next) { calls.push(arguments); next(manifests); } // yup, kinda nasty, but oh well, it is just tests module.exports = function secondPassThrough(manifests, config, next) { calls.push('external file'); next(manifests); }; postProcessManifests({ manifestProcessors:[ [passThroughProcessor, {'LMAO':'the french smiley cat'}], path.resolve(__filename), ], outdir: copySamples, bundles: [{ bundleName: 'minimal', manifest: 'minimal.manifest.json', }], }, function(error) { t.error(error); t.equals(calls.length, 2, 'calls the post-processors'); t.equals(calls[0][1].LMAO, 'the french smiley cat', 'pass correct options'); t.equals(calls[1], 'external file', 'loads external processors'); }); }); function copyRecursiveSync(src, dest) { var exists = fs.existsSync(src); var stats = exists && fs.statSync(src); var isDirectory = exists && stats.isDirectory(); if (exists && isDirectory) { try{fs.mkdirSync(dest);} catch(e) {/**/} fs.readdirSync(src).forEach(function(childItemName) { copyRecursiveSync(path.join(src, childItemName), path.join(dest, childItemName)); }); } else { fs.writeFileSync(dest, fs.readFileSync(src)); } } <file_sep>/test/proxy.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ var t = require('tap'); var proxy = require('../packages/mendel-development/proxy'); var onlyPublicMethods = proxy.onlyPublicMethods; function Iface(name) { this.name = name; } Iface.prototype = { publicMethod: function() { return this.name + ' publicMethod'; }, _privateMethod: function() { return this.name + ' _privateMethod'; }, filteredMethod: function() { return this.name + ' filteredMethod'; }, }; function spy(obj, methods) { methods.forEach(function(m) { var o = obj[m]; var s = function() { var args = Array.prototype.slice.call(arguments); var val = o.apply(obj, args); this[m].calls.push({ args: args, returns: val, }); this[m].callCount++; return val; }; s.calls = []; s.callCount = 0; obj[m] = s; }); } function checkCallCounts(name, obj, methods, counts) { methods.forEach(function (m, i) { t.equal(obj[m].callCount, counts[i], name + '.' + m + ' calls'); }); } var allMethods = ['publicMethod', '_privateMethod', 'filteredMethod']; var src = new Iface('src'); var dest = new Iface('dest'); proxy(Iface, src, dest, { filters: [onlyPublicMethods], exclude: ['filteredMethod'], }); spy(src, allMethods); spy(dest, allMethods); allMethods.forEach(function (m) { src[m].call(src); }); var methods = Array.prototype.slice.call(allMethods); checkCallCounts('dest', dest, [methods.shift()], [1]); checkCallCounts('dest', dest, methods, [0, 0]); src = new Iface('src'); dest = new Iface('dest'); proxy(Iface, src, dest); spy(src, allMethods); spy(dest, allMethods); allMethods.forEach(function (m) { src[m].call(src); }); checkCallCounts('dest', dest, allMethods, [1, 1, 1]); <file_sep>/packages/mendel-development/proxy.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ function proxyMethod(method, source, destination) { var oldMethod = source[method]; source[method] = function() { var args = Array.prototype.slice.call(arguments); destination[method].apply(destination, args); return oldMethod.apply(source, args); }; } function onlyPublicMethods(method) { return method.indexOf('_') !== 0; } function notIn(methods) { return function(method) { return methods.indexOf(method) === -1; }; } function proxy(iface, src, dest, opts) { opts = opts || {}; var filters = opts.filters || []; var exclude = opts.exclude || []; if (exclude.length) { filters.push(notIn(exclude)); } filters.reduce(function (methods, fn) { return methods.filter(fn); }, Object.keys(iface.prototype)) .forEach(function(method) { proxyMethod(method, src, dest); }); } module.exports = proxy; module.exports.onlyPublicMethods = onlyPublicMethods; <file_sep>/packages/mendel-core/README.md # Mendel Core - Production resolution of file system based experiments Mendel Core is the brain behind `mendel-middleware`. It is used to resolve hundreds or even thousands of potential permutations of "application trees". It uses deterministic hashing to provide a two step resolving: 1. Given a variation array, it resolves which files should be used for a given user session. It outputs an "application tree" and a deterministic hash. 2. Given a hash generated in step 1, it can recover all file dependencies for the same user session, resulting in the same exact "application tree" as step 1. Mendel Core works by loading [Mendel Manifests](../../docs/Design.md) on a per-process basis, and resolves "application trees" on a per request (or per user session) basis. ``` +-----------------------------------------------+ | | | Mendel Core long running instance | | | | (contains all variations of | | all pre-compiled files) | | | +----+--------------+------------+----------+---+ | | | | v v v | | +-----------+ +-----------+ +-----------+ v | Tree for | | Tree for | | Tree for | | variations| | variations| | variations| etc | A | | B, C | | A, C | +-----------+ +-----------+ +-----------+ ``` Each tree representation can be used to server-side render, to hash generation or to resolve a bundle for a particular set of variations. ### Request Cycle: Variation resolution When the user first visits the application, Mendel Core use a variation array to resolve the application code: ``` +--------------------+ | | | Mendel Manifests | | | +---------+----------+ | v +---------------------------+ | | | Mendel Core per process | | instance | | | +------------------+--------+ ^ | NodeJS Process | | +------------------------------------------------------------------+ HTTP Request | | | | +------------+ | | +--------------+ | | | | | | | variations +-----------+ +------------> | dependencies | | | | | | +------------+ | +--------------+ | | +--------------+ | | | +------------> | hash | | | +--------------+ ``` Dependencies are a list of filenames and their content. Dependencies can than be used to server-side render and the hash can be used to generate bundle URLs that are safe for CDN caching. ### Request Cycle: Hash resolution When a request comes in with a hash, Mendel Core is able to safely recover all the dependencies from the manifest: ``` +--------------------+ | | | Mendel Manifests | | | +---------+----------+ | v +---------------------------+ | | | MendelCore per process | | instance | | | +------------------+--------+ ^ | NodeJS Process | | +------------------------------------------------------------------+ HTTP Request | | | | +------------+ | | +--------------+ | | | | | | | hash +-----------+ +------------> | dependencies | | | | | +------------+ +--------------+ ``` This request will usually be used to serve a bundle. The request can come from a user or from a CDN or any other proxy/caching layers. It does not need cookies and won't need a "Vary" header to prevent it to be cached incorrectly by proxies. The hash is sufficient to consistently resolve the dependencies. #### Mendel Hashing algorithm The Mendel hash is a binary format encoded in URLSafeBase64 (RFC4648 section 5). The binary has the format below, where each number in parenthesis is the number of bytes used for a particular information: ``` 1 2 3 4 5 6 +------------+---------+--------------+---------+----------+---------+ | ascii(6*8) | uint(8) | loop uint(8) | uint(8) | uint(16) | bin(20) | | === mendel | | !== 255 | == 255 | | | +------------+---------+--------------+---------+----------+---------+ ``` The 6 pieces stand for: 1. ID: The string “mendel” (lowercase) in ascii encoding 2. VERSION: The version of this binary, right now it is version 1, we reserved this for future compatibility 3. VARIATIONS_ARRAY: 0+ segments of 8 bit unsigned integers, that are different than 255 4. VARIATIONS_LIMITER: Integer with value 255 that marks end of file variations 5. FILE_COUNT: The number of total files that were hashed during tree walking 6. CONTENT_HASH: 20 byte sha1 binary Mendel starts with ID and VERSION and will walk the manifest, starting in the entry points of the package. Each "dep" is a browserify-like payload and has a sha1 of the source code, and also the dependencies of this file. Mendel will collect sha1 of all files and count how many files were walked. Every time Mendel finds a file with variations, it uses a one of two desired method for choosing a variation (discussed below), and it will then push **the index of the chosen variation** to the **variation index array**. The numbers are also appended to VARIATIONS_ARRAY of the binary. Once walking is done, Mendel adds VARIATIONS_LIMITER, to the binary, adds FILE_COUNT with the number of files walked, and computes CONTENT_HASH, the sha1 of all walked sha1 of the bundle. The final binary is than encoded with URLSafeBase64. The variations can be resolved in two ways: By an array of desired **variation names**. This is useful for generating the hash for the first time. The second way, is when we decode a hash binary, and walk the manifest to collect and bundle source code, using the **variation index array**. Because we need to make sure the contents are the same requested by user, the hash is calculated both when generating it for the first time (when generating HTML request) and when collecting the source code payload (when dynamically serving the bundle). If it is a match, the source code can be concatenated using `browser_pack`. ## Reference Usage Usually, you can use the `mendel-middleware` instead of using `mendel-core` directly. We also provide a [reference implementation](../../examples/full-example/) for the middleware use. In case you need advanced use of Mendel, the minimal server bellow should be enough for you to start your custom implementation. ```js // we call it MendelTrees because it is like a seed that will grow many // different trees depending on variations and bundles. It is almost a // tree factory, if you must :wink: const MendelTrees = require('mendel-core'); const trees = MendelTrees(); // if no options passed, will read .mendelrc function requestHandler(request, response) { // bundle should match .mendelrc bundle and can be multiple bundles const bundle = 'main'; if (/index.html/.test(request.url)) { // variations can come from request cookie const variations = ['base']; // if you have multiple bundles you need to find one tree per bundle const tree = trees.findTreeForVariations(bundle, variations); // bundle url can be wrapped in a cookie-less CDN url const src = '/' + bundle + '.' + tree.hash + '.js'; const script = '<script src="'+ src + '"></script>'; response.end('<html><head>'+ script + '</head></html>'); } else { // if you have multiple bundles you will need routes based on bundle const jsPath = new RegExp('/' + bundle + '\.(.*)\.js'); if (jsPath.test(request.url)) { // your CDN can safely cache this url without cookies // and without "Vary" header const hash = request.url.match(jsPath)[1]; const tree = trees.findTreeForHash(bundle, hash); response.end(JSON.stringify(tree)); // use your bundler } else { response.end('Not found'); } } } const http = require('http'); const server = http.createServer(requestHandler); server.listen(3000); ``` Usually, you won't be serving a JSON representation for your bundle, you will instead add error control, conflict detection and etc and eventually pack your bundle using UMD, browser-pack, rollup or even just concatenating all sources on global scope. Here is a minimal example of using browser pack: ```js // on the example above, add this line at the top of the file const bpack = require('browser-pack'); // and replace the line `response.end(JSON.stringify(tree));` by: if (!tree || tree.error || tree.conflicts) { return response.end('Error ' + tree && tree.error || tree.conflictList); } const pack = bpack({raw: true, hasExports: true}); pack.pipe(response); const modules = tree.deps.filter(Boolean); for (var i = 0; i < modules.length; i++) { pack.write(modules[i]); } pack.end(); ``` Please, see `mendel-middlware` for a production ready implementation of mendel-core with an express compatible API. Please, see `mendel-development-middleware` for a viable implementation of development bundles without using `mendel-core` and with cached re-bundling based on source file changes. <file_sep>/examples/planout-example/PlanoutAssignment.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. Contributed by <NAME> <<EMAIL>> See the accompanying LICENSE file for terms. */ var Planout = require("planout"); class PlanoutAssignment extends Planout.Experiment { configureLogger() { return; } log(/* event */) { /* The event contains the details of the assignment, as shown in the below example. This should be saved for analytics. { name: 'GenericExperiment', time: 1476884238.671, salt: 'GenericExperiment', inputs: { visitorId: '8417bb0e-d918-4807-b9a3-0339c6300d4f' }, params: { layer_1: 'layer_1_bucket_B', layer_2: 'layer_2_bucket_C' }, event: 'exposure' } */ } previouslyLogged() {} assign(params, args) { /* Planout uses deterministic hashing to choose assignments. This assures that the same visitorId will always get the same selection. In addition to the visitorId, Planout concatenates the params name ('layer_1' or 'layer_2') with the visitorId to assure that selections are not correlated across params. */ params.set('layer_1', new Planout.Ops.Random.UniformChoice({ choices: [ false, // if selected will show base "layer_1_bucket_A", "layer_1_bucket_B" ], unit: args.visitorId }) ); params.set('layer_2', new Planout.Ops.Random.UniformChoice({ choices: [ false, // if selected will show base "layer_2_bucket_A", "layer_2_bucket_B", "layer_2_bucket_C" ], unit: args.visitorId }) ); } } module.exports = PlanoutAssignment; <file_sep>/packages/mendel-pipeline/src/helpers/analytics/printer.js class Printer { constructor() { } print(data) { // eslint-disable-line throw new Error('Please implement me.'); } } module.exports = Printer; <file_sep>/examples/full-example/isomorphic/base/components/_test_/button_test.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ import React from 'react'; // eslint-disable-line no-unused-vars import { findDOMNode } from 'react-dom'; // eslint-disable-line no-unused-vars import { renderIntoDocument } from 'react-addons-test-utils'; import Button from '../button'; import {expect} from 'chai'; describe("Button", function() { it("renders with children", function() { const button = renderIntoDocument(<Button>{this.sayMeow()}</Button>); expect(findDOMNode(button).innerText).to.equal('meow'); }); }); <file_sep>/packages/mendel-pipeline/src/step/step.js const debug = require('debug'); const EventEmitter = require('events').EventEmitter; class Step extends EventEmitter { constructor() { super(); } static get name() { throw new Error('Must implement static "name"'); } perform() { throw new Error('Must implement "perform"'); } get verbose() { if (this._verbose) return this._verbose; return this._verbose = debug( `verbose:mendel:filestep:${this.constructor.name}` ); } emit(eventName, {entryId = ''} = {}) { this.verbose(eventName, entryId); super.emit.apply(this, arguments); } } module.exports = Step; <file_sep>/docs/Configuration.md # Mendel configuration The Mendel command line tool and most of Mendel's standalone packages are compatible with the same configuration. The configuration can be passed in 3 ways: 1. A file named `.mendelrc` in the root of your project 2. In a `mendel` property in the `package.json` for your project 3. As a JavaScript `options` object, if you are using one of the standalone packages programmatically. Most standalone packages support only a subset of the configuration, and Mendel CLI supports all of them. If `.mendelrc` is provided, `package.json` will be ignored, but if you use mendel programmatically and one of the files are also available `options` will take precedence and override params in the file configuration. ## Path configuration ## Variations and Variation Inheritance ## Bundle configuration ## Middleware configuration ## Enviroment based overrides ## Post process middleware plugin configuration <file_sep>/docs/ManifestValidation.md ## Manifest Validation - deterministic bundle It is important for production environment that the same "parent file" can require different "dependencies" based on variations, but files that only exist on "base" should not have different source code because of changes on variations. If this condition is not met, you might get the following error: ``` Error: Files with same variation (base) and id (body.js) should have the same SHA ``` If you get the above error, Mendel saves some files in a temp directory so you can use a diff tool to understand what happened with compiled versions that have different SHA-sum hash. In order to understand potential fixes, lets see a quick 3 file application example: ```js /* $ tree . ├── base │   ├── body.js │   └── square.js └── variations └── blue_square └── square.js */ // base/body.js var square = require('./square'); var body = document.querySelector('body'); body.apprendChild(square()); // base/square.js module.exports = function() { var div = document.createElement('div'); Object.assign(div.style, {backgroundColor: "red", display: 'inline-block', width: '50px', height: '50px' }); return div; }; // variations/blue_square/square.js module.exports = function() { var div = document.createElement('div'); Object.assign(div.style, {backgroundColor: "blue", display: 'inline-block', width: '50px', height: '50px' }); return div; }; ``` In the example above, it is important that `base/body.js` has exactly the same compiled source code across all variations, since the actual source code only exists in `base` folder. There are some reasons during compilation we might find different versions of the same source file: ### Source inconsistency because of different "resolution" If instead of creating `variations/blue_square/square.js` you create `variations/blue_square/square/index.js` you will create inconsistent "parent" string for the "base" variation of "body.js". The reason for that lays in absolute path resolution built-in Mendel: ```js // relevant line in 'body.js' var square = require('./square'); // when compiling base bundle './square' resolves to // '/base/square.js' // relativeToVariation('/base/square.js') -> 'square.js' // compiled source code for 'base/body.js' while building base bundle: var square = require('square.js'); // when compiling blue_square bundle './square' resolves to // '/variations/square/index.js' // relativeToVariation('/variations/square/index.js') -> 'square/index.js' // compiled source code for 'base/body.js' while building blue_square bundle: var square = require('square/index.js'); ``` This causes `body.js` to have two different compiled versions. In order to avoid that, make sure your variations have exactly the same path and extension as the base variation for files that already exist or already "resolve" in the base bundle. ### Source inconsistency because of non-deterministic transforms Some file transformations might be unsafe, and this problem can only be addressed outside of Mendel, on the transformation itself. For instance, lets assume the following, very naive, hypothetical Browserify transform: ```js var options = {excludeExtensions: [".json"]}; module.exports = transformTools.makeStringTransform("timestampify", options, function (content, transformOptions, done) { var newContent = content + '\n// Generated: ' + Date.now() + '\n'; done(null, newContent); }); ``` Because `Date.now()` is different when parsing `base/body.js` the first time (for base) and the second time (for blue_square) variation, it will yield different sources for the "same file". You could fix the potential transform problem with deterministic algorithms, in our naive example, this could be fixed by replacing `Date.now()` for git last commit date: ```js var options = {excludeExtensions: [".json"]}; var consistentDate = HipoteticalGitLibrary.lastCommitTimestamp(); module.exports = transformTools.makeStringTransform("timestampify", options, function (content, transformOptions, done) { var newContent = content + '\n// Build time: ' + consistentDate + '\n'; done(null, newContent); }); ``` A number of transforms might make similar mistakes, take for instance [this UglifyJS2 old issue](https://github.com/mishoo/UglifyJS2/issues/229) where something similar happened. <file_sep>/test/mendel-requirify.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ var fs = require('fs'); var path = require('path'); var temp = require('temp'); var test = require('tap').test; var rimraf = require('rimraf'); var browserify = require('browserify'); var requirify = require('../packages/mendel-requirify'); var treenherit = require('../packages/mendel-treenherit'); var requireTransform = require('../packages/mendel-development/require-transform'); var srcDir = path.resolve(__dirname, './app-samples/1'); temp.track(); var buildDir = temp.mkdirSync('build-requirify'); var entry = 'app/number-list.js'; var variationDirs = ['test_A', 'app']; var mendelRequireRegexp = /__mendel_require__\(/; var requireRegexp = /\brequire\(/; function run(t, outDir, outFile, cb) { t.plan(4); var b = browserify({ basedir: srcDir, entries: [path.join(srcDir, entry)], }); b.transform(treenherit, { dirs: variationDirs, }); b.plugin(requirify, { outdir: outDir, dirs: variationDirs, }); b.bundle(function (err) { if (err) { t.fail(err.message || err); } // wait for file to be written setTimeout(function() { var src; try { src = fs.readFileSync(outFile, 'utf-8'); } catch (e) { t.fail('Failed to open dest file: ' + outFile); } t.match(src, mendelRequireRegexp); t.notMatch(src, requireRegexp); var wrapper = requireTransform.wrapper; t.equal(src.indexOf(wrapper[0]), 0, 'wrapper prelude pos'); t.equal(src.indexOf(wrapper[1]), src.length - wrapper[1].length, 'wrapper epilogue pos'); temp.cleanup(function() { if (cb) { return cb(t); } t.end(); }); }, 150); }); } test('mendel-requirify', function (t) { var outFile = path.join(buildDir, entry); run(t, buildDir, outFile); }); test('mendel-requirify-defaults', function (t) { var outDir = path.join(process.cwd(), 'build-requirify'); var outFile = path.join(outDir, entry); run(t, null, outFile, function (t) { rimraf(outDir, function () { t.end(); }); }); }); <file_sep>/packages/mendel-outlet-css/mendel-postcss-remove-import.js /** * Because mendel-outlet-css concatenate CSS files into one, * all the @import that created dependency between CSS files are no * longer needed or valid. We need to remove them. */ const postcss = require('postcss'); let currentRemoval = new Set(); module.exports = postcss.plugin('postcss-remove-import', (/* options */) => { // Work with options here return root => { // Transform each rule here root.walkAtRules('import', atRule => { const path = atRule.params.replace(/(^["']|["']$)/g, ''); if (currentRemoval.has(path)) { atRule.remove(); } }); }; }); module.exports.setToRemove = function(removalSet) { currentRemoval = removalSet; }; <file_sep>/packages/mendel-config/src/variation-config.js const parseVariations = require('../variations'); const createValidator = require('./helpers/validator'); const validate = createValidator({ variations: {type: 'array', minLen: 1}, // There can be a user of Mendel who does not want variation but faster build. allVariationDirs: {type: 'array', minLen: 0}, allDirs: {type: 'array', minLen: 1}, }); function VariationConfig(config) { const variations = parseVariations(config); const allVariationDirs = getAllDirs(variations); const baseVariation = { id: config.baseConfig.id, chain: [config.baseConfig.dir], dir: config.baseConfig.dir, }; // base variation must come first in order to variationMatches to work variations.unshift(baseVariation); const allDirs = getAllDirs(variations); const variationConfig = { variations, baseVariation, allDirs, allVariationDirs, }; validate(variationConfig); return variationConfig; } function getAllDirs(variationArray) { return variationArray.reduce((allDirs, variation) => { variation.chain.forEach(dir => { if (!allDirs.includes(dir)) allDirs.push(dir); }); return allDirs; }, []); } module.exports = VariationConfig; <file_sep>/packages/mendel-pipeline/src/cache/entry.js class Entry { static getTypeForConfig(typeConfigs, id) { if (isNodeModule(id)) return 'node_modules'; const type = typeConfigs.find(type => type.test(id)); return type ? type.name : '_others'; } constructor(id) { this.id = id; // property is filled by cache where they have more context this.normalizedId; this.variation; this.runtime; // one of 'browser', 'main', 'package', 'isomorphic' this.type; // one of the ids of types defined in mendelrc. this.istSource; this.istDeps; this.istMap; this.rawSource; this.rawDeps; this.source; // Transform used for source this.transformIds; this.map; // dependencies this.deps; this.dependents; // Other metadata this.error; // If there is an error this.done; // Whether entry went through upto GST step in pipeline this.reset(); } // Let's store rawSource setSource(source, deps, map) { this.source = source; this.deps = deps; if (map) { this.map = map; } if (!this.rawSource) { this.rawSource = source; this.rawDeps = deps; } } hasSource() { return !!this.source; } getDependency() { return this.deps; } reset() { this.rawSource = null; this.rawDeps = {}; this.source = null; this.map = null; this.deps = {}; this.dependents = []; this.error = null; this.done = false; } // For debugging purposes debug() { return { id: this.id, normalizedId: this.normalizedId, variation: this.variation, dependents: this.dependents, source: this.source, deps: this.deps, map: this.map, }; } } function isNodeModule(id) { return id.indexOf('node_modules') >= 0 || /\/mendel-\S+\//.test(id); } module.exports = Entry; <file_sep>/examples/planout-example/isomorphic/variations/layer_1_bucket_A/components/body.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. Contributed by <NAME> <<EMAIL>> See the accompanying LICENSE file for terms. */ import React from 'react'; const style = { margin: "20px 0", padding: "20px", backgroundColor: "#F39C12" } export default () => { return ( <div style={style}> <b>body.js</b><br/> variations/layer_1_bucket_A/components/body.js </div> ); } <file_sep>/packages/mendel-transform-buble/index.js const {transform} = require('buble'); const {EOL} = require('os'); module.exports = function({source, filename, map: inputSourceMap}, options) { options = options || {}; const defaults = {source: filename}; const transformOptions = Object.assign(defaults, options); transformOptions.transforms = Object.assign( {modules: false}, options.transforms ); transformOptions.target = Object.assign({}, options.target); const result = transform(source, transformOptions); let {code, map} = result; if (options.sourceMap) { // append sourcemaps to code code += `${EOL}//# sourceMappingURL=${map.toUrl()}`; } return {source: code, map}; }; <file_sep>/packages/mendel-deps/test/js-fixtures/es5/foo/browser.js const {test} = require('glob'); <file_sep>/packages/mendel-pipeline/src/helpers/analytics/analytics-worker.js const Analytics = require('./analytics').constructor; class AnalyticsForWorker extends Analytics { record(name, before, after) { process.send({ type: 'analytics', name: `${process.pid}:${this.groupName}:${name}`, before, after, }); } } module.exports = function(name) { return new AnalyticsForWorker(name); }; <file_sep>/examples/planout-example/index.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ var app = require('./app'); var port = process.env.PORT ? process.env.PORT : 3000; var hostname = require('os').hostname(); if (module.parent) { module.exports = app; } else { app.listen(port, function () { console.log('listening at %s port %s', hostname, port); }); } <file_sep>/packages/mendel-pipeline/src/cache/network/base-network.js class BaseNetwork { static getServer(/* connectionOptions */) { throw new Error('Implement this'); } static getClient(/* connectionOptions */) { throw new Error('Implement this'); } } module.exports = BaseNetwork; <file_sep>/examples/full-example/isomorphic/base/components/message_board.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ import React from 'react'; import Message from './message'; class Board extends React.Component { render() { return ( <div className="board"> <Message /> <Message /> <Message /> </div> ); } } export default Board; <file_sep>/scripts/mendel-packages.js module.exports = [ 'packages/karma-mendel', 'packages/mendel-config', 'packages/mendel-core', 'packages/mendel-deps', 'packages/mendel-browser-pack', 'packages/mendel-development', 'packages/mendel-development-middleware', 'packages/mendel-exec', 'packages/mendel-generator-extract', 'packages/mendel-generator-node-modules', 'packages/mendel-generator-prune', 'packages/mendel-manifest-uglify', 'packages/mendel-middleware', 'packages/mendel-mocha-runner', 'packages/mendel-outlet-browser-pack', 'packages/mendel-outlet-css', 'packages/mendel-outlet-manifest', 'packages/mendel-outlet-server-side-render', 'packages/mendel-parser-json', 'packages/mendel-pipeline', 'packages/mendel-resolver', 'packages/mendel-transform-babel', 'packages/mendel-transform-buble', 'packages/mendel-transform-less', ]; <file_sep>/packages/mendel-development/resolve-variations.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ function resolveVariations(existingVariations, variations) { var i, j, evar, dir, resolved = []; // walk in reverse and fill in reverse achieves desired order for (i = existingVariations.length-1; i >= 0; i--) { evar = existingVariations[i]; if (-1 !== variations.indexOf(evar.id)) { for (j = evar.chain.length-1; j >= 0; j--) { dir = evar.chain[j]; if (-1 === resolved.indexOf(dir)) { resolved.unshift(dir); } } } } return resolved; } module.exports = resolveVariations; <file_sep>/packages/mendel-pipeline/src/helpers/analytics/analytics-collector.js class AnalyticsCollector { constructor(options) { this.options = options || {}; this.data = []; global.analytics = this; process.on('message', () => this.record()); process.on('exit', () => this.onExit()); } onExit() { if (this.options.printer && this.data.length) { this.options.printer.print(this.data); } } setOptions(options) { this.options = options; } connectProcess(childProces) { childProces.on('message', this.record.bind(this)); } record(message) { if ( !this.options.printer || !message || message.type !== 'analytics' ) return; const {pid, name, after, before} = message; this.data.push({ name, pid, before, after, timestamp: Date.now(), }); } } // Singleton module.exports = (function() {return new AnalyticsCollector();})(); <file_sep>/packages/mendel-transform-buble/README.md # mendel-transform-buble Mendel transform ES6+ converting using bublé https://buble.surge.sh <file_sep>/packages/mendel-pipeline/src/cli.js #!/usr/bin/env node /* eslint max-len: "off" */ const program = require('commander'); const chalk = require('chalk'); function parseIgnores(val='', previousIgnores) { return previousIgnores.concat( val.split(',') .map(splitted => splitted.trim()) .filter(Boolean) ); } program .version('0.1.0') .usage('[options] <dir path>') .option('--ignore <patterns>', 'Comma separated ignore glob patterns', parseIgnores, ['**/_test_/**', '**/_browser_test_/**', '**/assets/**']) // .option('-v, --verbose', 'Verbose mode') .option('-w, --watch', 'Watch mode', false) .option('-o, --outlet', 'Write a mendel v1 compatible manifest', false) .parse(process.argv); if (program.watch) { const MendelPipelineDaemon = require('./daemon'); const daemon = new MendelPipelineDaemon(program); daemon.watch(); } else { const Mendel = require('./main'); const daemon = new Mendel(program); daemon.run((error) => { if (error) process.exit(1); setImmediate(() => process.exit(0)); }); const AnalyticsCliPrinter = require('./helpers/analytics/cli-printer'); const collector = require('./helpers/analytics/analytics-collector'); collector.setOptions({ printer: new AnalyticsCliPrinter({enableColor: true}), }); process.on('exit', (code) => { console.log('exit', code); if (code > 0) daemon.onForceExit(); }); process.on('SIGINT', () => { console.log('SIGINT'); daemon.onForceExit(); process.exit(1); }); process.on('uncaughtException', (error) => { console.log([ `Force closing due to a critical error:\n`, chalk.red(error.stack), ].join(' ')); daemon.onForceExit(); process.exit(1); }); // nodemon style shutdown process.once('SIGUSR2', () => process.kill(process.pid, 'SIGUSR2')); } <file_sep>/packages/mendel-config/index.js var path = require('path'); var yaml = require('js-yaml'); var fs = require('fs'); var xtend = require('xtend'); function findConfig(where) { var parts = where.split(path.sep); do { var loc = parts.join(path.sep); if (!loc) break; var config; var mendelrc = process.env.MENDELRC || '.mendelrc'; var rc = path.join(loc, mendelrc); if (fs.existsSync(rc)) { config = loadFromYaml(rc); config.projectRoot = path.dirname(rc); return config; } var packagejson = path.join(loc, 'package.json'); if (fs.existsSync(packagejson)) { var pkg = require(path.resolve(packagejson)); if (pkg.mendel) { config = pkg.mendel; config.projectRoot = path.dirname(packagejson); return config; } } parts.pop(); } while (parts.length); return {}; } function loadFromYaml(path) { return yaml.safeLoad(fs.readFileSync(path, 'utf8')); } module.exports = function(config) { if (typeof config === 'string') config = {projectRoot: config}; if (typeof config !== 'object') config = {}; var projectRoot = config.projectRoot || config.basedir || process.cwd(); // support --no-config or {config: false} to skip looking for file configs if (config.config !== false) { var fileConfig = findConfig(projectRoot); // in case we found a file config, assign by priority if (fileConfig.projectRoot) { config = xtend(fileConfig, config); // but force projectRoot to always be consistent config.projectRoot = fileConfig.projectRoot; // In case this config is passed to mendel-config again config.config = false; } } // require only inside conditional if (config['base-config']) { // This requires node 6 - can use ES6 features return require('./src')(config); } else { config.basedir = config.projectRoot; // This requires node 0.10 - must be written in ES5 return require('./legacy')(config); } }; <file_sep>/packages/mendel-browser-pack/index-deps.js /** * Modules internal to a bundle can be referenced by index instead of id. * Remap ids and deps in such case. * @example * This compresses the bundle by renaming all dependency indexes from file paths * to a numbered index. * * Here is a sample transformation: * ```js * [ * { * "entry": true, * "id": "/User/me/projects/site/src/main.js", * "deps": { * "./colors.js": "/User/me/projects/site/src/colors.js", * "./shared.js": "/User/me/projects/site/src/shared.js" * } * }, * { * "id": "/User/me/projects/site/src/colors.js", * "deps": { * "external-lib": false * } * }, * { * "expose": "shared", * "id": "/User/me/projects/site/src/shared.js", * "deps": {} * } * ] * ``` * * Should become: * ```js * [ * { * "entry": true, * "id": 1, * "deps": { * "./colors.js": 2, * "./shared.js": "shared" * } * }, * { * "id": 2, * "deps": { * "external-lib": false * } * }, * { * "expose": "shared", * "id": "shared", * "deps": {} * } * ] * ``` */ module.exports = function indexedDeps(mods) { // the index can't be ever 0 because 0 is false for browserify var newModIndex = [0]; // indexes are created first, because deps can come unordered mods.forEach(function(mod){ if (!mod.expose) newModIndex.push(mod.id); }); // create a new array of modified modules return mods.map(function(oldMod) { return Object.keys(oldMod).reduce(function(newMod, prop) { if (prop === 'deps') { // deps needs to be reindexed newMod.deps = Object.keys(oldMod.deps).reduce( function(newDeps, name) { var id = oldMod.deps[name]; var index = newModIndex.indexOf(id); if (index > -1) { newDeps[name] = index; } else { // deps not indexed are exposed or external newDeps[name] = id; } return newDeps; }, {}); } else if (prop === 'id') { // id needs to be reindexed var index = newModIndex.indexOf(oldMod.id); if (index > -1) { newMod.id = index; } else { // unless it is entry or exposed newMod.id = oldMod.expose || oldMod.id; } } else { // for all other props we just copy over newMod[prop] = oldMod[prop]; } return newMod; }, {}); }); }; <file_sep>/packages/mendel-development/post-process-manifest.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ var fs = require('fs'); var path = require('path'); var async = require('async'); var inspect = require('util').inspect; var resolve = require('resolve'); var debug = require('debug')('mendel-manifest-postprocess'); var sortManifest = require('./sort-manifest'); var validateManifest = require('./validate-manifest'); module.exports = postProcessManifests; function postProcessManifests(config, finish) { debug('start'); var resolveProcessor = processorResolver.bind(null, config); var processors = [ [loadManifests, config], ].concat(config.manifestProcessors).concat([ [sortManifestProcessor, config], [validateManifestProcessor, config], [writeManifest, config], ]).filter(Boolean); async.map(processors, resolveProcessor, function(err, processors) { // istanbul ignore if if (err) throw err; var input = config.bundles; async.eachSeries(processors, function(processorPair, doneStep) { var processor = processorPair[0]; var opts = processorPair[1] || {}; debug('running ' + inspect(processor)); opts.mendelConfig = config; try { processor(input, opts, function(output) { input = output; doneStep(); }); } catch(e) { doneStep(e); } }, finish); }); } function processorResolver(config, processorIn, doneProcessor) { if (!Array.isArray(processorIn)) { return processorResolver(config, [processorIn, {}], doneProcessor); } var processor = processorIn[0]; var opts = processorIn[1]; if (typeof processor === 'string') { var resolveOpts = { basedir: config.basedir, }; resolve(processor, resolveOpts, function (err, path) { // istanbul ignore if if (err) return doneProcessor(err); var newProcessor = [require(path), opts]; doneProcessor(null, newProcessor); }); } else { doneProcessor(null, processorIn); } } function loadManifests(bundles, config, next) { var manifests = bundles.reduce(function(manifests, bundle) { var file = path.join(config.outdir, bundle.manifest); delete require.cache[require.resolve(file)]; manifests[bundle.bundleName] = require(file); return manifests; }, {}); next(manifests); } function sortManifestProcessor(manifests, config, next) { Object.keys(manifests).forEach(function(bundleName) { manifests[bundleName] = (sortManifest( manifests[bundleName].indexes, manifests[bundleName].bundles )); }); next(manifests); } function validateManifestProcessor(manifests, config, next) { Object.keys(manifests).forEach(function(bundleName) { var filename = config.bundles.filter(function(bundle) { return bundle.bundleName === bundleName; })[0].manifest; validateManifest( manifests[bundleName], filename, 'manifestProcessors' ); }); next(manifests); } function writeManifest(manifests, config, next) { Object.keys(manifests).forEach(function(bundleName) { var filename = config.bundles.filter(function(bundle) { return bundle.bundleName === bundleName; })[0].manifest; var file = path.join(config.outdir, filename); fs.writeFileSync( file, JSON.stringify(manifests[bundleName], null, 2) ); delete require.cache[require.resolve(file)]; }); next(); } <file_sep>/packages/mendel-config/src/generator-config.js var createValidator = require('./helpers/validator'); var nodeResolve = require('resolve').sync; function GeneratorConfig({id, plugin}, {projectRoot}) { this.id = id; try { this.plugin = nodeResolve(plugin, {basedir: projectRoot}); } catch (e) { if (e.code !== 'MODULE_NOT_FOUND') throw e; this.plugin = false; } GeneratorConfig.validate(this); } GeneratorConfig.validate = createValidator({ id: {required: true}, plugin: {required: true}, }); module.exports = GeneratorConfig; <file_sep>/packages/mendel-config/legacy/defaults.js /* Copyright 2015, Yahoo Inc. Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms. */ module.exports = function() { return { basedir: process.cwd(), outdir: 'mendel-build', bundlesoutdir: '', serveroutdir: '', bundleName: 'bundle', base: 'base', basetree: 'base', variationsdir: '', bundles: {}, variations: {}, env: {}, environment: 'development', }; };
08b75e0a21e1e0d5b922ba7618649b8e643a59ef
[ "JavaScript", "Markdown", "Shell" ]
133
JavaScript
stephanwlee/mendel
28ba8a89e51161e4d2125c6797d606ed56207b64
e87508872eaa70537be1674a2bd9af928c59b398
refs/heads/master
<file_sep>const Math = {}; function sumar(x1,x2){ return x1 + x2; } function restar(x1,x2){ return x1 - x2; } function multiplicacion(x1,x2){ return x1 * x2; } function division(x1,x2){ if(x2 == 0){ console.log('No se puede dividir por 0'); }else{ return x1/x2; } } Math.suma = sumar; Math.resta = restar; Math.multi = multiplicacion; Math.division = division; module.exports = Math;<file_sep>document.getElementById('formTask').addEventListener('submit',saveTask); function saveTask(e){ let title = document.getElementById('title').value; let description = document.getElementById('description').value; let task = { title, //title: title description //description: description ----> es una forma rapida de escribir codigo CLAVE: VALOR }; if(localStorage.getItem('tasks') === null){ // si es obtienen valores nulos de almacenados en tasks en el navegador. let tasks = []; tasks.push(task); //envio los datos al arreglo localStorage.setItem('tasks', JSON.stringify(tasks)); // almaceno datos en el navegador } else { // obtener y actualizarlas let tasks = JSON.parse(localStorage.getItem('tasks')); tasks.push(task); //actualiza nuevas tareas localStorage.setItem('tasks', JSON.stringify(tasks)); }; getTasks(); document.getElementById('formTask').reset(); e.preventDefault(); } function getTasks(){ let tasks = JSON.parse(localStorage.getItem('tasks')); let tasksView = document.getElementById('mostrar'); tasksView.innerHTML = ''; for(let i=0; i < tasks.length; i++){ let title = tasks[i].title;//almacena uno por uno el titulo de la tarea let description = tasks[i].description; tasksView.innerHTML += `<div class="card"> <div class="card-body"> <p>${title} - ${description}</p> <a class="btn btn-danger" onclick="deleteTasks('${title}')"> ELIMINAR </a> </div> </div>` //muestra el titulo en pantalla } } function deleteTasks(title){ let tasks = JSON.parse(localStorage.getItem('tasks')); // obtuve datos //quite el dato for(let i=0; i<tasks.length; i++){ if(tasks[i].title == title){ tasks.splice(i, 1); } } //almaceno otra vez los datos localStorage.setItem('tasks', JSON.stringify(tasks)) getTasks(); } getTasks(); /* localStorage.setItem('tasks', JSON.stringify(task)); //almacena en el navegador los datos. localStorage.getItem('tasks'); //.getItem para obtener los datos almacenados en el navegador JSON.parse()--->transformar de string a objeto JSON.stringify()--->transformar de objeto a string */<file_sep># aprendiendo-javascript Aqui aprendo hacer varios programas con javascript <file_sep>/* ------- como funciona en nodejs ---------- const http = require('http'); const colors = require('colors'); const handleServer = function (req, res) { res.writeHead(200, {'content-type':'text/html'}); res.write('<h1>HOLA MUNDO</h1>'); res.end(); } const server = http.createServer(handleServer); server.listen(3000, function (){ console.log('Server on port 3000'.grey); }); */ // -------- con framework express ----- const express = require('express'); const colors = require('colors'); const server = express(); server.get('/', function(req, res){ res.send('<h1>Hola mundo con express y nodejs</h1>'); res.end(); }) server.listen(3000, function (){ console.log('Server port 3000'.red); }) /* ---------- codigo leer archivo -------- const fs = require('fs'); fs.readFile('./text.txt', function(err, data){ if(err){ console.log(err); } console.log(data.toString()); //convertir los datos en String }); */ /* --------- codigo crear archivos ----------- const fs = require('fs'); fs.writeFile('./text.txt', 'linea uno', function (err) { if(err){ console.log(err); } console.log('Archivo creado'); }); console.log('Ultima linea de codigo'); */ /* const os = require('os'); console.log(os.platform()); console.log(os.release()); console.log(os.freemem()); console.log(os.totalmem()); */
3702a79fdc1e228fdd5147bc6f85c7c2cdd57e12
[ "JavaScript", "Markdown" ]
4
JavaScript
kaxer1/aprendiendo-javascript
1bbd8f03566cf3655129bd8e5cb62d7475f69f76
0090c699d28b5f875b368f56c6579a9b1baedcbe
refs/heads/master
<file_sep>import React, { Component } from 'react'; import 'bootstrap/dist/css/bootstrap.css'; import FormProduct from './FormProduct'; import ProductsPanel from './ProductsPanel'; class Products extends Component{ render(){ return ( <div className = 'container'> <div className='border rounded col-lg-5 mt-4 mx-auto'> <div className='row mt-4 pl-2'> <FormProduct onSubmit={this.props.subm} value={this.props.product} onChange={this.props.change} /> </div> <div className='row mt-3 mb-3'> <div className='col-md-6 font-weight-bold'> Stored items{' '} <span className='font-weight-bold badge badge-dark'> {this.props.list.length} </span> </div> </div> <React.Fragment> {this.props.list.length>0 ?<ProductsPanel list={this.props.list} addItem={this.props.add} delItem={this.props.del} remItem={this.props.rem}/> :null } </React.Fragment> </div> </div> ) } } export default Products;<file_sep>import React, { Component } from "react"; import { Modal } from "react-bootstrap"; import "bootstrap/dist/css/bootstrap.css"; class ModalEditClient extends Component { constructor(props) { super(props); this.state = { id: props.newUser.id }; } componentWillReceiveProps(props) { if (props.newUser.id !== this.state.id) { props.refreshModal(); } } render() { const { show, onHide } = this.props; const userEdited = () => { if (!this.props.newUser.id) { return { name: "", email: "", username: "", phone: "", website: "", company: { name: "" } }; } else { return this.props.users.find( element => this.props.newUser.id === element.id ); } }; return ( <Modal {...{ show, onHide }} size="lg" animation={false} aria-labelledby="contained-modal-title-vcenter" centered="true" > <Modal.Header> <Modal.Title id="contained-modal-title-vcenter"> Edit client </Modal.Title> </Modal.Header> <Modal.Body> <form id="form-new-client"> <div className="form-row"> <div className="form-group col-md-6"> <label htmlFor="inputName">Name</label> <input name="name" type="text" className="form-control" id="inputName" placeholder="Name" onBlur={this.props.onBlurField} defaultValue={userEdited().name} /> </div> <div className="form-group col-md-6"> <label htmlFor="inputUsername">Username</label> <input name="username" type="text" className="form-control" id="inputPassword4" placeholder="Username" onBlur={this.props.onBlurField} defaultValue={userEdited().username} /> </div> </div> <div className="form-group"> <label htmlFor="Email">Email</label> <input name="email" type="email" className="form-control" id="inputEmail" placeholder="<EMAIL>" onBlur={this.props.onBlurField} defaultValue={userEdited().email} /> </div> <div className="form-row"> <div className="form-group col-md-6"> <label htmlFor="inputCompany">Company</label> <input name="company" type="text" className="form-control" id="inputCompany" placeholder="My Company name" onBlur={this.props.onBlurField} defaultValue={userEdited().company.name} /> </div> <div className="form-group col-md-6"> <label htmlFor="inputSite">Website</label> <input name="website" type="text" className="form-control" id="inputSite" placeholder="www.mycompany.com" onBlur={this.props.onBlurField} defaultValue={userEdited().website} /> </div> </div> <div className="form-group"> <label htmlFor="inputPhone">Phone</label> <input name="phone" type="text" className="form-control" id="inputPhone" placeholder="+55 09 1234-5678" onBlur={this.props.onBlurField} defaultValue={userEdited().phone} /> </div> </form> </Modal.Body> <Modal.Footer> <button className="btn btn-secondary" onClick={() => this.props.onHide()} > Close </button> <button type="submit" className="btn btn-primary" form="form-new-client" onClick={this.props.handleEditClient} > Save </button> </Modal.Footer> </Modal> ); } } export default ModalEditClient; <file_sep>import React, { Component } from 'react'; import {Link,NavLink} from 'react-router-dom'; const NavBar = () => <nav className="navbar navbar-expand-lg navbar-dark bg-dark"> <div className="collapse navbar-collapse justify-content-md-center pr-4" id="navbarsExample08"> <ul className="navbar-nav font-weight-bold"> <li className='nav-item'> <Link to='/' className='navbar-brand'>ManagerSys</Link> </li> <li className="nav-item"> <NavLink to='/products' className="nav-link">Products</NavLink> </li> <li className="nav-item"> <NavLink to='/clients' className="nav-link">Clients</NavLink> </li> </ul> </div> </nav> export default NavBar;<file_sep>//The Following code are my baby steps in REACT. import React, { Component } from "react"; import "./App.css"; import "bootstrap/dist/css/bootstrap.css"; import Products from "./components/Products"; import NavBar from "./components/NavBar"; import Clients from "./components/Clients"; import { BrowserRouter, Route } from "react-router-dom"; class App extends Component { constructor() { super(); this.state = { list: [], product: "", count: 0, users: [], isLoading: true, modalShow: false, newUser: {}, modalEdit: false }; } saveId = id => { let user = this.state.newUser; user["id"] = id; this.setState({ newUser: user }); }; handleAddList = id => { const updateList = this.state.list; updateList[id].count++; this.setState({ list: updateList }); }; handleSubmitClient = event => { event.preventDefault(); let user = this.state.newUser; user["id"] = this.state.users.length + 1; let updateUsers = this.state.users; updateUsers.push(user); this.setState({ users: updateUsers, modalShow: false, newUser: {} }); }; handleEditClient = event => { event.preventDefault(); let user = this.state.newUser; let updateUsers = [...this.state.users]; let index = this.state.users.findIndex(element => user.id === element.id); updateUsers[index] = Object.assign(updateUsers[index], user); this.setState({ users: updateUsers, modalEdit: false, newUser: {} }); }; onBlurField = event => { //event.preventDefault(); const field = event.target.name; let user = this.state.newUser; if (field === "company") user[field] = { name: event.target.value }; else user[field] = event.target.value; this.setState({ newUser: user }); }; handleDeleteList = id => { const updateList = this.state.list.filter(item => item.id !== id); this.setState({ list: updateList }); }; handleDeleteUsers = id => { if (window.confirm("Are you sure?")) { const updateUsers = this.state.users.filter(item => item.id !== id); this.setState({ users: updateUsers }); } }; handleRemoveList = id => { if (this.state.list[id].count > 0) { let updateList = this.state.list; updateList[id].count--; this.setState({ list: updateList }); } }; handleSubmitList = event => { event.preventDefault(); if (this.state.product !== "") { let countUp = this.state.count + 1; const newProduct = { id: countUp, description: this.state.product, count: 0 }; let updateList = []; if (this.state.list.length > 0) { updateList = this.state.list; updateList.push(newProduct); } else { updateList = [newProduct]; } this.setState({ list: updateList, product: "", count: countUp }); } }; onChangeProduct = event => { this.setState({ product: event.target.value }); }; setUsers = props => { this.setState({ users: props.users, isLoading: props.isLoading }); }; toggleModalSave = () => { this.setState({ modalShow: !this.state.modalShow }); }; toggleModalEdit = () => { this.setState({ modalEdit: !this.state.modalEdit }); }; setModalEdit = (id = null) => { if (id) { this.saveId(id); this.toggleModalEdit(); } else { this.toggleModalEdit(); } }; render() { return ( <BrowserRouter> <div> <NavBar /> <Route exact path="/" render={props => ( <Products add={this.handleAddList} rem={this.handleRemoveList} del={this.handleDeleteList} subm={this.handleSubmitList} change={this.onChangeProduct} list={this.state.list} product={this.state.product} count={this.state.count} /> )} /> <Route path="/products" render={props => ( <Products add={this.handleAddList} rem={this.handleRemoveList} del={this.handleDeleteList} subm={this.handleSubmitList} change={this.onChangeProduct} list={this.state.list} product={this.state.product} count={this.state.count} /> )} /> <Route path="/clients" render={props => ( <Clients users={this.state.users} isLoading={this.state.isLoading} setUsers={this.setUsers} del={this.handleDeleteUsers} setModal={this.toggleModalSave} modalShow={this.state.modalShow} handleSubmitClient={this.handleSubmitClient} onBlurField={this.onBlurField} modalEdit={this.state.modalEdit} setModalEdit={this.setModalEdit} handleEditClient={this.handleEditClient} saveId={this.saveId} newUser={this.state.newUser} /> )} /> </div> </BrowserRouter> ); } } export default App; <file_sep>import React, { Component } from 'react'; import 'bootstrap/dist/css/bootstrap.css' class ProductsPanel extends Component { render() { const {list,addItem,delItem,remItem}=this.props; return ( list.map((item,index)=> <div key={index}> <div className='row mt-2 mb-4'> <div className='col-md-1 font-weight-bold'> {item.count} </div> <div className='col-md-1 p-auto'> <button className='btn btn-dark font-weight-bold' onClick={()=>addItem(index)}> + </button> </div> <div className='col-md-1 p-auto'> <button className='btn btn-dark' onClick={()=>remItem(index)}> - </button> </div> <div className='col-md-5 font-weight-bold'> {item.description} </div> <div className='col-md-2'> <button className='btn btn-danger rounded-circle font-weight-bold' onClick={()=>delItem(item.id)}> X </button> </div> </div> </div> ) ); } } export default ProductsPanel;
0ba4093409d8bb1b14ba9801427577f73df32141
[ "JavaScript" ]
5
JavaScript
gabrielmarden/React-Product-Form
6837970803ce76f6389961c69e7fa283e322d101
bbef9be9189e6a67a766c699a04a1e8fd51d542c
refs/heads/master
<repo_name>anlancan96/stateofchain<file_sep>/index.js import path from 'path' const express = require('express'); const compression = require('compression'); const bodyParser = require('body-parser'); const PORT = process.env.NODE_ENV || 3000; const app = express(); app.set('views', path.join(__dirname, 'views')); var engine = require('ejs-locals'); app.engine('ejs', engine); app.set('view engine', 'ejs'); app.use(compression()); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.use(express.static(__dirname + '/public')); app.use(express.static(__dirname + '/views')); app.use((req, res, next) => { res.locals.sharee = { url: req.originalUrl } res.header("Access-Control-Allow-Origin", '*'); res.header('Access-Control-Allow-Credentials', 'true') res.header("Access-Control-Allow-Headers", "X-PINGOTHER, Content-Type"); res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"); next(); }); app.use(function (req, res, next) { res.locals.shareall = { url: req.originalUrl } next(); }) app.use('/admin', function (req, res, next) { res.locals.shareall = { mdun: 'admin' } next(); }) import adminRouter from './routers/admin' app.use('/admin', adminRouter); import masterRouter from './routers/master' app.use('/master', function (req, res, next) { res.locals.shareall = { mdun: 'master' } next(); }) app.use('/master', masterRouter); import indexRouter from './routers/index' app.use('/', indexRouter); app.listen(PORT, (err) => { if(err) return console.log(err); console.log('Server listening on: ' + PORT); }) <file_sep>/routers/index.js const router = require('express').Router(); // import home controller import Home from '../controllers/HomeController' import Detail from '../controllers/DetailController' /* GET home page. */ router.get('/', Home.index); /* GET home page. */ router.get('/detail', Home.index); router.post('/detail', Detail.index); export default router;<file_sep>/controllers/AdminController.js // this is home controller const mdun = 'admin' module.exports = { index: (req, res) => { res.render(mdun + '/dashboard', { title: 'Dashboard ' }); }, user: (req, res) => { res.render(mdun + '/user', { title: 'List User ' }); }, addUser: (req, res) => { res.render(mdun + '/user/add', { title: 'Add User ', event: 'createUser()' }) }, editUser: (req, res) => { res.render(mdun + '/user/edit', { title: 'Add User ', event: 'editUser()' }) }, product: (req, res) => { res.render(mdun + '/product', { title: 'List Product ' }); }, addProduct: (req, res) => { res.render(mdun + '/product/add', { title: 'Add Product ' }) }, warranty: (req, res) => { res.render(mdun + '/warranty', { title: 'List Warranty ' }); }, addWarranty: (req, res) => { res.render(mdun + '/warranty/add', { title: 'Add Warranty', type: 1 }) }, warrantyEdit: (req, res) => { res.render(mdun + '/warranty/add', { title: 'Edit Warranty', type: 2, // 2 la sua id: req.params.id }) }, warrantyDetail: (req, res) => { res.render(mdun + '/warranty/detail', { title: 'Detail Warranty', type: 3, // 3 la chitiet id: req.params.id }) }, warrantyByer: (req, res) => { res.render(mdun + '/warranty/byer', { title: 'Byer Warranty', type: 3, // 3 la chitiet id: req.params.id }) }, }<file_sep>/controllers/DetailController.js const mdun = 'detail' module.exports = { index: (req, res) => { res.render(mdun, { title: 'Detail', id:req.body.addressWarranty }); } }<file_sep>/README.md ``` Node version: v10.11.0 NPM version: v6.4.1 ``` ### Cấu trúc Project * Controllers : Nơi xử lý logic và định nghĩa các phương thức xử lý cho 1 route. * Definitions: Nơi lưu trữ và đặt các biến không thể thay đổi vd: API_USER = '/api-user'. * Dist: Nơi chứa các file build từ ES6 -> ES5. * Errors: Nơi định nghĩa các lỗi xử lý vào ra, ... * Models: Nơi định nghĩa đối tượng dùng để tương tác với cơ sở dữ liệu Ví dụ : Một phần mềm chơi game => sẽ có các đối tượng như ngừoi chơi, enemies,... thì sẽ chia folder như sau: ``` Models: | --- player --- index.js (định nghĩa đối tượng: vd: tên, tuổi, tài khoản, mật khẩu, điểm,...) --- validator.js (định nghĩa các phương thức xác minh các trường dữ liệu như: tuổi thì phải là số nguyên) |--- enemies --- index.js --- validator.js ``` * Public: Nơi chứa các tệp css, images, js. * Routers: Nơi chứa các methods GET, PUT, POST, DELETE cho từng đối tượng. * Views: Chứa các file html được server trả về client hiển thị cho ngừoi dùng. * package.json: Chứa các scripts, node_modules cần thiết cho việc chạy ứng dụng. <file_sep>/controllers/MasterController.js // this is home controller const mdun = 'master' module.exports = { index: (req, res) => { res.render(mdun + '/dashboard', { title: 'Dashboard' }); }, agency: (req, res) => { res.render(mdun + '/agency', { title: 'Agency ' }); }, agencyadd: (req, res) => { res.render(mdun + '/agency/add', { title: 'Add Agency', type: 1 // 1 la them moi }) }, agencyedit: (req, res) => { res.render(mdun + '/agency/add', { title: 'Edit Agency', type: 2, // 2 la sua id: req.params.id }) }, customer: (req, res) => { res.render(mdun + '/customer', { title: 'Customer Admin' }); }, addcustomer: (req, res) => { res.render(mdun + '/customer/add', { title: 'Add Address Customer' }) }, product: (req, res) => { res.render(mdun + '/product', { title: 'Product List ' }); }, addproduct: (req, res) => { res.render(mdun + '/product/add', { title: 'Add Address Product ' }) } }
52387fcc3f05dc085b452d896f13da82a8a54efd
[ "JavaScript", "Markdown" ]
6
JavaScript
anlancan96/stateofchain
818fafccce402767889a6884dc942fc6b3e956c8
5aaacdd0e0e4430792e5e340d98fece20ec8a015
refs/heads/master
<repo_name>Stances/NFG.TimeTracker<file_sep>/NFG.TimeTracker/ViewModels/ObservableObject.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; using System.Reflection; namespace NFG.TimeTracker.ViewModels { public abstract class ObservableObject<T>:INotifyPropertyChanged { #region Implementation of INotifyPropertyChanged /// <summary> /// Occurs when a property value changes /// </summary> public event PropertyChangedEventHandler PropertyChanged; #endregion /// <summary> /// Called when [property changed] /// </summary> /// <param name="property"> The property.</param> public void OnPropertyChanged(Expression <Func <T,object >> property ) { var propertyName = GetPropertyName(property); if (PropertyChanged != null) { var handler = PropertyChanged; handler(this, new PropertyChangedEventArgs(propertyName)); } } /// <summary> /// Gets property name /// </summary> /// <param name ="expression"> The expression.</param> /// <returns></returns> private string GetPropertyName(Expression<Func<T, object>> expression) { if (expression == null) { throw new ArgumentNullException("propertyExpression"); } var memberExpression = expression.Body as MemberExpression; if (memberExpression == null) { throw new ArgumentException("The expression is not a member access expression.", "expression"); } } } }
afb9f9f31e942e9ea7943345ca75318494e1750c
[ "C#" ]
1
C#
Stances/NFG.TimeTracker
89357f111e51192b68d6dd8b86f2bde00dc1a5e6
7ffbc48d3d2f51ba4ccc8f14e681f66a0f102d71
refs/heads/master
<file_sep>docker build \ --rm=true \ --build-arg http_proxy=$http_proxy \ --build-arg HTTP_PROXY=$http_proxy \ --build-arg HTTPS_PROXY=$https_proxy \ --build-arg https_proxy=$https_proxy \ --build-arg no_proxy=$no_proxy \ --tag=hpestorage/csp_3par_primera:v0.1 <file_sep>package models type DataInJson struct { Array_Ip string `json:"array_ip"` User_Name string `json:"username"` Password string `json:"<PASSWORD>"` } type Token struct { Data DataInJson `json:"data"` } type Session_Key struct { Key string `json:"key"` } type SessionTokenResponseNested struct { Id string `json:"id"` Array_Ip string `json:"array_ip"` Username string `json:"username"` CreationTime string `json:"creation_time"` ExpiryTime string `json:"expiry_time"` Session_Token string `json:"session_token"` } type SessionTokenResponse struct { Data SessionTokenResponseNested `json:"data"` } <file_sep>package main import "github.com/wdurairaj/csp_3par_primera/restserver" import log "github.com/hpe-storage/common-host-libs/logger" /* Request Router for various endpoints of the CSP specification */ func HandleRequest(){ log.Println("HPE 3PAR CSP - HandleRequest invoked") restserver.HandleRequest() } func main(){ HandleRequest() } <file_sep>package models /* Create Request: { "data": { "name": "my-new-volume", "size": "1073741824", "description": "my first volume", "config": { "parameter1": "default", "parameter2": false } } } Create Response: { "data": { "id": "063b5de80e54af7a6b0000000000000000000000d0", "name": "my-new-volume", "size": 1073741824, "description": "my first volume", "published": false, "base_snapshot_id": "", "volume_group_id": "073b5de80e54af7a6b000000000000000000000098", "config": { "parameter1": "default", "parameter2": false } } } */ type config struct { Cpg string `json:"cpg"` Tpvv string `json:"tpvv"` } type CreateRequestVolume struct { Name string `json:"name"` Size int64 `json:"size"` Description string `json:"description"` Config config `json:"config"` } type Create_volume_request struct { Data CreateRequestVolume `json:"data"` } <file_sep>module github.com/wdurairaj/csp_3par_primera go 1.12 require ( github.com/go-resty/resty/v2 v2.1.0 github.com/google/uuid v1.1.1 github.com/gorilla/mux v1.7.3 github.com/hpe-storage/common-host-libs v0.0.0-20191024202731-60b13fd67326 github.com/sirupsen/logrus v1.4.2 // indirect gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect ) <file_sep>package models /* Create Response: { "data": { "id": "063b5de80e54af7a6b0000000000000000000000d0", "name": "my-new-volume", "size": 1073741824, "description": "my first volume", "published": false, "base_snapshot_id": "", "volume_group_id": "073b5de80e54af7a6b000000000000000000000098", "config": { "parameter1": "default", "parameter2": false } } } */ type configVolumeResponse struct { Cpg string `json:"cpg"` Tpvv string `json:"tpvv"` } type CreateVolumeResponse struct { Id string `json:"id"` Name string `json:"name"` Size int64 `json:"size"` Description string `json:"description"` Published bool `json:"published"` Base_Snapshot_Id string `json:"base_snapshot_id"` Volume_Group_Id string `json:"volume_group_id"` Config configVolumeResponse `json:"config"` UserCPG string `json:"userCPG"` } type CreateVolumeResponse1 struct { Id string `json:"uuid"` Name string `json:"name"` Size int64 `json:"sizeMiB"` Description string `json:"description"` Published bool `json:"published"` Base_Snapshot_Id string `json:"base_snapshot_id"` Volume_Group_Id string `json:"volume_group_id"` Config configVolumeResponse `json:"config"` //UserCPG string `json:"userCPG"` } type Create_volume_response struct { Data CreateVolumeResponse `json:"data"` } type Get_volume_response struct { Data []CreateVolumeResponse `json:"data"` } type GetVolumeResponseById struct { Total int32 `json:"total` Members []CreateVolumeResponse1 `json:"members"` } type Get_volume_response1 struct { Data CreateVolumeResponse1 `json:"data"` } <file_sep>package restserver import ( "encoding/json" "fmt" "io/ioutil" "net/http" "net/url" // "reflect" "strings" "github.com/google/uuid" log "github.com/hpe-storage/common-host-libs/logger" "github.com/wdurairaj/csp_3par_primera/hpe3parcsp" "github.com/wdurairaj/csp_3par_primera/models" ) var session_key models.Session_Key var token_struct models.Token var sessKey string var headerArrayIp string var CacheMap map[string]string func delete_vol_by_id(w http.ResponseWriter, r *http.Request) { log.Println(">>>>>>> Delete volume by id") defer log.Println(" <<<<<<<<<<<<<<<<< Delete Volume by id") sessKey = r.Header.Get("x-auth-token") headerArrayIp = r.Header.Get("x-array-ip") uriString := r.RequestURI uriSplit := strings.Split(uriString, "/") volUUID := uriSplit[4] volUUID = strings.Split(volUUID,"?")[0] //reqBody, _ := ioutil.ReadAll(r.Body) /* query := "query=\"uuid EQ " + volUUID + "\"" fmt.Println("Printing query ", query) encodedQuery := url.PathEscape(query) fmt.Println("Encoded query is : ", encodedQuery) getVolUri := "https://" + headerArrayIp + ":8080/api/v1/volumes?" + encodedQuery fmt.Println("Get volume query string uri is ", getVolUri) getResp, err := hpe3parcsp.HttpRestyGet(getVolUri, session_key.Key) if err != nil { fmt.Println("Error is : ", err) } fmt.Println("Printing status of get response ", getResp.Status()) mapGetVolRequest := make(map[string]interface{}) err2 := json.Unmarshal(getResp.Body(), &mapGetVolRequest) if err2 != nil { fmt.Println("Error is : ", err2) } var volName string for k, v := range mapGetVolRequest { fmt.Println("\n Key is ", k) fmt.Println("\n Value is ", v) vt := reflect.TypeOf(v) switch vt.Kind() { case reflect.String: fmt.Println("value of key %s is of time string", k) case reflect.Slice: fmt.Println("Printing vt ", vt) fmt.Println("value of key %s is of type slice", k) fmt.Println("Printing the slice values ") for index, itemCopy := range v.([]interface{}) { fmt.Println("Index is ", index) fmt.Println("itemCopy is ", itemCopy) itemValueType := reflect.TypeOf(itemCopy) fmt.Println("For key, type is %s ", itemValueType) switch itemValueType.Kind() { case reflect.Map: for k1, v1 := range itemCopy.(map[string]interface{}) { fmt.Println("I am printing Key ", k1) fmt.Println("I am printing Value ", v1) if k1 == "name" { volName = v1.(string) } } } } case reflect.Map: vmap := v.(map[string]interface{}) for confKey, confVal := range vmap { confValType := reflect.TypeOf(confVal) switch confValType.Kind() { case reflect.String: fmt.Println("Inside Map, this is a string type for key %s ", confKey) case reflect.Map: if confKey == "name" { fmt.Println("Printing the name of volume", confVal) volName = confVal.(string) } case reflect.Bool: fmt.Println("Inside Map, this is a boolean type for key %s ", confKey) default: fmt.Println("Inside Map, this is some other type for key %s ", confKey) } } fmt.Println("value for key %s is of map type", k) default: fmt.Println("Some other type for key %s ", k) } }*/ log.Printf("Cache Map %v", CacheMap) log.Println(" vol uuid : ", volUUID) // TODO: investigate the failure //volUUID = strings.Split(volUUID,"?")[0] volName := CacheMap[volUUID] log.Println("Printing name of the volume from CacheMap ", volName) deleteUrl := "https://" + headerArrayIp + ":8080/api/v1/volumes/" + volName log.Println("DELETE url for volume is ", deleteUrl) deleteResp, delErr := hpe3parcsp.HttpRestyDelete(deleteUrl, session_key.Key) if delErr != nil { log.Println("Error after delete call is : ", delErr) } delete(CacheMap, volUUID) log.Println("status of delete rest call is ", deleteResp.Status()) if deleteResp.StatusCode() == 200 { w.WriteHeader(deleteResp.StatusCode()) } } func get_vol_by_id(w http.ResponseWriter, r *http.Request) { log.Println(">>>>>>>>> Get Volume By Id ") defer log.Println("<<<<<< Get Volume By Id") sessKey = r.Header.Get("x-auth-token") headerArrayIp = r.Header.Get("x-array-ip") uriString := r.RequestURI uriSplit := strings.Split(uriString, "/") log.Println("Printing len of uriSplit", len(uriSplit)) var volUUID string var getByNameQuery bool if len(uriSplit) == 4 { // /containers/v1/volumes?name=my-new-volum volUUID = r.URL.Query().Get("name") getByNameQuery = true } else { getByNameQuery = false // /containers/v1/volumes/{uuid} or // /containers/v1/volumes/pvc-{uuid} volUUID = uriSplit[4] } log.Println("Printing volUUID ", volUUID) log.Println("Passed uri string is ", uriString) log.Println("Session key string is ", sessKey) log.Println("Header Array Ip string is ", headerArrayIp) query := "" getVolUri := "" encodedQuery := "" if getByNameQuery { query = volUUID[:31] //encodedQuery = url.PathEscape(query) getVolUri = "https://" + headerArrayIp + ":8080/api/v1/volumes/" + query } else { if strings.HasPrefix(volUUID,"pvc") { query = volUUID[:31] getVolUri = "https://" + headerArrayIp + ":8080/api/v1/volumes/" + query }else { query = "query=\"uuid EQ " + volUUID + "\"" encodedQuery = url.PathEscape(query) getVolUri = "https://" + headerArrayIp + ":8080/api/v1/volumes?" + encodedQuery } } //getVolUri = "https://" + headerArrayIp + ":8080/api/v1/volumes?" + encodedQuery //log.Println("Printing query ", query) //getVolUri := "https://" + headerArrayIp + ":8080/api/v1/volumes?" + encodedQuery //getVolUri := log.Println("Get volume query string uri is ", getVolUri) getResp, err := hpe3parcsp.HttpRestyGet(getVolUri, session_key.Key) if err != nil { fmt.Println("Error is : ", err) } fmt.Println("Printing get response for volume ", getResp.String()) fmt.Println("Printing status of get response ", getResp.Status()) if getResp.StatusCode() == 404 { w.WriteHeader(http.StatusNotFound) errorStr := "{\"errors\": [" + "{" + " \"code\": \"Not Found\", " + " \"message\": \"Volume with name " + volUUID[:31] + " not found.\"" + "}" + "]" + "}" fmt.Fprint(w, errorStr) return } if getResp.StatusCode() == 403 { //w.WriteHeader(http.StatusUnauthorized) //return log.Println("Saved AuthURI ", hpe3parcsp.AuthURI) log.Println("Saved token post body ", hpe3parcsp.AuthTokenPostBody) resp, _ := hpe3parcsp.HttpPost(hpe3parcsp.AuthURI, hpe3parcsp.AuthTokenPostBody) json.Unmarshal(resp.Body(), &session_key) sessKey = session_key.Key getResp, err = hpe3parcsp.HttpRestyGet(getVolUri, session_key.Key) } mapGetVolRequest := make(map[string]interface{}) //here wright get call for volume information from 3PAR str := getResp.String() log.Println("GET VOLUME RESPONSE ", str) err2 := json.Unmarshal(getResp.Body(), &mapGetVolRequest) if err2 != nil { fmt.Println("Error is : ", err2) } fmt.Println("Here Response for get vol after unmarshal is :", mapGetVolRequest) /*id, err := uuid.NewUUID() if err != nil { // handle error log.Errorln(" uuid gen error") } */ if getByNameQuery { //var resBodyCreateVolString models.Create_volume_response var volumesList models.Get_volume_response volumesList.Data = make([]models.CreateVolumeResponse, 1) volumesList.Data[0] = models.CreateVolumeResponse{} //idStr := fmt.Sprintf("%f", volumesList.Data[0].Id = mapGetVolRequest["uuid"].(string) //provisioningType := []string{"full","tpvv","snp","peer","unknown","tdvv","dds" } volumesList.Data[0].Name = volUUID[:31] var computeSizeInMiB int64 computeSizeInMiB = int64(mapGetVolRequest["sizeMiB"].(float64) * 1048576) volumesList.Data[0].Size = int64(computeSizeInMiB) volumesList.Data[0].Config.Cpg = mapGetVolRequest["userCPG"].(string) if mapGetVolRequest["provisioningType"] == 1 { volumesList.Data[0].Config.Tpvv = "true" } else { volumesList.Data[0].Config.Tpvv = "false" } if err2 != nil { log.Println("Error Mapping Create Volume Response is : ", err) log.Println(w, err) } else { log.Printf("Response for get vol after unmarshal is %#v:", volumesList) volumeResponseMap, _ := json.Marshal(volumesList) log.Println(" GET VOLUME BY NAME ; ", string(volumeResponseMap)) fmt.Fprint(w, string(volumeResponseMap)) } } else { var resBodyCreateVolString models.GetVolumeResponseById //var createVolResponse models.CreateVolumeResponse var resBody models.Get_volume_response1 err2 := json.Unmarshal(getResp.Body(), &resBodyCreateVolString) if err2 != nil { fmt.Println("Error is : ", err2) } fmt.Println("Here Response for get vol after unmarshal is :", resBodyCreateVolString) //createVolResponse1 := make([]models.CreateVolumeResponse, 1) //createVolResponse1 = resBodyCreateVolString.Members[0] //createVolResponse.Id = //createVolResponse.Name = volUUID[:31] //var computeSizeInMiB int64 //computeSizeInMiB = int64(mapGetVolRequest["sizeMiB"].(float64) * 1048576) //998643.8095238095) //createVolResponse.Size = int64(computeSizeInMiB) //createVolResponse.Size = int32(mapGetVolRequest["sizeMiB"].(float64)) if (len(resBodyCreateVolString.Members)) == 0 { w.WriteHeader(http.StatusNotFound) return } //resBody.Data = make([]models.CreateVolumeResponse1, 1) resBody.Data = models.CreateVolumeResponse1{} resBody.Data = (resBodyCreateVolString.Members)[0] resBody.Data.Size = resBody.Data.Size * 1048576 //resBody.Data[0].Config.Cpg = (resBodyCreateVolString.Members)[0].UserCPG if mapGetVolRequest["provisioningType"] == 1 { resBody.Data.Config.Tpvv = "true" } else { resBody.Data.Config.Tpvv = "false" } //resBody.Data = make([]models.CreateVolumeResponse, 1) //resBody.Data[0] = createVolResponse1[0] /*resBodyCreateVolString.Data[0] = models.CreateVolumeResponse{} resBodyCreateVolString.Data[0].Id = idStr //provisioningType := []string{"full","tpvv","snp","peer","unknown","tdvv","dds" } resBodyCreateVolString.Data[0].Name = volUUID[:31] resBodyCreateVolString.Data[0].Size = int32(mapGetVolRequest["sizeMiB"].(float64)) resBodyCreateVolString.Data[0].Config.Cpg = mapGetVolRequest["userCPG"].(string)*/ if err2 != nil { log.Println("Error Mapping Create Volume Response is : ", err) log.Println(w, err) } else { log.Printf("Response for get vol after unmarshal is %#v:", resBody) volumeResponseMap, _ := json.Marshal(resBody) log.Println("GET VOLUME by id ", string(volumeResponseMap)) fmt.Fprint(w, string(volumeResponseMap)) } } } func homePage(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Welcome!") fmt.Println("Endpoint Hit") } func create_volume(w http.ResponseWriter, r *http.Request) { /* Create Request: { "data": { "name": "my-new-volume", "size": "1073741824", "description": "my first volume", "config": { "parameter1": "default", "parameter2": false } } } Create Response: { "data": { "id": "063b5de80e54af7a6b0000000000000000000000d0", "name": "my-new-volume", "size": 1073741824, "description": "my first volume", "published": false, "base_snapshot_id": "", "volume_group_id": "073b5de80e54af7a6b000000000000000000000098", "config": { "parameter1": "default", "parameter2": false } } } */ log.Println(">>>> Create Volume Call ") defer log.Println(" <<<<< Create Volume Call") sessKey = r.Header.Get("x-auth-token") reqBody, _ := ioutil.ReadAll(r.Body) reqB := string(reqBody) log.Println("Create volume request is : %v", reqB) log.Println("Session key from request header: ", sessKey) var create_volume_request models.Create_volume_request err := json.Unmarshal(reqBody, &create_volume_request) if err != nil { log.Println("Error is : ", err) } log.Println("create volume request (after unmarshal) \n", create_volume_request) log.Println("session key for create volume: ", sessKey) pbMapForCreateVol := make(map[string]interface{}) pvName := create_volume_request.Data.Name pbMapForCreateVol["name"] = pvName[:31] sizeInt := create_volume_request.Data.Size pbMapForCreateVol["sizeMiB"] = (int)(sizeInt / 1048576) config := create_volume_request.Data.Config log.Println("Config map is ", config) log.Println("Printing the configMap", config) pbMapForCreateVol["cpg"] = config.Cpg tpvv_string := config.Tpvv var tpvv = true if tpvv_string == "true" { tpvv = true } log.Println("tpvv is ", tpvv) headerArrayIp = r.Header.Get("x-array-ip") log.Println("Printing array ip ", headerArrayIp) pbMapForCreateVol["tpvv"] = tpvv log.Println("Create volume name ", pbMapForCreateVol["name"]) mapPBCreateVol, _ := json.Marshal(pbMapForCreateVol) postBodyCreateVolString := string(mapPBCreateVol) log.Println("post body - create volume ", postBodyCreateVolString) createVolURI := "https://" + headerArrayIp + ":8080/api/v1/volumes" response, err := hpe3parcsp.HttpSessionPost(createVolURI, postBodyCreateVolString, sessKey) log.Println("response for create Vol call is ", response.String()) if err != nil { log.Println("ERRROR: response for create Vol call is ", err) } log.Println("Response status is : ", response.Status()) var resBodyCreateVolString models.Create_volume_response var resBodyMap = make(map[string]interface{}) if response.Status() == "201 Created" { getVolByNameString := "https://" + headerArrayIp + ":8080/api/v1/volumes/" volName := create_volume_request.Data.Name getVolByNameUri := getVolByNameString + volName[:31] response1, err1 := hpe3parcsp.HttpRestyGet(getVolByNameUri, sessKey) log.Println("Printing response status of getvolcall : ", response1.Status()) if err1 != nil { log.Println("Error (get volume call) :", err1) } log.Println("Response for get vol is :", response1.String()) err2 := json.Unmarshal(response1.Body(), &resBodyMap) /*id, err := uuid.NewUUID() if err != nil { // handle error log.Errorln(" uuid gen error") }*/ //resBodyCreateVolString.Data.Id = response1. fmt.Println(" =================== VOLUME MAPPED : ", resBodyMap) resBodyCreateVolString.Data.Id = resBodyMap["uuid"].(string) resBodyCreateVolString.Data.Name = resBodyMap["name"].(string) resBodyCreateVolString.Data.Size = int64(resBodyMap["sizeMiB"].(float64)) resBodyCreateVolString.Data.Size = resBodyCreateVolString.Data.Size * 1048576 resBodyCreateVolString.Data.Config.Cpg = create_volume_request.Data.Config.Cpg resBodyCreateVolString.Data.Config.Tpvv = create_volume_request.Data.Config.Tpvv //CacheMap[resBodyCreateVolString.Data.Id] = make(map[string]string) CacheMap[resBodyCreateVolString.Data.Id] = resBodyCreateVolString.Data.Name log.Printf("CacheMap %v", CacheMap) if err2 != nil { log.Println("Error Mapping Create Volume Response is : ", err) log.Println(w, err) } else { log.Printf("Response for get vol after unmarshal is %#v:", resBodyCreateVolString) volumeResponseMap, _ := json.Marshal(resBodyCreateVolString) fmt.Fprint(w, string(volumeResponseMap)) } } else { // Used for reinvoke this REST endpoint by CSI driver. if response.Status() == "403 Forbidden" { fmt.Printf("WILLIAM: responding with unauthorized") w.WriteHeader(http.StatusUnauthorized) } else { fmt.Println(" ERROR status", response.Status()) fmt.Println(" ERROR response", response.String()) w.WriteHeader(response.StatusCode()) fmt.Println(w, response.String()) } } } //noinspection ALL func create_array_session(w http.ResponseWriter, r *http.Request) { log.Println(">>>> create_array_session /containers/v1/tokens") defer log.Println("<<<<< create_array_session") reqBody, _ := ioutil.ReadAll(r.Body) reqB := string(reqBody) log.Println("Received request : %v", reqB) json.Unmarshal(reqBody, &token_struct) user := token_struct.Data.User_Name password := token_struct.Data.Password arrayIp := token_struct.Data.Array_Ip log.Println("Array ip is : ", arrayIp) postBodyMap := make(map[string]string) postBodyMap["user"] = user postBodyMap["password"] = <PASSWORD> mapPBS, _ := json.Marshal(postBodyMap) postBodyString := string(mapPBS) log.Println("post_body_map_string is ", postBodyString) postUriForSessionToken := "https://" + arrayIp + ":8080/api/v1/credentials" response, err := hpe3parcsp.HttpPost(postUriForSessionToken, postBodyString) log.Println("SESSION KEY Response body is", response.String()) json.Unmarshal(response.Body(), &session_key) // session_token := session_key.Key log.Println("Printing only session key out: ", session_key.Key) log.Println("Printing only session key struct out: ", session_key) id, err := uuid.NewUUID() if err != nil { // handle error log.Errorln(" uuid gen error") } uuidString := id.String() fmt.Printf(uuidString) TokenResponseMap := make(map[string]string) TokenResponseMap["id"] = uuidString TokenResponseMap["array_ip"] = token_struct.Data.Array_Ip TokenResponseMap["username"] = token_struct.Data.User_Name TokenResponseMap["creation_time"] = "" TokenResponseMap["expiry_time"] = "" TokenResponseMap["session_token"] = session_key.Key nestedMapTRM := make(map[string]interface{}) nestedMapTRM["data"] = TokenResponseMap mapTRM, _ := json.Marshal(nestedMapTRM) TokenResponseString := string(mapTRM) log.Println("TokenResponseString is ", TokenResponseString) fmt.Fprint(w, TokenResponseString) } func get_all_tokens(w http.ResponseWriter, r *http.Request) { log.Println("get all tokens invoked") fmt.Println("listing all token requests") fmt.Println("printing the session token key value: ", session_key.Key) } <file_sep>package hpe3parcsp import ( "crypto/tls" "github.com/go-resty/resty/v2" log "github.com/hpe-storage/common-host-libs/logger" "github.com/wdurairaj/csp_3par_primera/models" ) var session_key models.Session_Key var token_struct models.Token var sessKey string var headerArrayIp string var AuthTokenPostBody string var AuthURI string func HttpRestyDelete(URI string, sessionKey string) (*resty.Response, error) { client := resty.New() client.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true}) headerMap := make(map[string]string) headerMap["X-HP3PAR-WSAPI-SessionKey"] = sessionKey headerMap["Content-type"] = "application/json" resp, err := client.R(). SetHeaders(headerMap). Delete(URI) if err != nil { return nil, err } else { return resp, nil } } func HttpRestyGet(URI string, sessionKey string) (*resty.Response, error) { client := resty.New() client.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true}) headerMap := make(map[string]string) headerMap["X-HP3PAR-WSAPI-SessionKey"] = sessionKey headerMap["Content-type"] = "application/json" resp, err := client.R(). SetHeaders(headerMap). Get(URI) if err != nil { return nil, err } else { return resp, nil } } func HttpSessionPost(URI string, postBody string, sessionKey string) (*resty.Response, error) { client := resty.New() client.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true}) log.Println("Post Body : ", postBody) log.Println("Post Uri : ", URI) log.Println("Session Key Passed: ", sessionKey) headerMap := make(map[string]string) headerMap["X-HP3PAR-WSAPI-SessionKey"] = sessionKey headerMap["Content-type"] = "application/json" resp, err := client.R(). SetHeaders(headerMap). SetBody([]byte(postBody)). Post(URI) if err != nil { return nil, err } else { return resp, nil } } func HttpPost(URI string, postBody string) (*resty.Response, error) { client := resty.New() client.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true}) resp, err := client.R(). SetHeader("Content-type", "application/json"). SetBody([]byte(postBody)). Post(URI) if err != nil { return nil, err } else { AuthTokenPostBody = postBody AuthURI = URI return resp, nil } } <file_sep>FROM golang:latest ADD main /bin/ EXPOSE 10000 CMD ["/bin/main"] <file_sep>## HPE 3PAR and HPE Primera Container Storage Provider (CSP) ### Steps to build 1. `go mod vendor` 2. `go build cmd/main.go` 3. `cp main ./build && cd ./build` 4. `docker build --rm=true --build-arg http_proxy=$http_proxy --build-arg HTTP_PROXY=$http_proxy --build-arg HTTPS_PROXY=$https_proxy --build-arg https_proxy=$https_proxy --build-arg no_proxy=$no_proxy --tag=sandanar/csp_3par_primera:v0.1 .` 5. `docker push sandanar/csp_3par_primera:v0.1` ### Step to deploy the CSP as a kubernetes service `kubectl create -f https://raw.githubusercontent.com/wdurairaj/csp_3par_primera/master/build/hpe3parprimera.yml` ### Step to create the CSI driver `kubectl create -f https://github.com/wdurairaj/csp_3par_primera/raw/master/build/hpe-csi-k8s-1.16.yaml` ### Step to create a sample SC, PVC using Dynamic Provisioning `kubectl create -f https://raw.githubusercontent.com/wdurairaj/csp_3par_primera/master/build/test-pvc.yml` ### Console output of kubernetes (1.16.2) ``` [root@CSSOSECO-MSTR-00-6961 ~]# kubectl get service -n kube-system NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE hpe3parprimera-csp-svc ClusterIP 10.97.104.212 <none> 10000/TCP 15m kube-dns ClusterIP 10.96.0.10 <none> 53/UDP,53/TCP,9153/TCP 2d23h [root@CSSOSECO-MSTR-00-6961 ~]# kubectl get pods -o wide --all-namespaces NAMESPACE NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES kube-system coredns-5644d7b6d9-9jmfk 1/1 Running 0 2d23h 10.32.0.3 cssoseco-mstr-00-6961 <none> <none> kube-system coredns-5644d7b6d9-wbcdd 1/1 Running 0 2d23h 10.32.0.4 cssoseco-mstr-00-6961 <none> <none> kube-system csp-service-7f86855475-gqxph 1/1 Running 0 15m 10.44.0.1 cssoseco-wrkr-01-6963 <none> <none> ``` ### Curl commands to test the change (using first session token creation, followed by volume creation) ``` [root@CSSOSECO-MSTR-00-6961 ~]# curl -H 'Content-type: application/json' -X POST -d '{"data": {"array_ip": "192.168.67.7", "user_name": "3paradm","password": "<PASSWORD>"}}' http://10.97.104.212:10000/containers/v1/tokens {"array_ip":"192.168.67.7","creation_time":"","expiry_time":"","id":"42a6f87a-f676-11e9-a88c-962f6e895f01","session_token":"<KEY>","username":"3paradm"} curl -H 'x-array-ip: 192.168.67.7' -H 'x-auth-token: <KEY>' -H 'Content-type: application/json' -X POST -d '{"data": {"name": "my-new-volume2", "size": 3000,"description": "my first volume","config": {"parameter1": "default","parameter2": false,"cpg":"FC_r6","tpvv":"true"}}}' http://127.0.0.1:10000/containers/v1/volumes ``` <file_sep>package restserver import ( "fmt" "log" "net/http" "github.com/gorilla/mux" ) func HandleRequest() { myRouter := mux.NewRouter().StrictSlash(true) CacheMap = make(map[string]string) myRouter.HandleFunc("/", homePage) myRouter.HandleFunc("/containers/v1/tokens", create_array_session).Methods("POST") myRouter.HandleFunc("/containers/v1/volumes", create_volume).Methods("POST") // myRouter.HandleFunc("/csp/containers/v1/volumes/{id}") myRouter.HandleFunc("/containers/v1/volumes", get_vol_by_id).Methods("GET") myRouter.HandleFunc("/containers/v1/volumes/{id}", get_vol_by_id).Methods("GET") myRouter.HandleFunc("/containers/v1/volumes/{id}", delete_vol_by_id).Methods("DELETE") myRouter.HandleFunc("/alltokens", get_all_tokens) // fmt.Println("Received response is %v", string(tokenStringValue)) err := http.ListenAndServe(":10000", myRouter) fmt.Println("Hey there i started REST service") if err != nil { log.Fatal("Listen and Serve ERROR", err) } }
d98c2ad224fdf9960736739cd601f90c101d08bc
[ "Markdown", "Go", "Go Module", "Dockerfile", "Shell" ]
11
Shell
ansarars/csp_3par_primera
c6905705d9b5e4cecb4fe209767a25338b91bcb4
a2082c90a6bd09a09b146ce194a3cf5938a75549
refs/heads/master
<repo_name>giulianogimenez/mazebank<file_sep>/README.md # Maze Bank Example using Cucumber (4.0.0) and BDD concepts with Java 8 and Gradle builder. # Automatized tests with Gradle Use de follow command if you are facing issues with Gradle tests: $ gradle cleanTest build <file_sep>/src/test/java/br/gov/sp/fatec/mazebank/tests/DepositarFeature.java package br.gov.sp.fatec.mazebank.tests; import static org.junit.jupiter.api.Assertions.assertEquals; import br.gov.sp.fatec.mazebank.Conta; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; public class DepositarFeature { Conta conta; @Given("que eu tenho a conta de {string} do cpf {string}") public void que_eu_tenho_a_conta_de_do_cpf(String nome, String cpf) { conta = new Conta(nome, cpf); } @When("eu efetuar um deposito de {double}") public void eu_efetuar_um_deposito_de(Double deposito) { conta.depositar(deposito); } @When("efetuar outro deposito de {double}") public void efetuar_outro_deposito_de(Double deposito) { conta.depositar(deposito); } @Then("o saldo deposito dever ser de {double}") public void o_saldo_deposito_dever_ser_de(Double saldo) { assertEquals(saldo, conta.getSaldo()); } } <file_sep>/src/test/java/br/gov/sp/fatec/mazebank/tests/ContaRunner.java package br.gov.sp.fatec.mazebank.tests; import org.junit.runner.RunWith; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; @RunWith(Cucumber.class) @CucumberOptions(plugin = {"pretty"}, features = "src/test/resource", glue = "br.gov.sp.fatec.mazebank.tests") public class ContaRunner { } <file_sep>/build.gradle plugins{ id 'java' id 'application' } mainClassName = 'br.gov.sp.fatec.mazebank.Program' repositories { mavenCentral() } dependencies { testCompile('io.cucumber:cucumber-java:4.0.0', 'io.cucumber:cucumber-junit:4.0.0') testCompileOnly('org.junit.jupiter:junit-jupiter-api:5.3.1') testRuntimeOnly('org.junit.jupiter:junit-jupiter-engine:5.1.0') } test { useJUnit() }<file_sep>/target/cucumber/report.js $(document).ready(function() {var formatter = new CucumberHTML.DOMFormatter($('.cucumber-report'));formatter.uri("src/test/resource/CriarConta.feature"); formatter.feature({ "name": "Criar uma nova conta", "description": "\tEsta funcionalidade tem o cenário de criar uma nova conta de um cliente da Maze Bank.\n\tSão obrigatórios o nome e o CPF do cliente.", "keyword": "Funcionalidade" }); formatter.scenario({ "name": "Criar uma conta de pessoa física.", "description": "", "keyword": "Cenario" }); formatter.step({ "name": "que eu deseje criar uma conta na Maze Bank", "keyword": "Dado " }); formatter.match({ "location": "CriarContaFeature.que_eu_deseje_criar_uma_conta_na_Maze_Bank()" }); formatter.result({ "status": "passed" }); formatter.step({ "name": "eu informar o nome \"<NAME>\" e o CPF \"12345678909\"", "keyword": "Quando " }); formatter.match({ "location": "CriarContaFeature.eu_informar_o_nome_e_o_CPF(String,String)" }); formatter.result({ "status": "passed" }); formatter.step({ "name": "deverá emitir o saldo de 0.0", "keyword": "Então " }); formatter.match({ "location": "CriarContaFeature.deverá_emitir_o_saldo_de(Double)" }); formatter.result({ "status": "passed" }); formatter.scenario({ "name": "criar uma conta de pessoa fisica sem o cpf", "description": "", "keyword": "Cenario" }); formatter.step({ "name": "eu informar o nome \"<NAME>\" e o CPF vazio", "keyword": "Quando " }); formatter.match({ "location": "CriarContaFeature.eu_informar_o_nome_e_o_CPF_vazio(String)" }); formatter.result({ "status": "passed" }); formatter.step({ "name": "deverá vir com saldo nulo", "keyword": "Então " }); formatter.match({ "location": "CriarContaFeature.deverá_vir_com_saldo_nulo()" }); formatter.result({ "status": "passed" }); formatter.uri("src/test/resource/Depositar.feature"); formatter.feature({ "name": "depositar um valor em uma conta", "description": "\tEsta funcionalidade tem por fim efetuar testes de depósito bancário de uma conta", "keyword": "Funcionalidade" }); formatter.scenario({ "name": "depositando um valor qualquer", "description": "", "keyword": "Cenario" }); formatter.step({ "name": "que eu tenho a conta de \"<NAME>\" do cpf \"12345678909\"", "keyword": "Dado " }); formatter.match({ "location": "DepositarFeature.que_eu_tenho_a_conta_de_do_cpf(String,String)" }); formatter.result({ "status": "passed" }); formatter.step({ "name": "eu efetuar um depósito de 1000.0", "keyword": "Quando " }); formatter.match({ "location": "DepositarFeature.eu_efetuar_um_depósito_de(Double)" }); formatter.result({ "status": "passed" }); formatter.step({ "name": "efetuar outro depósito de 250.0", "keyword": "E " }); formatter.match({ "location": "DepositarFeature.efetuar_outro_depósito_de(Double)" }); formatter.result({ "status": "passed" }); formatter.step({ "name": "o saldo deverá ser de 1250.0", "keyword": "Então " }); formatter.match({ "location": "DepositarFeature.o_saldo_deverá_ser_de(Double)" }); formatter.result({ "status": "passed" }); });<file_sep>/src/test/java/br/gov/sp/fatec/mazebank/tests/CriarContaFeature.java package br.gov.sp.fatec.mazebank.tests; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import br.gov.sp.fatec.mazebank.Conta; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; public class CriarContaFeature { Conta conta; @Given("que eu deseje criar uma conta na Maze Bank") public void que_eu_deseje_criar_uma_conta_na_Maze_Bank() { } @When("eu informar o nome {string} e o CPF {string}") public void eu_informar_o_nome_e_o_CPF(String nome, String cpf) { conta = new Conta(nome, cpf); } @Then("deve vir o saldo de {double}") public void deve_vir_o_saldo_de(Double saldo) { assertEquals(saldo, conta.getSaldo()); } @When("eu informar o nome {string} e o CPF vazio") public void eu_informar_o_nome_e_o_CPF_vazio(String nome) { conta = new Conta(nome, ""); } @Then("deve vir o saldo nulo") public void deve_vir_o_saldo_nulo() { assertNull(conta.getSaldo()); } } <file_sep>/src/main/java/br/gov/sp/fatec/mazebank/Conta.java package br.gov.sp.fatec.mazebank; /** * @author giuliano * */ public class Conta { private String nome, cpf; private Double saldo; public Conta(String nome, String cpf) { this.nome = nome; this.cpf = cpf; if(validarCPF(cpf)) { this.saldo = 0d; } } private boolean validarCPF(String cpf) { return !cpf.trim().equals(""); } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getCpf() { return cpf; } public void setCpf(String cpf) { this.cpf = cpf; } public Double getSaldo() { return saldo; } public void depositar(Double deposito) { this.saldo = this.saldo + deposito; } }
905f3c4496f73dd726a76f8c0adc05674b12fcbb
[ "Markdown", "Java", "JavaScript", "Gradle" ]
7
Markdown
giulianogimenez/mazebank
973f2afc6eb365396f8d3614e021a994e0194da9
593af8bb74b58780d1dd061540eaf5128afdaf9d
refs/heads/master
<repo_name>SecureCloud-biz/keygen<file_sep>/example/python2-flask/keygen.py from __future__ import with_statement from contextlib import closing import sqlite3 from flask import Flask, request, session, g, redirect, url_for, abort, \ render_template, flash from pprint import pprint import OpenSSL import re # configuration DATABASE = "database.db" DEBUG = True SERVER_CERTIFICATE = "keygen.crt" SERVER_KEY = "keygen.key" app = Flask(__name__) app.config.from_object(__name__) def connect_db(): return sqlite3.connect(app.config['DATABASE']) def init_db(): with closing(connect_db()) as db: with app.open_resource('schema.sql') as f: db.cursor().executescript(f.read()) db.commit() def init_server_certificate(): # Create key pair k = OpenSSL.crypto.PKey() k.generate_key(OpenSSL.crypto.TYPE_RSA, 2048) # Create a Self-Signed Certificate c = OpenSSL.crypto.X509() s = c.get_subject() s.O = 'keygen test' s.CN = 'localhost' c.set_serial_number(1000) c.gmtime_adj_notBefore(0) c.gmtime_adj_notAfter(10*365*24*60*60) c.set_issuer(c.get_subject()) c.set_pubkey(k) c.sign(k, 'sha1') with open(app.config['SERVER_CERTIFICATE'], "w") as cf: cf.write(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, c)) with open(app.config['SERVER_KEY'], "w") as cf: cf.write(OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, k)) @app.before_request def before_request(): g.db = connect_db() with open(app.config['SERVER_KEY'], "r") as cf: g.key = OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_PEM, cf.read()) with open(app.config['SERVER_CERTIFICATE'], "r") as cf: g.cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cf.read()) @app.teardown_request def teardown_request(exception): g.db.close() @app.route('/sign-certificate', methods=['POST']) def sign_certificate(): pprint('Generating certificate for {}'.format(request.form['username'])) rawpubkey = re.sub(r'[\r\n]+', '', request.form['public_key']) pubkey = OpenSSL.crypto.NetscapeSPKI(rawpubkey).get_pubkey() x509 = OpenSSL.crypto.X509() x509.set_issuer(g.cert.get_subject()) x509.set_version(3) x509.set_pubkey(pubkey) x509.set_serial_number(1000) x509.get_subject().CN = request.form['username'] x509.gmtime_adj_notBefore(0) x509.gmtime_adj_notAfter(365*24 * 60 * 60) x509.sign(g.key, 'sha1') r = OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_ASN1, x509) return (r, 200, {'Content-Type': 'application/x-x509-user-cert'}) @app.route('/secure', methods=['GET']) def secure(): return render_template('secure.html', DN=request.environ['DN'], VERIFIED=request.environ['VERIFIED']) if __name__ == "__main__": app.run() <file_sep>/example/python2-flask/schema.sql DROP TABLE IF EXISTS users; CREATE TABLE users ( public_key string PRIMARY KEY, username string ); <file_sep>/example/python2-flask/Makefile bootstrap.py: create_bootstrap.py ./create_bootstrap.py chmod u+x bootstrap.py database.db: init_db.py keygen.py python2 init_db.py venv: bootstrap.py ./bootstrap.py -p python2 venv chmod u+x venv/bin/activate .PHONY: clean run clean: - rm -rf venv bootstrap.py run: keygen.py python keygen.py uwsgi: venv/bin/uwsgi -H venv -w keygen:app -s uwsgi.sock -M # vim: tabstop=8 noexpandtab <file_sep>/README.md # Keygen **URL: keygen.alexchamberlain.co.uk** This is an experiment to see whether client side certificates can actually be used with normal people, who don't really understand what HTTP or SSL are. ## Contributing Please contribute! Raise issues or fork and we'll chat! I'd love if someone reputable would write an idiots guide to client-side certificates and the risks involved. ## Examples I've written one example server, which signs the client-certificates. If you don't like Python, please contribute another example server so others can see how to sign certificates in other languages. ### python2-flask The one and only example server is written in Python and uses Flask - the lightweight web framework; Flask requires Python 2, rather than Python 3. Instructions on running the server locally will follow. ## License The stuff I've written is licensed under the MIT license, as written in LICENSE. I have reimplemented the [GitHub Ribbons][1], which uses the font *Collegiate*. The font is from [k-type.com][2]. [1]: https://github.com/blog/273-github-ribbons [2]: http://www.k-type.com/?p=435 <file_sep>/nginx/bootstrap.sh #!/bin/bash if [ ! -f server.crt ]; then openssl genrsa -des3 -out server.key.bak 2048 openssl req -new -key server.key.bak -out server.csr openssl rsa -in server.key.bak -out server.key openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt fi rm -rf nginx-1.2.3 if [ ! -f nginx-1.2.3.tar.gz ]; then wget http://nginx.org/download/nginx-1.2.3.tar.gz fi tar -xzf nginx-1.2.3.tar.gz pwdir="$(pwd)" cd nginx-1.2.3 ./configure --prefix="$pwdir" --sbin-path=nginx --conf-path=nginx.conf \ --with-http_ssl_module make make install <file_sep>/example/python2-flask/init.py from keygen import init_db, init_server_certificate if __name__ == "__main__": init_db() init_server_certificate() <file_sep>/example/python2-flask/create_bootstrap.py #!/usr/bin/python2 from __future__ import with_statement import virtualenv, textwrap output = virtualenv.create_bootstrap_script(textwrap.dedent(""" import os, subprocess def after_install(options, home_dir): pip = os.path.join(home_dir, 'bin', 'pip') subprocess.call([pip, 'install', 'flask']) subprocess.call([pip, 'install', 'pyopenssl']) subprocess.call([pip, 'install', 'uwsgi']) """)) with open('bootstrap.py', 'w') as f: f.write(output)
4db418189c469fc2f69046c6af4c5d5b07a3a09e
[ "SQL", "Markdown", "Makefile", "Python", "Shell" ]
7
Python
SecureCloud-biz/keygen
47687cd040052fe53d2b5bbcfad12ac547f55b81
e64dda5d13bc25ad66fd4b1dc1df6f862bfb5224
refs/heads/master
<file_sep># CMAKE generated file: DO NOT EDIT! # Generated by "Unix Makefiles" Generator, CMake Version 3.16 # Default target executed when no arguments are given to make. default_target: all .PHONY : default_target # Allow only one "make -f Makefile2" at a time, but pass parallelism. .NOTPARALLEL: #============================================================================= # Special targets provided by cmake. # Disable implicit rules so canonical targets will work. .SUFFIXES: # Remove some rules from gmake that .SUFFIXES does not remove. SUFFIXES = .SUFFIXES: .hpux_make_needs_suffix_list # Suppress display of executed commands. $(VERBOSE).SILENT: # A target that is always out of date. cmake_force: .PHONY : cmake_force #============================================================================= # Set environment variables for the build. # The shell in which to execute make rules. SHELL = /bin/sh # The CMake executable. CMAKE_COMMAND = /usr/local/bin/cmake # The command to remove a file. RM = /usr/local/bin/cmake -E remove -f # Escaping for special characters. EQUALS = = # The top-level source directory on which CMake was run. CMAKE_SOURCE_DIR = /home/zhangjoe/Desktop/GraduateWork/hot # The top-level build directory on which CMake was run. CMAKE_BINARY_DIR = /home/zhangjoe/Desktop/GraduateWork/hot #============================================================================= # Targets provided globally by CMake. # Special rule for the target rebuild_cache rebuild_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..." /usr/local/bin/cmake -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) .PHONY : rebuild_cache # Special rule for the target rebuild_cache rebuild_cache/fast: rebuild_cache .PHONY : rebuild_cache/fast # Special rule for the target edit_cache edit_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "No interactive CMake dialog available..." /usr/local/bin/cmake -E echo No\ interactive\ CMake\ dialog\ available. .PHONY : edit_cache # Special rule for the target edit_cache edit_cache/fast: edit_cache .PHONY : edit_cache/fast # Special rule for the target test test: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running tests..." /usr/local/bin/ctest --force-new-ctest-process $(ARGS) .PHONY : test # Special rule for the target test test/fast: test .PHONY : test/fast # The main all target all: cmake_check_build_system cd /home/zhangjoe/Desktop/GraduateWork/hot && $(CMAKE_COMMAND) -E cmake_progress_start /home/zhangjoe/Desktop/GraduateWork/hot/CMakeFiles /home/zhangjoe/Desktop/GraduateWork/hot/tests/hot/commons-test/CMakeFiles/progress.marks cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f CMakeFiles/Makefile2 tests/hot/commons-test/all $(CMAKE_COMMAND) -E cmake_progress_start /home/zhangjoe/Desktop/GraduateWork/hot/CMakeFiles 0 .PHONY : all # The main clean target clean: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f CMakeFiles/Makefile2 tests/hot/commons-test/clean .PHONY : clean # The main clean target clean/fast: clean .PHONY : clean/fast # Prepare targets for installation. preinstall: all cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f CMakeFiles/Makefile2 tests/hot/commons-test/preinstall .PHONY : preinstall # Prepare targets for installation. preinstall/fast: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f CMakeFiles/Makefile2 tests/hot/commons-test/preinstall .PHONY : preinstall/fast # clear depends depend: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1 .PHONY : depend # Convenience name for target. tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/rule: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f CMakeFiles/Makefile2 tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/rule .PHONY : tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/rule # Convenience name for target. hot-commons-test: tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/rule .PHONY : hot-commons-test # fast build rule for target. hot-commons-test/fast: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/build.make tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/build .PHONY : hot-commons-test/fast src/hot/commons/AlgorithmsTest.o: src/hot/commons/AlgorithmsTest.cpp.o .PHONY : src/hot/commons/AlgorithmsTest.o # target to build an object file src/hot/commons/AlgorithmsTest.cpp.o: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/build.make tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/src/hot/commons/AlgorithmsTest.cpp.o .PHONY : src/hot/commons/AlgorithmsTest.cpp.o src/hot/commons/AlgorithmsTest.i: src/hot/commons/AlgorithmsTest.cpp.i .PHONY : src/hot/commons/AlgorithmsTest.i # target to preprocess a source file src/hot/commons/AlgorithmsTest.cpp.i: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/build.make tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/src/hot/commons/AlgorithmsTest.cpp.i .PHONY : src/hot/commons/AlgorithmsTest.cpp.i src/hot/commons/AlgorithmsTest.s: src/hot/commons/AlgorithmsTest.cpp.s .PHONY : src/hot/commons/AlgorithmsTest.s # target to generate assembly for a file src/hot/commons/AlgorithmsTest.cpp.s: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/build.make tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/src/hot/commons/AlgorithmsTest.cpp.s .PHONY : src/hot/commons/AlgorithmsTest.cpp.s src/hot/commons/DiscriminativeBitTest.o: src/hot/commons/DiscriminativeBitTest.cpp.o .PHONY : src/hot/commons/DiscriminativeBitTest.o # target to build an object file src/hot/commons/DiscriminativeBitTest.cpp.o: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/build.make tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/src/hot/commons/DiscriminativeBitTest.cpp.o .PHONY : src/hot/commons/DiscriminativeBitTest.cpp.o src/hot/commons/DiscriminativeBitTest.i: src/hot/commons/DiscriminativeBitTest.cpp.i .PHONY : src/hot/commons/DiscriminativeBitTest.i # target to preprocess a source file src/hot/commons/DiscriminativeBitTest.cpp.i: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/build.make tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/src/hot/commons/DiscriminativeBitTest.cpp.i .PHONY : src/hot/commons/DiscriminativeBitTest.cpp.i src/hot/commons/DiscriminativeBitTest.s: src/hot/commons/DiscriminativeBitTest.cpp.s .PHONY : src/hot/commons/DiscriminativeBitTest.s # target to generate assembly for a file src/hot/commons/DiscriminativeBitTest.cpp.s: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/build.make tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/src/hot/commons/DiscriminativeBitTest.cpp.s .PHONY : src/hot/commons/DiscriminativeBitTest.cpp.s src/hot/commons/MultiMaskPartialKeyMappingTest.o: src/hot/commons/MultiMaskPartialKeyMappingTest.cpp.o .PHONY : src/hot/commons/MultiMaskPartialKeyMappingTest.o # target to build an object file src/hot/commons/MultiMaskPartialKeyMappingTest.cpp.o: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/build.make tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/src/hot/commons/MultiMaskPartialKeyMappingTest.cpp.o .PHONY : src/hot/commons/MultiMaskPartialKeyMappingTest.cpp.o src/hot/commons/MultiMaskPartialKeyMappingTest.i: src/hot/commons/MultiMaskPartialKeyMappingTest.cpp.i .PHONY : src/hot/commons/MultiMaskPartialKeyMappingTest.i # target to preprocess a source file src/hot/commons/MultiMaskPartialKeyMappingTest.cpp.i: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/build.make tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/src/hot/commons/MultiMaskPartialKeyMappingTest.cpp.i .PHONY : src/hot/commons/MultiMaskPartialKeyMappingTest.cpp.i src/hot/commons/MultiMaskPartialKeyMappingTest.s: src/hot/commons/MultiMaskPartialKeyMappingTest.cpp.s .PHONY : src/hot/commons/MultiMaskPartialKeyMappingTest.s # target to generate assembly for a file src/hot/commons/MultiMaskPartialKeyMappingTest.cpp.s: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/build.make tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/src/hot/commons/MultiMaskPartialKeyMappingTest.cpp.s .PHONY : src/hot/commons/MultiMaskPartialKeyMappingTest.cpp.s src/hot/commons/SIMDHelperTest.o: src/hot/commons/SIMDHelperTest.cpp.o .PHONY : src/hot/commons/SIMDHelperTest.o # target to build an object file src/hot/commons/SIMDHelperTest.cpp.o: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/build.make tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/src/hot/commons/SIMDHelperTest.cpp.o .PHONY : src/hot/commons/SIMDHelperTest.cpp.o src/hot/commons/SIMDHelperTest.i: src/hot/commons/SIMDHelperTest.cpp.i .PHONY : src/hot/commons/SIMDHelperTest.i # target to preprocess a source file src/hot/commons/SIMDHelperTest.cpp.i: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/build.make tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/src/hot/commons/SIMDHelperTest.cpp.i .PHONY : src/hot/commons/SIMDHelperTest.cpp.i src/hot/commons/SIMDHelperTest.s: src/hot/commons/SIMDHelperTest.cpp.s .PHONY : src/hot/commons/SIMDHelperTest.s # target to generate assembly for a file src/hot/commons/SIMDHelperTest.cpp.s: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/build.make tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/src/hot/commons/SIMDHelperTest.cpp.s .PHONY : src/hot/commons/SIMDHelperTest.cpp.s src/hot/commons/SingleMaskPartialKeyMappingTest.o: src/hot/commons/SingleMaskPartialKeyMappingTest.cpp.o .PHONY : src/hot/commons/SingleMaskPartialKeyMappingTest.o # target to build an object file src/hot/commons/SingleMaskPartialKeyMappingTest.cpp.o: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/build.make tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/src/hot/commons/SingleMaskPartialKeyMappingTest.cpp.o .PHONY : src/hot/commons/SingleMaskPartialKeyMappingTest.cpp.o src/hot/commons/SingleMaskPartialKeyMappingTest.i: src/hot/commons/SingleMaskPartialKeyMappingTest.cpp.i .PHONY : src/hot/commons/SingleMaskPartialKeyMappingTest.i # target to preprocess a source file src/hot/commons/SingleMaskPartialKeyMappingTest.cpp.i: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/build.make tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/src/hot/commons/SingleMaskPartialKeyMappingTest.cpp.i .PHONY : src/hot/commons/SingleMaskPartialKeyMappingTest.cpp.i src/hot/commons/SingleMaskPartialKeyMappingTest.s: src/hot/commons/SingleMaskPartialKeyMappingTest.cpp.s .PHONY : src/hot/commons/SingleMaskPartialKeyMappingTest.s # target to generate assembly for a file src/hot/commons/SingleMaskPartialKeyMappingTest.cpp.s: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/build.make tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/src/hot/commons/SingleMaskPartialKeyMappingTest.cpp.s .PHONY : src/hot/commons/SingleMaskPartialKeyMappingTest.cpp.s src/hot/commons/SparsePartialKeysTest.o: src/hot/commons/SparsePartialKeysTest.cpp.o .PHONY : src/hot/commons/SparsePartialKeysTest.o # target to build an object file src/hot/commons/SparsePartialKeysTest.cpp.o: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/build.make tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/src/hot/commons/SparsePartialKeysTest.cpp.o .PHONY : src/hot/commons/SparsePartialKeysTest.cpp.o src/hot/commons/SparsePartialKeysTest.i: src/hot/commons/SparsePartialKeysTest.cpp.i .PHONY : src/hot/commons/SparsePartialKeysTest.i # target to preprocess a source file src/hot/commons/SparsePartialKeysTest.cpp.i: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/build.make tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/src/hot/commons/SparsePartialKeysTest.cpp.i .PHONY : src/hot/commons/SparsePartialKeysTest.cpp.i src/hot/commons/SparsePartialKeysTest.s: src/hot/commons/SparsePartialKeysTest.cpp.s .PHONY : src/hot/commons/SparsePartialKeysTest.s # target to generate assembly for a file src/hot/commons/SparsePartialKeysTest.cpp.s: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/build.make tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/src/hot/commons/SparsePartialKeysTest.cpp.s .PHONY : src/hot/commons/SparsePartialKeysTest.cpp.s src/hot/commons/TestModule.o: src/hot/commons/TestModule.cpp.o .PHONY : src/hot/commons/TestModule.o # target to build an object file src/hot/commons/TestModule.cpp.o: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/build.make tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/src/hot/commons/TestModule.cpp.o .PHONY : src/hot/commons/TestModule.cpp.o src/hot/commons/TestModule.i: src/hot/commons/TestModule.cpp.i .PHONY : src/hot/commons/TestModule.i # target to preprocess a source file src/hot/commons/TestModule.cpp.i: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/build.make tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/src/hot/commons/TestModule.cpp.i .PHONY : src/hot/commons/TestModule.cpp.i src/hot/commons/TestModule.s: src/hot/commons/TestModule.cpp.s .PHONY : src/hot/commons/TestModule.s # target to generate assembly for a file src/hot/commons/TestModule.cpp.s: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/build.make tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/src/hot/commons/TestModule.cpp.s .PHONY : src/hot/commons/TestModule.cpp.s # Help Target help: @echo "The following are some of the valid targets for this Makefile:" @echo "... all (the default if no target is provided)" @echo "... clean" @echo "... depend" @echo "... rebuild_cache" @echo "... edit_cache" @echo "... hot-commons-test" @echo "... test" @echo "... src/hot/commons/AlgorithmsTest.o" @echo "... src/hot/commons/AlgorithmsTest.i" @echo "... src/hot/commons/AlgorithmsTest.s" @echo "... src/hot/commons/DiscriminativeBitTest.o" @echo "... src/hot/commons/DiscriminativeBitTest.i" @echo "... src/hot/commons/DiscriminativeBitTest.s" @echo "... src/hot/commons/MultiMaskPartialKeyMappingTest.o" @echo "... src/hot/commons/MultiMaskPartialKeyMappingTest.i" @echo "... src/hot/commons/MultiMaskPartialKeyMappingTest.s" @echo "... src/hot/commons/SIMDHelperTest.o" @echo "... src/hot/commons/SIMDHelperTest.i" @echo "... src/hot/commons/SIMDHelperTest.s" @echo "... src/hot/commons/SingleMaskPartialKeyMappingTest.o" @echo "... src/hot/commons/SingleMaskPartialKeyMappingTest.i" @echo "... src/hot/commons/SingleMaskPartialKeyMappingTest.s" @echo "... src/hot/commons/SparsePartialKeysTest.o" @echo "... src/hot/commons/SparsePartialKeysTest.i" @echo "... src/hot/commons/SparsePartialKeysTest.s" @echo "... src/hot/commons/TestModule.o" @echo "... src/hot/commons/TestModule.i" @echo "... src/hot/commons/TestModule.s" .PHONY : help #============================================================================= # Special targets to cleanup operation of make. # Special rule to run CMake to check the build system integrity. # No rule that depends on this can have commands that come from listfiles # because they might be regenerated. cmake_check_build_system: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0 .PHONY : cmake_check_build_system <file_sep>file(REMOVE_RECURSE "CMakeFiles/hot-test-helpers-lib.dir/src/hot/testhelpers/PartialKeyMappingTestHelper.cpp.o" "CMakeFiles/hot-test-helpers-lib.dir/src/hot/testhelpers/SampleTriples.cpp.o" "libhot-test-helpers-lib.a" "libhot-test-helpers-lib.pdb" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/hot-test-helpers-lib.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep>file(REMOVE_RECURSE "CMakeFiles/hot-single-threaded-test.dir/src/hot/singlethreaded/HOTSingleThreadedTest.cpp.o" "CMakeFiles/hot-single-threaded-test.dir/src/hot/singlethreaded/TestModule.cpp.o" "hot-single-threaded-test" "hot-single-threaded-test.pdb" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/hot-single-threaded-test.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep># The set of languages for which implicit dependencies are needed: set(CMAKE_DEPENDS_LANGUAGES "CXX" ) # The set of files for implicit dependencies of each language: set(CMAKE_DEPENDS_CHECK_CXX "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/map-helpers-test/src/idx/maphelpers/MapValueExtractorTest.cpp" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/map-helpers-test/CMakeFiles/map-helpers-test.dir/src/idx/maphelpers/MapValueExtractorTest.cpp.o" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/map-helpers-test/src/idx/maphelpers/STLLikeIndexTest.cpp" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/map-helpers-test/CMakeFiles/map-helpers-test.dir/src/idx/maphelpers/STLLikeIndexTest.cpp.o" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/map-helpers-test/src/idx/maphelpers/TestModule.cpp" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/map-helpers-test/CMakeFiles/map-helpers-test.dir/src/idx/maphelpers/TestModule.cpp.o" ) set(CMAKE_CXX_COMPILER_ID "GNU") # Preprocessor definitions for this target. set(CMAKE_TARGET_DEFINITIONS_CXX "BOOST_ALL_NO_LIB=1" "BOOST_SYSTEM_NO_DEPRECATED" "BOOST_THREAD_PROVIDES_EXECUTORS" "BOOST_THREAD_USES_CHRONO" "BOOST_THREAD_VERSION=4" ) # The include file search paths: set(CMAKE_CXX_TARGET_INCLUDE_PATH "tests/idx/map-helpers-test/include" "libs/idx/map-helpers/include" "libs/idx/content-helpers/include" "_deps/boost-src" ) # Targets to which this target links. set(CMAKE_TARGET_LINKED_INFO_FILES "/home/zhangjoe/Desktop/GraduateWork/hot/third-party/boost-cmake/CMakeFiles/Boost_unit_test_framework.dir/DependInfo.cmake" "/home/zhangjoe/Desktop/GraduateWork/hot/third-party/boost-cmake/CMakeFiles/Boost_timer.dir/DependInfo.cmake" "/home/zhangjoe/Desktop/GraduateWork/hot/third-party/boost-cmake/CMakeFiles/Boost_chrono.dir/DependInfo.cmake" ) # Fortran module output directory. set(CMAKE_Fortran_TARGET_MODULE_DIR "") <file_sep>file(REMOVE_RECURSE "CMakeFiles/hot-commons-test.dir/src/hot/commons/AlgorithmsTest.cpp.o" "CMakeFiles/hot-commons-test.dir/src/hot/commons/DiscriminativeBitTest.cpp.o" "CMakeFiles/hot-commons-test.dir/src/hot/commons/MultiMaskPartialKeyMappingTest.cpp.o" "CMakeFiles/hot-commons-test.dir/src/hot/commons/SIMDHelperTest.cpp.o" "CMakeFiles/hot-commons-test.dir/src/hot/commons/SingleMaskPartialKeyMappingTest.cpp.o" "CMakeFiles/hot-commons-test.dir/src/hot/commons/SparsePartialKeysTest.cpp.o" "CMakeFiles/hot-commons-test.dir/src/hot/commons/TestModule.cpp.o" "hot-commons-test" "hot-commons-test.pdb" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/hot-commons-test.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep># The set of languages for which implicit dependencies are needed: set(CMAKE_DEPENDS_LANGUAGES "CXX" ) # The set of files for implicit dependencies of each language: set(CMAKE_DEPENDS_CHECK_CXX "/home/zhangjoe/Desktop/GraduateWork/hot/tests/hot/rowex-test/src/hot/rowex/HOTRowexNodeTest.cpp" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/hot/rowex-test/CMakeFiles/hot-rowex-test.dir/src/hot/rowex/HOTRowexNodeTest.cpp.o" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/hot/rowex-test/src/hot/rowex/HOTRowexTest.cpp" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/hot/rowex-test/CMakeFiles/hot-rowex-test.dir/src/hot/rowex/HOTRowexTest.cpp.o" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/hot/rowex-test/src/hot/rowex/StringTestData.cpp" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/hot/rowex-test/CMakeFiles/hot-rowex-test.dir/src/hot/rowex/StringTestData.cpp.o" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/hot/rowex-test/src/hot/rowex/TestModule.cpp" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/hot/rowex-test/CMakeFiles/hot-rowex-test.dir/src/hot/rowex/TestModule.cpp.o" ) set(CMAKE_CXX_COMPILER_ID "GNU") # Preprocessor definitions for this target. set(CMAKE_TARGET_DEFINITIONS_CXX "BOOST_ALL_NO_LIB=1" "BOOST_SYSTEM_NO_DEPRECATED" "BOOST_THREAD_PROVIDES_EXECUTORS" "BOOST_THREAD_USES_CHRONO" "BOOST_THREAD_VERSION=4" ) # The include file search paths: set(CMAKE_CXX_TARGET_INCLUDE_PATH "tests/hot/rowex-test/include" "libs/idx/content-helpers/include" "libs/idx/utils/include" "libs/idx/utils" "libs/hot/single-threaded/include" "libs/hot/commons/include" "libs/hot/rowex/include" "tests/hot/test-helpers/include" "_deps/boost-src" "third-party/tbb/include" ) # Targets to which this target links. set(CMAKE_TARGET_LINKED_INFO_FILES "/home/zhangjoe/Desktop/GraduateWork/hot/third-party/boost-cmake/CMakeFiles/Boost_unit_test_framework.dir/DependInfo.cmake" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/hot/test-helpers/CMakeFiles/hot-test-helpers-lib.dir/DependInfo.cmake" "/home/zhangjoe/Desktop/GraduateWork/hot/third-party/boost-cmake/CMakeFiles/Boost_timer.dir/DependInfo.cmake" "/home/zhangjoe/Desktop/GraduateWork/hot/third-party/boost-cmake/CMakeFiles/Boost_chrono.dir/DependInfo.cmake" ) # Fortran module output directory. set(CMAKE_Fortran_TARGET_MODULE_DIR "") <file_sep># CMake generated Testfile for # Source directory: /home/zhangjoe/Desktop/GraduateWork/hot/tests/hot # Build directory: /home/zhangjoe/Desktop/GraduateWork/hot/tests/hot # # This file includes the relevant testing commands required for # testing this directory and lists subdirectories to be tested as well. subdirs("commons-test") subdirs("rowex-test") subdirs("single-threaded-test") subdirs("test-helpers") <file_sep>file(REMOVE_RECURSE "CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventExecutorTest.cpp.o" "CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventListBackingBufferSizeEstimatorTest.cpp.o" "CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventListTest.cpp.o" "CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventReaderExceptionTest.cpp.o" "CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventReaderTest.cpp.o" "CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventTest.cpp.o" "CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventTypeIdTest.cpp.o" "CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventTypeIdToEventTypeMappingTest.cpp.o" "CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkLineReaderTest.cpp.o" "CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/ContentReaderTest.cpp.o" "CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/ContinuosBufferTest.cpp.o" "CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/TempFile.cpp.o" "CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/TestModule.cpp.o" "benchmark-helpers-test" "benchmark-helpers-test.pdb" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/benchmark-helpers-test.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep># CMake generated Testfile for # Source directory: /home/zhangjoe/Desktop/GraduateWork/hot/tests/idx # Build directory: /home/zhangjoe/Desktop/GraduateWork/hot/tests/idx # # This file includes the relevant testing commands required for # testing this directory and lists subdirectories to be tested as well. subdirs("benchmark-helpers-test") subdirs("content-helpers-test") subdirs("map-helpers-test") <file_sep># The set of languages for which implicit dependencies are needed: set(CMAKE_DEPENDS_LANGUAGES "CXX" ) # The set of files for implicit dependencies of each language: set(CMAKE_DEPENDS_CHECK_CXX "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/content-helpers-test/src/idx/contenthelpers/CStringComparatorTest.cpp" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/CStringComparatorTest.cpp.o" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/content-helpers-test/src/idx/contenthelpers/ContentEqualsTest.cpp" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/ContentEqualsTest.cpp.o" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/content-helpers-test/src/idx/contenthelpers/IdentityKeyExtractorTest.cpp" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/IdentityKeyExtractorTest.cpp.o" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/content-helpers-test/src/idx/contenthelpers/KeyComparatorTest.cpp" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/KeyComparatorTest.cpp.o" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/content-helpers-test/src/idx/contenthelpers/OptionalValueTest.cpp" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/OptionalValueTest.cpp.o" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/content-helpers-test/src/idx/contenthelpers/PairKeyExtractorTest.cpp" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/PairKeyExtractorTest.cpp.o" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/content-helpers-test/src/idx/contenthelpers/PairPointerKeyExtractorTest.cpp" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/PairPointerKeyExtractorTest.cpp.o" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/content-helpers-test/src/idx/contenthelpers/TestModule.cpp" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/TestModule.cpp.o" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/content-helpers-test/src/idx/contenthelpers/ValueToKeyTypeMapperTest.cpp" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/ValueToKeyTypeMapperTest.cpp.o" ) set(CMAKE_CXX_COMPILER_ID "GNU") # Preprocessor definitions for this target. set(CMAKE_TARGET_DEFINITIONS_CXX "BOOST_ALL_NO_LIB=1" "BOOST_SYSTEM_NO_DEPRECATED" "BOOST_THREAD_PROVIDES_EXECUTORS" "BOOST_THREAD_USES_CHRONO" "BOOST_THREAD_VERSION=4" ) # The include file search paths: set(CMAKE_CXX_TARGET_INCLUDE_PATH "tests/idx/content-helpers-test/include" "libs/idx/content-helpers/include" "_deps/boost-src" ) # Targets to which this target links. set(CMAKE_TARGET_LINKED_INFO_FILES "/home/zhangjoe/Desktop/GraduateWork/hot/third-party/boost-cmake/CMakeFiles/Boost_unit_test_framework.dir/DependInfo.cmake" "/home/zhangjoe/Desktop/GraduateWork/hot/third-party/boost-cmake/CMakeFiles/Boost_timer.dir/DependInfo.cmake" "/home/zhangjoe/Desktop/GraduateWork/hot/third-party/boost-cmake/CMakeFiles/Boost_chrono.dir/DependInfo.cmake" ) # Fortran module output directory. set(CMAKE_Fortran_TARGET_MODULE_DIR "") <file_sep># CMAKE generated file: DO NOT EDIT! # Generated by "Unix Makefiles" Generator, CMake Version 3.16 # Default target executed when no arguments are given to make. default_target: all .PHONY : default_target # Allow only one "make -f Makefile2" at a time, but pass parallelism. .NOTPARALLEL: #============================================================================= # Special targets provided by cmake. # Disable implicit rules so canonical targets will work. .SUFFIXES: # Remove some rules from gmake that .SUFFIXES does not remove. SUFFIXES = .SUFFIXES: .hpux_make_needs_suffix_list # Suppress display of executed commands. $(VERBOSE).SILENT: # A target that is always out of date. cmake_force: .PHONY : cmake_force #============================================================================= # Set environment variables for the build. # The shell in which to execute make rules. SHELL = /bin/sh # The CMake executable. CMAKE_COMMAND = /usr/local/bin/cmake # The command to remove a file. RM = /usr/local/bin/cmake -E remove -f # Escaping for special characters. EQUALS = = # The top-level source directory on which CMake was run. CMAKE_SOURCE_DIR = /home/zhangjoe/Desktop/GraduateWork/hot # The top-level build directory on which CMake was run. CMAKE_BINARY_DIR = /home/zhangjoe/Desktop/GraduateWork/hot #============================================================================= # Targets provided globally by CMake. # Special rule for the target edit_cache edit_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "No interactive CMake dialog available..." /usr/local/bin/cmake -E echo No\ interactive\ CMake\ dialog\ available. .PHONY : edit_cache # Special rule for the target edit_cache edit_cache/fast: edit_cache .PHONY : edit_cache/fast # Special rule for the target rebuild_cache rebuild_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..." /usr/local/bin/cmake -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) .PHONY : rebuild_cache # Special rule for the target rebuild_cache rebuild_cache/fast: rebuild_cache .PHONY : rebuild_cache/fast # Special rule for the target test test: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running tests..." /usr/local/bin/ctest --force-new-ctest-process $(ARGS) .PHONY : test # Special rule for the target test test/fast: test .PHONY : test/fast # The main all target all: cmake_check_build_system cd /home/zhangjoe/Desktop/GraduateWork/hot && $(CMAKE_COMMAND) -E cmake_progress_start /home/zhangjoe/Desktop/GraduateWork/hot/CMakeFiles /home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/benchmark-helpers-test/CMakeFiles/progress.marks cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f CMakeFiles/Makefile2 tests/idx/benchmark-helpers-test/all $(CMAKE_COMMAND) -E cmake_progress_start /home/zhangjoe/Desktop/GraduateWork/hot/CMakeFiles 0 .PHONY : all # The main clean target clean: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f CMakeFiles/Makefile2 tests/idx/benchmark-helpers-test/clean .PHONY : clean # The main clean target clean/fast: clean .PHONY : clean/fast # Prepare targets for installation. preinstall: all cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f CMakeFiles/Makefile2 tests/idx/benchmark-helpers-test/preinstall .PHONY : preinstall # Prepare targets for installation. preinstall/fast: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f CMakeFiles/Makefile2 tests/idx/benchmark-helpers-test/preinstall .PHONY : preinstall/fast # clear depends depend: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1 .PHONY : depend # Convenience name for target. tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/rule: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f CMakeFiles/Makefile2 tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/rule .PHONY : tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/rule # Convenience name for target. benchmark-helpers-test: tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/rule .PHONY : benchmark-helpers-test # fast build rule for target. benchmark-helpers-test/fast: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build .PHONY : benchmark-helpers-test/fast src/idx/benchmark/BenchmarkEventExecutorTest.o: src/idx/benchmark/BenchmarkEventExecutorTest.cpp.o .PHONY : src/idx/benchmark/BenchmarkEventExecutorTest.o # target to build an object file src/idx/benchmark/BenchmarkEventExecutorTest.cpp.o: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventExecutorTest.cpp.o .PHONY : src/idx/benchmark/BenchmarkEventExecutorTest.cpp.o src/idx/benchmark/BenchmarkEventExecutorTest.i: src/idx/benchmark/BenchmarkEventExecutorTest.cpp.i .PHONY : src/idx/benchmark/BenchmarkEventExecutorTest.i # target to preprocess a source file src/idx/benchmark/BenchmarkEventExecutorTest.cpp.i: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventExecutorTest.cpp.i .PHONY : src/idx/benchmark/BenchmarkEventExecutorTest.cpp.i src/idx/benchmark/BenchmarkEventExecutorTest.s: src/idx/benchmark/BenchmarkEventExecutorTest.cpp.s .PHONY : src/idx/benchmark/BenchmarkEventExecutorTest.s # target to generate assembly for a file src/idx/benchmark/BenchmarkEventExecutorTest.cpp.s: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventExecutorTest.cpp.s .PHONY : src/idx/benchmark/BenchmarkEventExecutorTest.cpp.s src/idx/benchmark/BenchmarkEventListBackingBufferSizeEstimatorTest.o: src/idx/benchmark/BenchmarkEventListBackingBufferSizeEstimatorTest.cpp.o .PHONY : src/idx/benchmark/BenchmarkEventListBackingBufferSizeEstimatorTest.o # target to build an object file src/idx/benchmark/BenchmarkEventListBackingBufferSizeEstimatorTest.cpp.o: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventListBackingBufferSizeEstimatorTest.cpp.o .PHONY : src/idx/benchmark/BenchmarkEventListBackingBufferSizeEstimatorTest.cpp.o src/idx/benchmark/BenchmarkEventListBackingBufferSizeEstimatorTest.i: src/idx/benchmark/BenchmarkEventListBackingBufferSizeEstimatorTest.cpp.i .PHONY : src/idx/benchmark/BenchmarkEventListBackingBufferSizeEstimatorTest.i # target to preprocess a source file src/idx/benchmark/BenchmarkEventListBackingBufferSizeEstimatorTest.cpp.i: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventListBackingBufferSizeEstimatorTest.cpp.i .PHONY : src/idx/benchmark/BenchmarkEventListBackingBufferSizeEstimatorTest.cpp.i src/idx/benchmark/BenchmarkEventListBackingBufferSizeEstimatorTest.s: src/idx/benchmark/BenchmarkEventListBackingBufferSizeEstimatorTest.cpp.s .PHONY : src/idx/benchmark/BenchmarkEventListBackingBufferSizeEstimatorTest.s # target to generate assembly for a file src/idx/benchmark/BenchmarkEventListBackingBufferSizeEstimatorTest.cpp.s: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventListBackingBufferSizeEstimatorTest.cpp.s .PHONY : src/idx/benchmark/BenchmarkEventListBackingBufferSizeEstimatorTest.cpp.s src/idx/benchmark/BenchmarkEventListTest.o: src/idx/benchmark/BenchmarkEventListTest.cpp.o .PHONY : src/idx/benchmark/BenchmarkEventListTest.o # target to build an object file src/idx/benchmark/BenchmarkEventListTest.cpp.o: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventListTest.cpp.o .PHONY : src/idx/benchmark/BenchmarkEventListTest.cpp.o src/idx/benchmark/BenchmarkEventListTest.i: src/idx/benchmark/BenchmarkEventListTest.cpp.i .PHONY : src/idx/benchmark/BenchmarkEventListTest.i # target to preprocess a source file src/idx/benchmark/BenchmarkEventListTest.cpp.i: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventListTest.cpp.i .PHONY : src/idx/benchmark/BenchmarkEventListTest.cpp.i src/idx/benchmark/BenchmarkEventListTest.s: src/idx/benchmark/BenchmarkEventListTest.cpp.s .PHONY : src/idx/benchmark/BenchmarkEventListTest.s # target to generate assembly for a file src/idx/benchmark/BenchmarkEventListTest.cpp.s: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventListTest.cpp.s .PHONY : src/idx/benchmark/BenchmarkEventListTest.cpp.s src/idx/benchmark/BenchmarkEventReaderExceptionTest.o: src/idx/benchmark/BenchmarkEventReaderExceptionTest.cpp.o .PHONY : src/idx/benchmark/BenchmarkEventReaderExceptionTest.o # target to build an object file src/idx/benchmark/BenchmarkEventReaderExceptionTest.cpp.o: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventReaderExceptionTest.cpp.o .PHONY : src/idx/benchmark/BenchmarkEventReaderExceptionTest.cpp.o src/idx/benchmark/BenchmarkEventReaderExceptionTest.i: src/idx/benchmark/BenchmarkEventReaderExceptionTest.cpp.i .PHONY : src/idx/benchmark/BenchmarkEventReaderExceptionTest.i # target to preprocess a source file src/idx/benchmark/BenchmarkEventReaderExceptionTest.cpp.i: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventReaderExceptionTest.cpp.i .PHONY : src/idx/benchmark/BenchmarkEventReaderExceptionTest.cpp.i src/idx/benchmark/BenchmarkEventReaderExceptionTest.s: src/idx/benchmark/BenchmarkEventReaderExceptionTest.cpp.s .PHONY : src/idx/benchmark/BenchmarkEventReaderExceptionTest.s # target to generate assembly for a file src/idx/benchmark/BenchmarkEventReaderExceptionTest.cpp.s: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventReaderExceptionTest.cpp.s .PHONY : src/idx/benchmark/BenchmarkEventReaderExceptionTest.cpp.s src/idx/benchmark/BenchmarkEventReaderTest.o: src/idx/benchmark/BenchmarkEventReaderTest.cpp.o .PHONY : src/idx/benchmark/BenchmarkEventReaderTest.o # target to build an object file src/idx/benchmark/BenchmarkEventReaderTest.cpp.o: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventReaderTest.cpp.o .PHONY : src/idx/benchmark/BenchmarkEventReaderTest.cpp.o src/idx/benchmark/BenchmarkEventReaderTest.i: src/idx/benchmark/BenchmarkEventReaderTest.cpp.i .PHONY : src/idx/benchmark/BenchmarkEventReaderTest.i # target to preprocess a source file src/idx/benchmark/BenchmarkEventReaderTest.cpp.i: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventReaderTest.cpp.i .PHONY : src/idx/benchmark/BenchmarkEventReaderTest.cpp.i src/idx/benchmark/BenchmarkEventReaderTest.s: src/idx/benchmark/BenchmarkEventReaderTest.cpp.s .PHONY : src/idx/benchmark/BenchmarkEventReaderTest.s # target to generate assembly for a file src/idx/benchmark/BenchmarkEventReaderTest.cpp.s: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventReaderTest.cpp.s .PHONY : src/idx/benchmark/BenchmarkEventReaderTest.cpp.s src/idx/benchmark/BenchmarkEventTest.o: src/idx/benchmark/BenchmarkEventTest.cpp.o .PHONY : src/idx/benchmark/BenchmarkEventTest.o # target to build an object file src/idx/benchmark/BenchmarkEventTest.cpp.o: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventTest.cpp.o .PHONY : src/idx/benchmark/BenchmarkEventTest.cpp.o src/idx/benchmark/BenchmarkEventTest.i: src/idx/benchmark/BenchmarkEventTest.cpp.i .PHONY : src/idx/benchmark/BenchmarkEventTest.i # target to preprocess a source file src/idx/benchmark/BenchmarkEventTest.cpp.i: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventTest.cpp.i .PHONY : src/idx/benchmark/BenchmarkEventTest.cpp.i src/idx/benchmark/BenchmarkEventTest.s: src/idx/benchmark/BenchmarkEventTest.cpp.s .PHONY : src/idx/benchmark/BenchmarkEventTest.s # target to generate assembly for a file src/idx/benchmark/BenchmarkEventTest.cpp.s: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventTest.cpp.s .PHONY : src/idx/benchmark/BenchmarkEventTest.cpp.s src/idx/benchmark/BenchmarkEventTypeIdTest.o: src/idx/benchmark/BenchmarkEventTypeIdTest.cpp.o .PHONY : src/idx/benchmark/BenchmarkEventTypeIdTest.o # target to build an object file src/idx/benchmark/BenchmarkEventTypeIdTest.cpp.o: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventTypeIdTest.cpp.o .PHONY : src/idx/benchmark/BenchmarkEventTypeIdTest.cpp.o src/idx/benchmark/BenchmarkEventTypeIdTest.i: src/idx/benchmark/BenchmarkEventTypeIdTest.cpp.i .PHONY : src/idx/benchmark/BenchmarkEventTypeIdTest.i # target to preprocess a source file src/idx/benchmark/BenchmarkEventTypeIdTest.cpp.i: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventTypeIdTest.cpp.i .PHONY : src/idx/benchmark/BenchmarkEventTypeIdTest.cpp.i src/idx/benchmark/BenchmarkEventTypeIdTest.s: src/idx/benchmark/BenchmarkEventTypeIdTest.cpp.s .PHONY : src/idx/benchmark/BenchmarkEventTypeIdTest.s # target to generate assembly for a file src/idx/benchmark/BenchmarkEventTypeIdTest.cpp.s: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventTypeIdTest.cpp.s .PHONY : src/idx/benchmark/BenchmarkEventTypeIdTest.cpp.s src/idx/benchmark/BenchmarkEventTypeIdToEventTypeMappingTest.o: src/idx/benchmark/BenchmarkEventTypeIdToEventTypeMappingTest.cpp.o .PHONY : src/idx/benchmark/BenchmarkEventTypeIdToEventTypeMappingTest.o # target to build an object file src/idx/benchmark/BenchmarkEventTypeIdToEventTypeMappingTest.cpp.o: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventTypeIdToEventTypeMappingTest.cpp.o .PHONY : src/idx/benchmark/BenchmarkEventTypeIdToEventTypeMappingTest.cpp.o src/idx/benchmark/BenchmarkEventTypeIdToEventTypeMappingTest.i: src/idx/benchmark/BenchmarkEventTypeIdToEventTypeMappingTest.cpp.i .PHONY : src/idx/benchmark/BenchmarkEventTypeIdToEventTypeMappingTest.i # target to preprocess a source file src/idx/benchmark/BenchmarkEventTypeIdToEventTypeMappingTest.cpp.i: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventTypeIdToEventTypeMappingTest.cpp.i .PHONY : src/idx/benchmark/BenchmarkEventTypeIdToEventTypeMappingTest.cpp.i src/idx/benchmark/BenchmarkEventTypeIdToEventTypeMappingTest.s: src/idx/benchmark/BenchmarkEventTypeIdToEventTypeMappingTest.cpp.s .PHONY : src/idx/benchmark/BenchmarkEventTypeIdToEventTypeMappingTest.s # target to generate assembly for a file src/idx/benchmark/BenchmarkEventTypeIdToEventTypeMappingTest.cpp.s: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventTypeIdToEventTypeMappingTest.cpp.s .PHONY : src/idx/benchmark/BenchmarkEventTypeIdToEventTypeMappingTest.cpp.s src/idx/benchmark/BenchmarkLineReaderTest.o: src/idx/benchmark/BenchmarkLineReaderTest.cpp.o .PHONY : src/idx/benchmark/BenchmarkLineReaderTest.o # target to build an object file src/idx/benchmark/BenchmarkLineReaderTest.cpp.o: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkLineReaderTest.cpp.o .PHONY : src/idx/benchmark/BenchmarkLineReaderTest.cpp.o src/idx/benchmark/BenchmarkLineReaderTest.i: src/idx/benchmark/BenchmarkLineReaderTest.cpp.i .PHONY : src/idx/benchmark/BenchmarkLineReaderTest.i # target to preprocess a source file src/idx/benchmark/BenchmarkLineReaderTest.cpp.i: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkLineReaderTest.cpp.i .PHONY : src/idx/benchmark/BenchmarkLineReaderTest.cpp.i src/idx/benchmark/BenchmarkLineReaderTest.s: src/idx/benchmark/BenchmarkLineReaderTest.cpp.s .PHONY : src/idx/benchmark/BenchmarkLineReaderTest.s # target to generate assembly for a file src/idx/benchmark/BenchmarkLineReaderTest.cpp.s: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkLineReaderTest.cpp.s .PHONY : src/idx/benchmark/BenchmarkLineReaderTest.cpp.s src/idx/benchmark/ContentReaderTest.o: src/idx/benchmark/ContentReaderTest.cpp.o .PHONY : src/idx/benchmark/ContentReaderTest.o # target to build an object file src/idx/benchmark/ContentReaderTest.cpp.o: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/ContentReaderTest.cpp.o .PHONY : src/idx/benchmark/ContentReaderTest.cpp.o src/idx/benchmark/ContentReaderTest.i: src/idx/benchmark/ContentReaderTest.cpp.i .PHONY : src/idx/benchmark/ContentReaderTest.i # target to preprocess a source file src/idx/benchmark/ContentReaderTest.cpp.i: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/ContentReaderTest.cpp.i .PHONY : src/idx/benchmark/ContentReaderTest.cpp.i src/idx/benchmark/ContentReaderTest.s: src/idx/benchmark/ContentReaderTest.cpp.s .PHONY : src/idx/benchmark/ContentReaderTest.s # target to generate assembly for a file src/idx/benchmark/ContentReaderTest.cpp.s: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/ContentReaderTest.cpp.s .PHONY : src/idx/benchmark/ContentReaderTest.cpp.s src/idx/benchmark/ContinuosBufferTest.o: src/idx/benchmark/ContinuosBufferTest.cpp.o .PHONY : src/idx/benchmark/ContinuosBufferTest.o # target to build an object file src/idx/benchmark/ContinuosBufferTest.cpp.o: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/ContinuosBufferTest.cpp.o .PHONY : src/idx/benchmark/ContinuosBufferTest.cpp.o src/idx/benchmark/ContinuosBufferTest.i: src/idx/benchmark/ContinuosBufferTest.cpp.i .PHONY : src/idx/benchmark/ContinuosBufferTest.i # target to preprocess a source file src/idx/benchmark/ContinuosBufferTest.cpp.i: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/ContinuosBufferTest.cpp.i .PHONY : src/idx/benchmark/ContinuosBufferTest.cpp.i src/idx/benchmark/ContinuosBufferTest.s: src/idx/benchmark/ContinuosBufferTest.cpp.s .PHONY : src/idx/benchmark/ContinuosBufferTest.s # target to generate assembly for a file src/idx/benchmark/ContinuosBufferTest.cpp.s: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/ContinuosBufferTest.cpp.s .PHONY : src/idx/benchmark/ContinuosBufferTest.cpp.s src/idx/benchmark/TempFile.o: src/idx/benchmark/TempFile.cpp.o .PHONY : src/idx/benchmark/TempFile.o # target to build an object file src/idx/benchmark/TempFile.cpp.o: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/TempFile.cpp.o .PHONY : src/idx/benchmark/TempFile.cpp.o src/idx/benchmark/TempFile.i: src/idx/benchmark/TempFile.cpp.i .PHONY : src/idx/benchmark/TempFile.i # target to preprocess a source file src/idx/benchmark/TempFile.cpp.i: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/TempFile.cpp.i .PHONY : src/idx/benchmark/TempFile.cpp.i src/idx/benchmark/TempFile.s: src/idx/benchmark/TempFile.cpp.s .PHONY : src/idx/benchmark/TempFile.s # target to generate assembly for a file src/idx/benchmark/TempFile.cpp.s: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/TempFile.cpp.s .PHONY : src/idx/benchmark/TempFile.cpp.s src/idx/benchmark/TestModule.o: src/idx/benchmark/TestModule.cpp.o .PHONY : src/idx/benchmark/TestModule.o # target to build an object file src/idx/benchmark/TestModule.cpp.o: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/TestModule.cpp.o .PHONY : src/idx/benchmark/TestModule.cpp.o src/idx/benchmark/TestModule.i: src/idx/benchmark/TestModule.cpp.i .PHONY : src/idx/benchmark/TestModule.i # target to preprocess a source file src/idx/benchmark/TestModule.cpp.i: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/TestModule.cpp.i .PHONY : src/idx/benchmark/TestModule.cpp.i src/idx/benchmark/TestModule.s: src/idx/benchmark/TestModule.cpp.s .PHONY : src/idx/benchmark/TestModule.s # target to generate assembly for a file src/idx/benchmark/TestModule.cpp.s: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/build.make tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/TestModule.cpp.s .PHONY : src/idx/benchmark/TestModule.cpp.s # Help Target help: @echo "The following are some of the valid targets for this Makefile:" @echo "... all (the default if no target is provided)" @echo "... clean" @echo "... depend" @echo "... edit_cache" @echo "... rebuild_cache" @echo "... benchmark-helpers-test" @echo "... test" @echo "... src/idx/benchmark/BenchmarkEventExecutorTest.o" @echo "... src/idx/benchmark/BenchmarkEventExecutorTest.i" @echo "... src/idx/benchmark/BenchmarkEventExecutorTest.s" @echo "... src/idx/benchmark/BenchmarkEventListBackingBufferSizeEstimatorTest.o" @echo "... src/idx/benchmark/BenchmarkEventListBackingBufferSizeEstimatorTest.i" @echo "... src/idx/benchmark/BenchmarkEventListBackingBufferSizeEstimatorTest.s" @echo "... src/idx/benchmark/BenchmarkEventListTest.o" @echo "... src/idx/benchmark/BenchmarkEventListTest.i" @echo "... src/idx/benchmark/BenchmarkEventListTest.s" @echo "... src/idx/benchmark/BenchmarkEventReaderExceptionTest.o" @echo "... src/idx/benchmark/BenchmarkEventReaderExceptionTest.i" @echo "... src/idx/benchmark/BenchmarkEventReaderExceptionTest.s" @echo "... src/idx/benchmark/BenchmarkEventReaderTest.o" @echo "... src/idx/benchmark/BenchmarkEventReaderTest.i" @echo "... src/idx/benchmark/BenchmarkEventReaderTest.s" @echo "... src/idx/benchmark/BenchmarkEventTest.o" @echo "... src/idx/benchmark/BenchmarkEventTest.i" @echo "... src/idx/benchmark/BenchmarkEventTest.s" @echo "... src/idx/benchmark/BenchmarkEventTypeIdTest.o" @echo "... src/idx/benchmark/BenchmarkEventTypeIdTest.i" @echo "... src/idx/benchmark/BenchmarkEventTypeIdTest.s" @echo "... src/idx/benchmark/BenchmarkEventTypeIdToEventTypeMappingTest.o" @echo "... src/idx/benchmark/BenchmarkEventTypeIdToEventTypeMappingTest.i" @echo "... src/idx/benchmark/BenchmarkEventTypeIdToEventTypeMappingTest.s" @echo "... src/idx/benchmark/BenchmarkLineReaderTest.o" @echo "... src/idx/benchmark/BenchmarkLineReaderTest.i" @echo "... src/idx/benchmark/BenchmarkLineReaderTest.s" @echo "... src/idx/benchmark/ContentReaderTest.o" @echo "... src/idx/benchmark/ContentReaderTest.i" @echo "... src/idx/benchmark/ContentReaderTest.s" @echo "... src/idx/benchmark/ContinuosBufferTest.o" @echo "... src/idx/benchmark/ContinuosBufferTest.i" @echo "... src/idx/benchmark/ContinuosBufferTest.s" @echo "... src/idx/benchmark/TempFile.o" @echo "... src/idx/benchmark/TempFile.i" @echo "... src/idx/benchmark/TempFile.s" @echo "... src/idx/benchmark/TestModule.o" @echo "... src/idx/benchmark/TestModule.i" @echo "... src/idx/benchmark/TestModule.s" .PHONY : help #============================================================================= # Special targets to cleanup operation of make. # Special rule to run CMake to check the build system integrity. # No rule that depends on this can have commands that come from listfiles # because they might be regenerated. cmake_check_build_system: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0 .PHONY : cmake_check_build_system <file_sep>file(REMOVE_RECURSE "libhot-test-helpers-lib.a" ) <file_sep># The set of languages for which implicit dependencies are needed: set(CMAKE_DEPENDS_LANGUAGES "CXX" ) # The set of files for implicit dependencies of each language: set(CMAKE_DEPENDS_CHECK_CXX "/home/zhangjoe/Desktop/GraduateWork/hot/tests/hot/test-helpers/src/hot/testhelpers/PartialKeyMappingTestHelper.cpp" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/hot/test-helpers/CMakeFiles/hot-test-helpers-lib.dir/src/hot/testhelpers/PartialKeyMappingTestHelper.cpp.o" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/hot/test-helpers/src/hot/testhelpers/SampleTriples.cpp" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/hot/test-helpers/CMakeFiles/hot-test-helpers-lib.dir/src/hot/testhelpers/SampleTriples.cpp.o" ) set(CMAKE_CXX_COMPILER_ID "GNU") # Preprocessor definitions for this target. set(CMAKE_TARGET_DEFINITIONS_CXX "BOOST_ALL_NO_LIB=1" "BOOST_SYSTEM_NO_DEPRECATED" "BOOST_THREAD_PROVIDES_EXECUTORS" "BOOST_THREAD_USES_CHRONO" "BOOST_THREAD_VERSION=4" ) # The include file search paths: set(CMAKE_CXX_TARGET_INCLUDE_PATH "tests/hot/test-helpers/include" "libs/hot/commons/include" "libs/idx/content-helpers/include" "_deps/boost-src" ) # Targets to which this target links. set(CMAKE_TARGET_LINKED_INFO_FILES "/home/zhangjoe/Desktop/GraduateWork/hot/third-party/boost-cmake/CMakeFiles/Boost_unit_test_framework.dir/DependInfo.cmake" "/home/zhangjoe/Desktop/GraduateWork/hot/third-party/boost-cmake/CMakeFiles/Boost_timer.dir/DependInfo.cmake" "/home/zhangjoe/Desktop/GraduateWork/hot/third-party/boost-cmake/CMakeFiles/Boost_chrono.dir/DependInfo.cmake" ) # Fortran module output directory. set(CMAKE_Fortran_TARGET_MODULE_DIR "") <file_sep># CMake generated Testfile for # Source directory: /home/zhangjoe/Desktop/GraduateWork/hot/libs # Build directory: /home/zhangjoe/Desktop/GraduateWork/hot/libs # # This file includes the relevant testing commands required for # testing this directory and lists subdirectories to be tested as well. subdirs("idx") subdirs("hot") subdirs("profile-lib") <file_sep># The set of languages for which implicit dependencies are needed: set(CMAKE_DEPENDS_LANGUAGES "CXX" ) # The set of files for implicit dependencies of each language: set(CMAKE_DEPENDS_CHECK_CXX "/home/zhangjoe/Desktop/GraduateWork/hot/tests/hot/commons-test/src/hot/commons/AlgorithmsTest.cpp" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/src/hot/commons/AlgorithmsTest.cpp.o" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/hot/commons-test/src/hot/commons/DiscriminativeBitTest.cpp" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/src/hot/commons/DiscriminativeBitTest.cpp.o" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/hot/commons-test/src/hot/commons/MultiMaskPartialKeyMappingTest.cpp" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/src/hot/commons/MultiMaskPartialKeyMappingTest.cpp.o" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/hot/commons-test/src/hot/commons/SIMDHelperTest.cpp" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/src/hot/commons/SIMDHelperTest.cpp.o" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/hot/commons-test/src/hot/commons/SingleMaskPartialKeyMappingTest.cpp" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/src/hot/commons/SingleMaskPartialKeyMappingTest.cpp.o" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/hot/commons-test/src/hot/commons/SparsePartialKeysTest.cpp" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/src/hot/commons/SparsePartialKeysTest.cpp.o" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/hot/commons-test/src/hot/commons/TestModule.cpp" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/hot/commons-test/CMakeFiles/hot-commons-test.dir/src/hot/commons/TestModule.cpp.o" ) set(CMAKE_CXX_COMPILER_ID "GNU") # Preprocessor definitions for this target. set(CMAKE_TARGET_DEFINITIONS_CXX "BOOST_ALL_NO_LIB=1" "BOOST_SYSTEM_NO_DEPRECATED" "BOOST_THREAD_PROVIDES_EXECUTORS" "BOOST_THREAD_USES_CHRONO" "BOOST_THREAD_VERSION=4" ) # The include file search paths: set(CMAKE_CXX_TARGET_INCLUDE_PATH "tests/hot/commons-test/include" "libs/idx/content-helpers/include" "libs/idx/utils/include" "libs/idx/utils" "libs/hot/commons/include" "tests/hot/test-helpers/include" "_deps/boost-src" "third-party/tbb/include" ) # Targets to which this target links. set(CMAKE_TARGET_LINKED_INFO_FILES "/home/zhangjoe/Desktop/GraduateWork/hot/third-party/boost-cmake/CMakeFiles/Boost_unit_test_framework.dir/DependInfo.cmake" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/hot/test-helpers/CMakeFiles/hot-test-helpers-lib.dir/DependInfo.cmake" "/home/zhangjoe/Desktop/GraduateWork/hot/third-party/boost-cmake/CMakeFiles/Boost_timer.dir/DependInfo.cmake" "/home/zhangjoe/Desktop/GraduateWork/hot/third-party/boost-cmake/CMakeFiles/Boost_chrono.dir/DependInfo.cmake" ) # Fortran module output directory. set(CMAKE_Fortran_TARGET_MODULE_DIR "") <file_sep># CMAKE generated file: DO NOT EDIT! # Generated by "Unix Makefiles" Generator, CMake Version 3.16 # Default target executed when no arguments are given to make. default_target: all .PHONY : default_target # Allow only one "make -f Makefile2" at a time, but pass parallelism. .NOTPARALLEL: #============================================================================= # Special targets provided by cmake. # Disable implicit rules so canonical targets will work. .SUFFIXES: # Remove some rules from gmake that .SUFFIXES does not remove. SUFFIXES = .SUFFIXES: .hpux_make_needs_suffix_list # Suppress display of executed commands. $(VERBOSE).SILENT: # A target that is always out of date. cmake_force: .PHONY : cmake_force #============================================================================= # Set environment variables for the build. # The shell in which to execute make rules. SHELL = /bin/sh # The CMake executable. CMAKE_COMMAND = /usr/local/bin/cmake # The command to remove a file. RM = /usr/local/bin/cmake -E remove -f # Escaping for special characters. EQUALS = = # The top-level source directory on which CMake was run. CMAKE_SOURCE_DIR = /home/zhangjoe/Desktop/GraduateWork/hot # The top-level build directory on which CMake was run. CMAKE_BINARY_DIR = /home/zhangjoe/Desktop/GraduateWork/hot #============================================================================= # Targets provided globally by CMake. # Special rule for the target rebuild_cache rebuild_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..." /usr/local/bin/cmake -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) .PHONY : rebuild_cache # Special rule for the target rebuild_cache rebuild_cache/fast: rebuild_cache .PHONY : rebuild_cache/fast # Special rule for the target edit_cache edit_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "No interactive CMake dialog available..." /usr/local/bin/cmake -E echo No\ interactive\ CMake\ dialog\ available. .PHONY : edit_cache # Special rule for the target edit_cache edit_cache/fast: edit_cache .PHONY : edit_cache/fast # Special rule for the target test test: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running tests..." /usr/local/bin/ctest --force-new-ctest-process $(ARGS) .PHONY : test # Special rule for the target test test/fast: test .PHONY : test/fast # The main all target all: cmake_check_build_system cd /home/zhangjoe/Desktop/GraduateWork/hot && $(CMAKE_COMMAND) -E cmake_progress_start /home/zhangjoe/Desktop/GraduateWork/hot/CMakeFiles /home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/content-helpers-test/CMakeFiles/progress.marks cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f CMakeFiles/Makefile2 tests/idx/content-helpers-test/all $(CMAKE_COMMAND) -E cmake_progress_start /home/zhangjoe/Desktop/GraduateWork/hot/CMakeFiles 0 .PHONY : all # The main clean target clean: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f CMakeFiles/Makefile2 tests/idx/content-helpers-test/clean .PHONY : clean # The main clean target clean/fast: clean .PHONY : clean/fast # Prepare targets for installation. preinstall: all cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f CMakeFiles/Makefile2 tests/idx/content-helpers-test/preinstall .PHONY : preinstall # Prepare targets for installation. preinstall/fast: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f CMakeFiles/Makefile2 tests/idx/content-helpers-test/preinstall .PHONY : preinstall/fast # clear depends depend: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1 .PHONY : depend # Convenience name for target. tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/rule: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f CMakeFiles/Makefile2 tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/rule .PHONY : tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/rule # Convenience name for target. content-helpers-test: tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/rule .PHONY : content-helpers-test # fast build rule for target. content-helpers-test/fast: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/build.make tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/build .PHONY : content-helpers-test/fast src/idx/contenthelpers/CStringComparatorTest.o: src/idx/contenthelpers/CStringComparatorTest.cpp.o .PHONY : src/idx/contenthelpers/CStringComparatorTest.o # target to build an object file src/idx/contenthelpers/CStringComparatorTest.cpp.o: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/build.make tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/CStringComparatorTest.cpp.o .PHONY : src/idx/contenthelpers/CStringComparatorTest.cpp.o src/idx/contenthelpers/CStringComparatorTest.i: src/idx/contenthelpers/CStringComparatorTest.cpp.i .PHONY : src/idx/contenthelpers/CStringComparatorTest.i # target to preprocess a source file src/idx/contenthelpers/CStringComparatorTest.cpp.i: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/build.make tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/CStringComparatorTest.cpp.i .PHONY : src/idx/contenthelpers/CStringComparatorTest.cpp.i src/idx/contenthelpers/CStringComparatorTest.s: src/idx/contenthelpers/CStringComparatorTest.cpp.s .PHONY : src/idx/contenthelpers/CStringComparatorTest.s # target to generate assembly for a file src/idx/contenthelpers/CStringComparatorTest.cpp.s: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/build.make tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/CStringComparatorTest.cpp.s .PHONY : src/idx/contenthelpers/CStringComparatorTest.cpp.s src/idx/contenthelpers/ContentEqualsTest.o: src/idx/contenthelpers/ContentEqualsTest.cpp.o .PHONY : src/idx/contenthelpers/ContentEqualsTest.o # target to build an object file src/idx/contenthelpers/ContentEqualsTest.cpp.o: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/build.make tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/ContentEqualsTest.cpp.o .PHONY : src/idx/contenthelpers/ContentEqualsTest.cpp.o src/idx/contenthelpers/ContentEqualsTest.i: src/idx/contenthelpers/ContentEqualsTest.cpp.i .PHONY : src/idx/contenthelpers/ContentEqualsTest.i # target to preprocess a source file src/idx/contenthelpers/ContentEqualsTest.cpp.i: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/build.make tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/ContentEqualsTest.cpp.i .PHONY : src/idx/contenthelpers/ContentEqualsTest.cpp.i src/idx/contenthelpers/ContentEqualsTest.s: src/idx/contenthelpers/ContentEqualsTest.cpp.s .PHONY : src/idx/contenthelpers/ContentEqualsTest.s # target to generate assembly for a file src/idx/contenthelpers/ContentEqualsTest.cpp.s: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/build.make tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/ContentEqualsTest.cpp.s .PHONY : src/idx/contenthelpers/ContentEqualsTest.cpp.s src/idx/contenthelpers/IdentityKeyExtractorTest.o: src/idx/contenthelpers/IdentityKeyExtractorTest.cpp.o .PHONY : src/idx/contenthelpers/IdentityKeyExtractorTest.o # target to build an object file src/idx/contenthelpers/IdentityKeyExtractorTest.cpp.o: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/build.make tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/IdentityKeyExtractorTest.cpp.o .PHONY : src/idx/contenthelpers/IdentityKeyExtractorTest.cpp.o src/idx/contenthelpers/IdentityKeyExtractorTest.i: src/idx/contenthelpers/IdentityKeyExtractorTest.cpp.i .PHONY : src/idx/contenthelpers/IdentityKeyExtractorTest.i # target to preprocess a source file src/idx/contenthelpers/IdentityKeyExtractorTest.cpp.i: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/build.make tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/IdentityKeyExtractorTest.cpp.i .PHONY : src/idx/contenthelpers/IdentityKeyExtractorTest.cpp.i src/idx/contenthelpers/IdentityKeyExtractorTest.s: src/idx/contenthelpers/IdentityKeyExtractorTest.cpp.s .PHONY : src/idx/contenthelpers/IdentityKeyExtractorTest.s # target to generate assembly for a file src/idx/contenthelpers/IdentityKeyExtractorTest.cpp.s: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/build.make tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/IdentityKeyExtractorTest.cpp.s .PHONY : src/idx/contenthelpers/IdentityKeyExtractorTest.cpp.s src/idx/contenthelpers/KeyComparatorTest.o: src/idx/contenthelpers/KeyComparatorTest.cpp.o .PHONY : src/idx/contenthelpers/KeyComparatorTest.o # target to build an object file src/idx/contenthelpers/KeyComparatorTest.cpp.o: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/build.make tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/KeyComparatorTest.cpp.o .PHONY : src/idx/contenthelpers/KeyComparatorTest.cpp.o src/idx/contenthelpers/KeyComparatorTest.i: src/idx/contenthelpers/KeyComparatorTest.cpp.i .PHONY : src/idx/contenthelpers/KeyComparatorTest.i # target to preprocess a source file src/idx/contenthelpers/KeyComparatorTest.cpp.i: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/build.make tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/KeyComparatorTest.cpp.i .PHONY : src/idx/contenthelpers/KeyComparatorTest.cpp.i src/idx/contenthelpers/KeyComparatorTest.s: src/idx/contenthelpers/KeyComparatorTest.cpp.s .PHONY : src/idx/contenthelpers/KeyComparatorTest.s # target to generate assembly for a file src/idx/contenthelpers/KeyComparatorTest.cpp.s: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/build.make tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/KeyComparatorTest.cpp.s .PHONY : src/idx/contenthelpers/KeyComparatorTest.cpp.s src/idx/contenthelpers/OptionalValueTest.o: src/idx/contenthelpers/OptionalValueTest.cpp.o .PHONY : src/idx/contenthelpers/OptionalValueTest.o # target to build an object file src/idx/contenthelpers/OptionalValueTest.cpp.o: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/build.make tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/OptionalValueTest.cpp.o .PHONY : src/idx/contenthelpers/OptionalValueTest.cpp.o src/idx/contenthelpers/OptionalValueTest.i: src/idx/contenthelpers/OptionalValueTest.cpp.i .PHONY : src/idx/contenthelpers/OptionalValueTest.i # target to preprocess a source file src/idx/contenthelpers/OptionalValueTest.cpp.i: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/build.make tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/OptionalValueTest.cpp.i .PHONY : src/idx/contenthelpers/OptionalValueTest.cpp.i src/idx/contenthelpers/OptionalValueTest.s: src/idx/contenthelpers/OptionalValueTest.cpp.s .PHONY : src/idx/contenthelpers/OptionalValueTest.s # target to generate assembly for a file src/idx/contenthelpers/OptionalValueTest.cpp.s: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/build.make tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/OptionalValueTest.cpp.s .PHONY : src/idx/contenthelpers/OptionalValueTest.cpp.s src/idx/contenthelpers/PairKeyExtractorTest.o: src/idx/contenthelpers/PairKeyExtractorTest.cpp.o .PHONY : src/idx/contenthelpers/PairKeyExtractorTest.o # target to build an object file src/idx/contenthelpers/PairKeyExtractorTest.cpp.o: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/build.make tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/PairKeyExtractorTest.cpp.o .PHONY : src/idx/contenthelpers/PairKeyExtractorTest.cpp.o src/idx/contenthelpers/PairKeyExtractorTest.i: src/idx/contenthelpers/PairKeyExtractorTest.cpp.i .PHONY : src/idx/contenthelpers/PairKeyExtractorTest.i # target to preprocess a source file src/idx/contenthelpers/PairKeyExtractorTest.cpp.i: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/build.make tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/PairKeyExtractorTest.cpp.i .PHONY : src/idx/contenthelpers/PairKeyExtractorTest.cpp.i src/idx/contenthelpers/PairKeyExtractorTest.s: src/idx/contenthelpers/PairKeyExtractorTest.cpp.s .PHONY : src/idx/contenthelpers/PairKeyExtractorTest.s # target to generate assembly for a file src/idx/contenthelpers/PairKeyExtractorTest.cpp.s: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/build.make tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/PairKeyExtractorTest.cpp.s .PHONY : src/idx/contenthelpers/PairKeyExtractorTest.cpp.s src/idx/contenthelpers/PairPointerKeyExtractorTest.o: src/idx/contenthelpers/PairPointerKeyExtractorTest.cpp.o .PHONY : src/idx/contenthelpers/PairPointerKeyExtractorTest.o # target to build an object file src/idx/contenthelpers/PairPointerKeyExtractorTest.cpp.o: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/build.make tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/PairPointerKeyExtractorTest.cpp.o .PHONY : src/idx/contenthelpers/PairPointerKeyExtractorTest.cpp.o src/idx/contenthelpers/PairPointerKeyExtractorTest.i: src/idx/contenthelpers/PairPointerKeyExtractorTest.cpp.i .PHONY : src/idx/contenthelpers/PairPointerKeyExtractorTest.i # target to preprocess a source file src/idx/contenthelpers/PairPointerKeyExtractorTest.cpp.i: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/build.make tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/PairPointerKeyExtractorTest.cpp.i .PHONY : src/idx/contenthelpers/PairPointerKeyExtractorTest.cpp.i src/idx/contenthelpers/PairPointerKeyExtractorTest.s: src/idx/contenthelpers/PairPointerKeyExtractorTest.cpp.s .PHONY : src/idx/contenthelpers/PairPointerKeyExtractorTest.s # target to generate assembly for a file src/idx/contenthelpers/PairPointerKeyExtractorTest.cpp.s: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/build.make tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/PairPointerKeyExtractorTest.cpp.s .PHONY : src/idx/contenthelpers/PairPointerKeyExtractorTest.cpp.s src/idx/contenthelpers/TestModule.o: src/idx/contenthelpers/TestModule.cpp.o .PHONY : src/idx/contenthelpers/TestModule.o # target to build an object file src/idx/contenthelpers/TestModule.cpp.o: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/build.make tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/TestModule.cpp.o .PHONY : src/idx/contenthelpers/TestModule.cpp.o src/idx/contenthelpers/TestModule.i: src/idx/contenthelpers/TestModule.cpp.i .PHONY : src/idx/contenthelpers/TestModule.i # target to preprocess a source file src/idx/contenthelpers/TestModule.cpp.i: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/build.make tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/TestModule.cpp.i .PHONY : src/idx/contenthelpers/TestModule.cpp.i src/idx/contenthelpers/TestModule.s: src/idx/contenthelpers/TestModule.cpp.s .PHONY : src/idx/contenthelpers/TestModule.s # target to generate assembly for a file src/idx/contenthelpers/TestModule.cpp.s: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/build.make tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/TestModule.cpp.s .PHONY : src/idx/contenthelpers/TestModule.cpp.s src/idx/contenthelpers/ValueToKeyTypeMapperTest.o: src/idx/contenthelpers/ValueToKeyTypeMapperTest.cpp.o .PHONY : src/idx/contenthelpers/ValueToKeyTypeMapperTest.o # target to build an object file src/idx/contenthelpers/ValueToKeyTypeMapperTest.cpp.o: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/build.make tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/ValueToKeyTypeMapperTest.cpp.o .PHONY : src/idx/contenthelpers/ValueToKeyTypeMapperTest.cpp.o src/idx/contenthelpers/ValueToKeyTypeMapperTest.i: src/idx/contenthelpers/ValueToKeyTypeMapperTest.cpp.i .PHONY : src/idx/contenthelpers/ValueToKeyTypeMapperTest.i # target to preprocess a source file src/idx/contenthelpers/ValueToKeyTypeMapperTest.cpp.i: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/build.make tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/ValueToKeyTypeMapperTest.cpp.i .PHONY : src/idx/contenthelpers/ValueToKeyTypeMapperTest.cpp.i src/idx/contenthelpers/ValueToKeyTypeMapperTest.s: src/idx/contenthelpers/ValueToKeyTypeMapperTest.cpp.s .PHONY : src/idx/contenthelpers/ValueToKeyTypeMapperTest.s # target to generate assembly for a file src/idx/contenthelpers/ValueToKeyTypeMapperTest.cpp.s: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(MAKE) -f tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/build.make tests/idx/content-helpers-test/CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/ValueToKeyTypeMapperTest.cpp.s .PHONY : src/idx/contenthelpers/ValueToKeyTypeMapperTest.cpp.s # Help Target help: @echo "The following are some of the valid targets for this Makefile:" @echo "... all (the default if no target is provided)" @echo "... clean" @echo "... depend" @echo "... rebuild_cache" @echo "... edit_cache" @echo "... content-helpers-test" @echo "... test" @echo "... src/idx/contenthelpers/CStringComparatorTest.o" @echo "... src/idx/contenthelpers/CStringComparatorTest.i" @echo "... src/idx/contenthelpers/CStringComparatorTest.s" @echo "... src/idx/contenthelpers/ContentEqualsTest.o" @echo "... src/idx/contenthelpers/ContentEqualsTest.i" @echo "... src/idx/contenthelpers/ContentEqualsTest.s" @echo "... src/idx/contenthelpers/IdentityKeyExtractorTest.o" @echo "... src/idx/contenthelpers/IdentityKeyExtractorTest.i" @echo "... src/idx/contenthelpers/IdentityKeyExtractorTest.s" @echo "... src/idx/contenthelpers/KeyComparatorTest.o" @echo "... src/idx/contenthelpers/KeyComparatorTest.i" @echo "... src/idx/contenthelpers/KeyComparatorTest.s" @echo "... src/idx/contenthelpers/OptionalValueTest.o" @echo "... src/idx/contenthelpers/OptionalValueTest.i" @echo "... src/idx/contenthelpers/OptionalValueTest.s" @echo "... src/idx/contenthelpers/PairKeyExtractorTest.o" @echo "... src/idx/contenthelpers/PairKeyExtractorTest.i" @echo "... src/idx/contenthelpers/PairKeyExtractorTest.s" @echo "... src/idx/contenthelpers/PairPointerKeyExtractorTest.o" @echo "... src/idx/contenthelpers/PairPointerKeyExtractorTest.i" @echo "... src/idx/contenthelpers/PairPointerKeyExtractorTest.s" @echo "... src/idx/contenthelpers/TestModule.o" @echo "... src/idx/contenthelpers/TestModule.i" @echo "... src/idx/contenthelpers/TestModule.s" @echo "... src/idx/contenthelpers/ValueToKeyTypeMapperTest.o" @echo "... src/idx/contenthelpers/ValueToKeyTypeMapperTest.i" @echo "... src/idx/contenthelpers/ValueToKeyTypeMapperTest.s" .PHONY : help #============================================================================= # Special targets to cleanup operation of make. # Special rule to run CMake to check the build system integrity. # No rule that depends on this can have commands that come from listfiles # because they might be regenerated. cmake_check_build_system: cd /home/zhangjoe/Desktop/GraduateWork/hot && $(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0 .PHONY : cmake_check_build_system <file_sep>#include <string> namespace idx { namespace utils { const std::string g_GIT_SHA1 = "96bf6fb7103b27e50e16a6026db8974c090ee84a"; } } <file_sep># CMake generated Testfile for # Source directory: /home/zhangjoe/Desktop/GraduateWork/hot/libs/hot # Build directory: /home/zhangjoe/Desktop/GraduateWork/hot/libs/hot # # This file includes the relevant testing commands required for # testing this directory and lists subdirectories to be tested as well. subdirs("commons") subdirs("rowex") subdirs("single-threaded") <file_sep>file(REMOVE_RECURSE "CMakeFiles/map-helpers-test.dir/src/idx/maphelpers/MapValueExtractorTest.cpp.o" "CMakeFiles/map-helpers-test.dir/src/idx/maphelpers/STLLikeIndexTest.cpp.o" "CMakeFiles/map-helpers-test.dir/src/idx/maphelpers/TestModule.cpp.o" "map-helpers-test" "map-helpers-test.pdb" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/map-helpers-test.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep>file(REMOVE_RECURSE "CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/CStringComparatorTest.cpp.o" "CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/ContentEqualsTest.cpp.o" "CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/IdentityKeyExtractorTest.cpp.o" "CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/KeyComparatorTest.cpp.o" "CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/OptionalValueTest.cpp.o" "CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/PairKeyExtractorTest.cpp.o" "CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/PairPointerKeyExtractorTest.cpp.o" "CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/TestModule.cpp.o" "CMakeFiles/content-helpers-test.dir/src/idx/contenthelpers/ValueToKeyTypeMapperTest.cpp.o" "content-helpers-test" "content-helpers-test.pdb" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/content-helpers-test.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep># The set of languages for which implicit dependencies are needed: set(CMAKE_DEPENDS_LANGUAGES "CXX" ) # The set of files for implicit dependencies of each language: set(CMAKE_DEPENDS_CHECK_CXX "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/benchmark-helpers-test/src/idx/benchmark/BenchmarkEventExecutorTest.cpp" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventExecutorTest.cpp.o" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/benchmark-helpers-test/src/idx/benchmark/BenchmarkEventListBackingBufferSizeEstimatorTest.cpp" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventListBackingBufferSizeEstimatorTest.cpp.o" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/benchmark-helpers-test/src/idx/benchmark/BenchmarkEventListTest.cpp" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventListTest.cpp.o" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/benchmark-helpers-test/src/idx/benchmark/BenchmarkEventReaderExceptionTest.cpp" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventReaderExceptionTest.cpp.o" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/benchmark-helpers-test/src/idx/benchmark/BenchmarkEventReaderTest.cpp" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventReaderTest.cpp.o" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/benchmark-helpers-test/src/idx/benchmark/BenchmarkEventTest.cpp" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventTest.cpp.o" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/benchmark-helpers-test/src/idx/benchmark/BenchmarkEventTypeIdTest.cpp" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventTypeIdTest.cpp.o" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/benchmark-helpers-test/src/idx/benchmark/BenchmarkEventTypeIdToEventTypeMappingTest.cpp" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkEventTypeIdToEventTypeMappingTest.cpp.o" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/benchmark-helpers-test/src/idx/benchmark/BenchmarkLineReaderTest.cpp" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/BenchmarkLineReaderTest.cpp.o" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/benchmark-helpers-test/src/idx/benchmark/ContentReaderTest.cpp" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/ContentReaderTest.cpp.o" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/benchmark-helpers-test/src/idx/benchmark/ContinuosBufferTest.cpp" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/ContinuosBufferTest.cpp.o" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/benchmark-helpers-test/src/idx/benchmark/TempFile.cpp" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/TempFile.cpp.o" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/benchmark-helpers-test/src/idx/benchmark/TestModule.cpp" "/home/zhangjoe/Desktop/GraduateWork/hot/tests/idx/benchmark-helpers-test/CMakeFiles/benchmark-helpers-test.dir/src/idx/benchmark/TestModule.cpp.o" ) set(CMAKE_CXX_COMPILER_ID "GNU") # Preprocessor definitions for this target. set(CMAKE_TARGET_DEFINITIONS_CXX "BOOST_ALL_NO_LIB=1" "BOOST_SYSTEM_NO_DEPRECATED" "BOOST_THREAD_PROVIDES_EXECUTORS" "BOOST_THREAD_USES_CHRONO" "BOOST_THREAD_VERSION=4" ) # The include file search paths: set(CMAKE_CXX_TARGET_INCLUDE_PATH "tests/idx/benchmark-helpers-test/include" "libs/idx/benchmark-helpers/include" "libs/idx/utils/include" "libs/idx/utils" "libs/idx/content-helpers/include" "libs/idx/map-helpers/include" "_deps/boost-src" "third-party/tbb/include" ) # Targets to which this target links. set(CMAKE_TARGET_LINKED_INFO_FILES "/home/zhangjoe/Desktop/GraduateWork/hot/third-party/boost-cmake/CMakeFiles/Boost_unit_test_framework.dir/DependInfo.cmake" "/home/zhangjoe/Desktop/GraduateWork/hot/third-party/boost-cmake/CMakeFiles/Boost_timer.dir/DependInfo.cmake" "/home/zhangjoe/Desktop/GraduateWork/hot/third-party/boost-cmake/CMakeFiles/Boost_chrono.dir/DependInfo.cmake" ) # Fortran module output directory. set(CMAKE_Fortran_TARGET_MODULE_DIR "") <file_sep># HOT_src This is our modification of HOT <file_sep>file(REMOVE_RECURSE "CMakeFiles/hot-rowex-test.dir/src/hot/rowex/HOTRowexNodeTest.cpp.o" "CMakeFiles/hot-rowex-test.dir/src/hot/rowex/HOTRowexTest.cpp.o" "CMakeFiles/hot-rowex-test.dir/src/hot/rowex/StringTestData.cpp.o" "CMakeFiles/hot-rowex-test.dir/src/hot/rowex/TestModule.cpp.o" "hot-rowex-test" "hot-rowex-test.pdb" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/hot-rowex-test.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach()
b231779148bcb9e42c406d4f87e67d7c983b8b2f
[ "Markdown", "Makefile", "CMake", "C++" ]
23
Makefile
ZhangJiaQiao/HOT_src
027dae3846f0e8dc840297815a93123ee8a2c9c4
ea2161ed4cab1ff69e2c9c76d0bdba3bb02d334e
refs/heads/master
<file_sep>package Week10; import org.junit.Test; import static org.junit.Assert.assertEquals; public class FindingGCDTestTest { @Test public void testFindingGCD() { //given FindingGCDTest gcdTest = new FindingGCDTest(); int expectedResult = 5; //when int actualResult = gcdTest.findingGCD(); //then assertEquals(expectedResult, actualResult); } }<file_sep>package Week10; public class BasicCalculator { public int sumCalculator(){ int result = 2+3; System.out.println(result); return result; } public int mulitplyCalculator(){ int result = 2*3; System.out.println(result); return result; } public double divideCalculator() { double result = 2 / 3; System.out.println(result); return result; } public static void main(String[] args) { BasicCalculator basicCalculator = new BasicCalculator(); basicCalculator.sumCalculator(); basicCalculator.mulitplyCalculator(); basicCalculator.divideCalculator(); } } ;<file_sep>package Week10; import org.junit.Test; import static org.junit.Assert.assertEquals; public class BasicCalculatorTest { @Test public void shouldReturnCorrectResultWhenSumupTwoNumbers() { //given BasicCalculator basicCalculator = new BasicCalculator(); int expectedResult = 5; //when int actualResult = basicCalculator.sumCalculator(); //then assertEquals(expectedResult, actualResult); } @Test public void shouldReturnCorrectResultWhenMultiplyupTwoNumbers2() { //given BasicCalculator basicCalculator = new BasicCalculator(); int expectedResult = 6; //when int actualResult = basicCalculator.mulitplyCalculator(); //then assertEquals(expectedResult, actualResult); } @Test public void shouldReturnCorrectResultWhenDivisionupTwoNumbers3() { //given BasicCalculator basicCalculator = new BasicCalculator(); double expectedResult = 0.25; //when double actualResult = basicCalculator.divideCalculator(); //then assertEquals(5, 3,2); } }
43cceb13df39bc1b7a1374f9c0a6cbd24811d7d6
[ "Java" ]
3
Java
Clogogo/Java-training-Testing
621efb6542d90aacd5db18593f9bf4d49a33e291
060b5cc2b9596f8d6a85e39ffc9a1b26a4c1ee9c
refs/heads/master
<file_sep>import React,{useState} from 'react' function Contact(props){ // const [name,setName]=useState('abinash') // const [age,setAge]=useState(27) // useEffect(()=>{ // console.warn("hello from hook") // },[age]) //for props explaintions // useEffect(()=>{ // console.warn("Check props", props.name) // },[]) // useEffect(()=>{ // console.warn("Check props 2 for update", props.name) // },[props.name]) const[val,setVal]=useState("Abinash") const test = (e) => { console.warn("test function", e.target.value) setVal(e.target.value) } // let data="Contact us Component" return( <div> <h1>Contact Us Component</h1> <input type="text" value={val} onChange={test}/> {/* <button onClick={()=>console.warn("test function2")}>Click me</button> */} <button onClick={()=>alert(val)}>Click me</button> {/* <h2>{props.name}</h2> */} {/* <h2>{name}</h2> <h2>{age}</h2> <button onClick={()=>setAge(72)}>Update Name</button> <button onClick={()=>setName("<NAME>")}>Update Name</button> */} </div> ) } export default Contact;
34617a542bca12cfef906e63246c60ec2cc59ba7
[ "JavaScript" ]
1
JavaScript
AbinashThakur/react-course
03c1684818050d6f1a773371b36d8801266bb588
fac0a2b3339e7bedbfe7f7e309c664ecc2e509c5
refs/heads/master
<repo_name>CSCI513-Spring20/Assignment1-team-atluri-mundru<file_sep>/Assignment1/src/SearchStrategy.java public interface SearchStrategy { public void search(int game[][]); } <file_sep>/Assignment1/src/BattleShip.java import java.io.BufferedReader; import java.io.FileReader; import java.util.*; public class BattleShip { int carrier = 1; int submarine = 2; String line; List<int[][]> a_list = new ArrayList<int[][]>(); int[][] game = new int[25][25]; static SearchStrategy searchS; public void strategy_implementation(SearchStrategy s_strategy){ searchS = s_strategy; } public List<int[][]> grid_alignment(String fileName){ try { FileReader i_file = new FileReader(fileName); BufferedReader buffer_reader = new BufferedReader(i_file); for(int i=0;i<=2;i++) { String l = buffer_reader.readLine(); StringTokenizer token = new StringTokenizer(l,"()"); for(int j=0;j<8;j++) { String element = token.nextToken(); StringTokenizer token_firstc = new StringTokenizer(element,","); int a = Integer.parseInt(token_firstc.nextToken()); int b = Integer.parseInt(token_firstc.nextToken()); if(j<5) { game[a][b] = carrier; } else { game[a][b] = submarine; } } //for (int row = 0; row < game.length; row++) { // for (int column = 0; column < game.length; column++) { //System.out.print(game[row][column]+" "); // } //System.out.println(); //} // Creating object and calling method of Horizontal Sweep Strategy HorizontalSweepStrategy horizontal_strategy = new HorizontalSweepStrategy(); horizontal_strategy.search(game); // Creating object and calling method of random search strategy RandomSearchStrategy random_strategy = new RandomSearchStrategy(); random_strategy.search(game); // Creating object and calling method of Strategic Search StrategicSearch strategy = new StrategicSearch(); int result[]=strategy.findingshipsefficient(game); //for(int s=0;s<8;s++) { //System.out.print(result[s]+" "); //} System.out.println("Strategy:Strategic Search"); System.out.println("Number of Cells Searched:"+result[8]); System.out.print("Carrier Found:"+"("+result[0]+","+result[1]+")"+"to"+"("+result[2]+","+result[3]+")"); System.out.println(" SubMarine Found:"+"("+result[4]+","+result[5]+")"+"to"+"("+"("+result[6]+","+result[7]+")"); //System.out.println("-------------------------------------------------"); for (int row = 0; row < game.length; row++) { for (int column = 0; column < game.length; column++) { game[row][column]=0; } } } buffer_reader.close(); } catch(Exception e) { System.out.println("Exception is "+e); } return a_list; } public void reading_from_input(){ a_list = grid_alignment("src/input.txt"); // System.out.println(mylist); } public static void main(String[] args) { BattleShip battleship = new BattleShip(); battleship.reading_from_input(); } }
e698006d1f521d4a08c4761afe05861bd513a2ff
[ "Java" ]
2
Java
CSCI513-Spring20/Assignment1-team-atluri-mundru
0b9372b304d07f73079638c0e21ce40f60137bbe
09ddf3dc0a26c6c0e709fd87f250409d2e83bf53
refs/heads/master
<repo_name>erisonliang/E-Mail-Web-Api-Windows-Service<file_sep>/EmailWindowsService/Model/EmailViewModel.cs using System; using System.Collections.Generic; namespace EmailWindowsService.Model { public class EMailViewModel { public EMailViewModel() { EmailAttachments = new List<EMailAttachmentViewModel>(); } public int Id { get; set; } public string SmtpServer { get; set; } public string From { get; set; } public string To { get; set; } public string Cc { get; set; } public string Bcc { get; set; } public string Subject { get; set; } public string Body { get; set; } public DateTime? SentDate { get; set; } public bool IsSent { get; set; } public bool IsRead { get; set; } public DateTime? ReadingDate { get; set; } public int Retry { get; set; } public DateTime? LastTryDate { get; set; } public string Exception { get; set; } public List<EMailAttachmentViewModel> EmailAttachments { get; set; } } } <file_sep>/EmailWebApi/Model/EMailModel.cs using System; using System.Collections.Generic; namespace EmailWebApi.Model { public class EMailModel { public int Id { get; set; } public string SmtpServer { get; set; } public string From { get; set; } public string To { get; set; } public string Cc { get; set; } public string Bcc { get; set; } public string Subject { get; set; } public string Body { get; set; } public DateTime? SentDate { get; set; } public bool IsSent { get; set; } public bool IsRead { get; set; } public DateTime? ReadingDate { get; set; } public int Retry { get; set; } public DateTime? LastTryDate { get; set; } public string Exception { get; set; } public List<EmailAttachment> EmailAttachments { get; set; } } }<file_sep>/EmailWebApi/Controllers/MailController.cs using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Net; using System.Net.Mail; using System.Net.Mime; using System.Threading.Tasks; using System.Web.Http; using EmailWebApi.Model; using YourProject.Domain.Entities; using YourProject.Domain.Interfaces; using YourProject.Logging; using Attachment = System.Net.Mail.Attachment; using EmailAttachment = YourProject.Domain.Entities.EmailAttachment; namespace EmailWebApi.Controller { public class MailController : ApiController { private readonly IEmail _emailService; public static int ApiRetry; public static string MailSmtpHost = ConfigurationManager.AppSettings["MailSmtpHost"]; public static string MailSmtpHost2 = ConfigurationManager.AppSettings["MailSmtpHost2"]; public static int MailSmtpPort = Convert.ToInt32(ConfigurationManager.AppSettings["MailSmtpPort"]); public static bool MailEnableSsl = true; private static string baseAddress = "EmailWebApi.Controller.MailController"; public MailController(IEmail emailService) { #region Write Log var dtEntry = DateTime.Now; var address = baseAddress + ".MailController(IEmail emailService)"; var dic = LogBusiness.GetDictionary(); dic.Add(LogFieldName.FullyQualifiedFunctionName, address); var dicParams = LogBusiness.GetDictionary(); dicParams.Add(LogFieldName.Token, dicParams); LogBusiness.CustomLog("AnonymousUser", LogEvent.MethodStart, dic, dicParams); #endregion try { _emailService = emailService; } catch (Exception ex) { #region Write Log dic = LogBusiness.GetDictionary(); dic.Add(LogFieldName.FullyQualifiedFunctionName, baseAddress); dic.Add(LogFieldName.ErrorMessage, ex.Message); dic.Add(LogFieldName.StackTrace, ex.StackTrace); dic.Add(LogFieldName.TimeElapsed, ((int)(DateTime.Now - dtEntry).TotalMilliseconds).ToString()); LogBusiness.CustomLog("EMail informations could not be loaded to MailAPI possibly from unexpected error", LogEvent.ErrorEvent, dic, dicParams); #endregion } } [HttpPost] [Route("api/mail/sendemailasync")] public async void SendEMailAsync([FromBody]EMailModel model) { await Task.Run(() => { if (model == null) return; #region Write Log var dtEntry = DateTime.Now; var address = baseAddress + ".SendEMail([FromBody]EMailModel model)"; var dic = LogBusiness.GetDictionary(); dic.Add(LogFieldName.FullyQualifiedFunctionName, address); var dicParams = LogBusiness.GetDictionary(); dicParams.Add(LogFieldName.Token, dicParams); LogBusiness.CustomLog(model.From, LogEvent.MethodStart, dic, dicParams); #endregion start: using (var smtp = new SmtpClient(MailSmtpHost)) { using (var message = new MailMessage()) { smtp.Credentials = new NetworkCredential(); smtp.Host = MailSmtpHost; smtp.Port = MailSmtpPort; smtp.DeliveryMethod = SmtpDeliveryMethod.Network; smtp.UseDefaultCredentials = false; message.IsBodyHtml = true; if (model.Retry == 0) { try { if (File.Exists(@"/Resources/yourMailPic.gif")) { message.AlternateViews.Add(CreateEmbeddedImage("/Resources/yourMailPic.gif")); } if (!string.IsNullOrEmpty(model.From)) { var fromList = model.From.Split('&'); message.From = new MailAddress(fromList[0], fromList[1]); } if (!string.IsNullOrEmpty(model.Subject)) message.Subject = model.Subject; if (!string.IsNullOrEmpty(model.Body)) message.Body = model.Body; if (!string.IsNullOrEmpty(model.To)) { var toList = model.To.Split(';'); foreach (var toRaw in toList) { var toRawList = toRaw.Split('&'); var addr = new MailAddress(toRawList[0], toRawList[1]); message.To.Add(addr); } } //CC's if (!string.IsNullOrEmpty(model.Cc)) { var ccMails = model.Cc.Split(';').ToArray(); foreach (var ccEmail in ccMails) { var ccRawList = ccEmail.Split('&'); var ccaddr = new MailAddress(ccRawList[0], ccRawList[1]); message.CC.Add(ccaddr); } } //BCC's if (!string.IsNullOrEmpty(model.Bcc)) { var bccMails = model.Bcc.Split(';').ToArray(); foreach (var bccEmail in bccMails) { var bccRawList = bccEmail.Split('&'); var bccaddr = new MailAddress(bccRawList[0], bccRawList[1]); message.Bcc.Add(bccaddr); } } //Attachment's if (model.EmailAttachments.Count > 0) { foreach (var attachment in model.EmailAttachments) { var attachmentMetaData = new Attachment(new MemoryStream(attachment.File), attachment.FileName, MediaTypeNames.Application.Octet); message.Attachments.Add(attachmentMetaData); } } model.SentDate = DateTime.Now; var mail = new Email { Subject = model.Subject, Bcc = model.Bcc, Cc = model.Cc, Body = model.Body, From = model.From, To = model.To, SmtpServer = MailSmtpHost }; foreach (var attachment in model.EmailAttachments) { var attach = new EmailAttachment { File = attachment.File, FileName = attachment.FileName }; mail.EmailAttachments.Add(attach); } _emailService.Add(mail); _emailService.Save(); var savePkId = mail.Id; var updateEmail = _emailService.GetAll().FirstOrDefault(x => x.Id == savePkId); try { smtp.Send(message); if (updateEmail == null) return; updateEmail.IsSent = true; updateEmail.SentDate = DateTime.Now; _emailService.Update(updateEmail); _emailService.Save(); } catch (Exception e) { if (updateEmail != null) { updateEmail.Exception = e.InnerException == null ? e.Message : e.Message + " --> " + e.InnerException.Message; updateEmail.LastTryDate = DateTime.Now; updateEmail.Retry = updateEmail.Retry++; _emailService.Update(updateEmail); _emailService.Save(); } } } catch (Exception ex) { #region Write Log dic = LogBusiness.GetDictionary(); dic.Add(LogFieldName.FullyQualifiedFunctionName, address); dic.Add(LogFieldName.ErrorMessage, ex.Message); dic.Add(LogFieldName.StackTrace, ex.StackTrace); LogBusiness.CustomLog(model.From, LogEvent.ErrorEvent, dic, dicParams); MailSmtpHost = MailSmtpHost2; goto start; #endregion } finally { #region Write Log dic = LogBusiness.GetDictionary(); dic.Add(LogFieldName.FullyQualifiedFunctionName, address); dic.Add(LogFieldName.TimeElapsed, ((int)(DateTime.Now - dtEntry).TotalMilliseconds).ToString()); LogBusiness.CustomLog(model.From, LogEvent.MethodEnd, dic, dicParams); #endregion } } else { try { if (!string.IsNullOrEmpty(model.From)) { var fromList = model.From.Split('&'); message.From = new MailAddress(fromList[0], fromList[1]); } if (!string.IsNullOrEmpty(model.Subject)) { message.Subject = model.Subject; } if (!string.IsNullOrEmpty(model.Body)) { message.Body = model.Body; } if (!string.IsNullOrEmpty(model.To)) { var toList = model.To.Split(';'); foreach (var toRaw in toList) { var toRawList = toRaw.Split('&'); var addr = new MailAddress(toRawList[0], toRawList[1]); message.To.Add(addr); } } //CC's if (!string.IsNullOrEmpty(model.Cc)) { var ccMails = model.Cc.Split(';').ToArray(); foreach (var ccEmail in ccMails) { var ccRawList = ccEmail.Split('&'); var ccaddr = new MailAddress(ccRawList[0], ccRawList[1]); message.CC.Add(ccaddr); } } //BCC's if (!string.IsNullOrEmpty(model.Bcc)) { var bccMails = model.Bcc.Split(';').ToArray(); foreach (var bccEmail in bccMails) { var bccRawList = bccEmail.Split('&'); var bccaddr = new MailAddress(bccRawList[0], bccRawList[1]); message.Bcc.Add(bccaddr); } } if (model.EmailAttachments.Count > 0) { foreach (var attachment in model.EmailAttachments) { var attachmentMetaData = new Attachment(new MemoryStream(attachment.File), attachment.FileName, MediaTypeNames.Application.Octet); message.Attachments.Add(attachmentMetaData); } } var updateEmail = _emailService.GetAll().FirstOrDefault(x => x.Id == model.Id); start2: try { smtp.Send(message); if (updateEmail == null) return; updateEmail.SmtpServer = smtp.Host; updateEmail.Retry = model.Retry; // WindowsSerive deneme sayısını artırıyor. updateEmail.IsSent = true; updateEmail.SentDate = DateTime.Now; updateEmail.Exception = "Last Exception was :" + model.Exception; updateEmail.LastTryDate = model.LastTryDate; _emailService.Update(updateEmail); _emailService.Save(); } catch (Exception e) { if (updateEmail != null) { updateEmail.SmtpServer = smtp.Host; updateEmail.Exception = e.InnerException == null ? e.Message : e.Message + " --> " + e.InnerException.Message; updateEmail.LastTryDate = DateTime.Now; updateEmail.Retry = model.Retry; _emailService.Update(updateEmail); _emailService.Save(); } smtp.Host = MailSmtpHost2; goto start2; } } catch (Exception ex) { #region Write Log dic = LogBusiness.GetDictionary(); dic.Add(LogFieldName.FullyQualifiedFunctionName, address); dic.Add(LogFieldName.ErrorMessage, ex.Message); dic.Add(LogFieldName.StackTrace, ex.StackTrace); LogBusiness.CustomLog(model.From, LogEvent.ErrorEvent, dic, dicParams); #endregion } finally { #region Write Log dic = LogBusiness.GetDictionary(); dic.Add(LogFieldName.FullyQualifiedFunctionName, address); dic.Add(LogFieldName.TimeElapsed, ((int)(DateTime.Now - dtEntry).TotalMilliseconds).ToString()); LogBusiness.CustomLog(model.From, LogEvent.MethodEnd, dic, dicParams); #endregion } } } } }); } [HttpPost] [Route("api/mail/sendemail")] public void SendEMail([FromBody]EMailModel model) { if (model == null) return; #region Write Log var dtEntry = DateTime.Now; var address = baseAddress + ".SendEMail([FromBody]EMailModel model)"; var dic = LogBusiness.GetDictionary(); dic.Add(LogFieldName.FullyQualifiedFunctionName, address); var dicParams = LogBusiness.GetDictionary(); dicParams.Add(LogFieldName.Token, dicParams); LogBusiness.CustomLog(model.From, LogEvent.MethodStart, dic, dicParams); #endregion start: using (var smtp = new SmtpClient(MailSmtpHost)) { using (var message = new MailMessage()) { smtp.Credentials = new NetworkCredential(); smtp.Host = MailSmtpHost; smtp.Port = MailSmtpPort; smtp.DeliveryMethod = SmtpDeliveryMethod.Network; smtp.UseDefaultCredentials = false; message.IsBodyHtml = true; if (model.Retry == 0) { try { var list = new List<MailAddress>(); if (!string.IsNullOrEmpty(model.From)) { var fromList = model.From.Split('&'); var mailFromList = new MailAddress(fromList[0], fromList[1]); message.From = mailFromList; list.Add(mailFromList); } if (!string.IsNullOrEmpty(model.Subject)) message.Subject = model.Subject; if (!string.IsNullOrEmpty(model.To)) { var toList = model.To.Split(';'); foreach (var toRaw in toList) { var toRawList = toRaw.Split('&'); var mailToList = new MailAddress(toRawList[0], toRawList[1]); var addr = mailToList; message.To.Add(addr); list.Add(mailToList); } } //CC 's if (!string.IsNullOrEmpty(model.Cc)) { var ccMails = model.Cc.Split(';').ToArray(); foreach (var ccEmail in ccMails) { var ccRawList = ccEmail.Split('&'); var mailCcList = new MailAddress(ccRawList[0], ccRawList[1]); var ccaddr = mailCcList; message.CC.Add(ccaddr); list.Add(mailCcList); } } //BCC 's if (!string.IsNullOrEmpty(model.Bcc)) { var bccMails = model.Bcc.Split(';').ToArray(); foreach (var bccEmail in bccMails) { var bccRawList = bccEmail.Split('&'); var mailBccList = new MailAddress(bccRawList[0], bccRawList[1]); var bccaddr = mailBccList; message.Bcc.Add(bccaddr); list.Add(mailBccList); } } EmailTemplate tempData = new EmailTemplate(list); if (!string.IsNullOrEmpty(model.Body)) message.CreateHtmlBody(list); else message.CreateHtmlBody(tempData); //Attachment 's if (model.EmailAttachments.Count > 0) { foreach (var attachment in model.EmailAttachments) { var attachmentMetaData = new Attachment(new MemoryStream(attachment.File), attachment.FileName, MediaTypeNames.Application.Octet); message.Attachments.Add(attachmentMetaData); } } model.SentDate = DateTime.Now; var mail = new Email { Subject = model.Subject, Bcc = model.Bcc, Cc = model.Cc, Body = model.Body, From = model.From, To = model.To, SmtpServer = MailSmtpHost }; foreach (var attachment in model.EmailAttachments) { var attach = new EmailAttachment { File = attachment.File, FileName = attachment.FileName }; mail.EmailAttachments.Add(attach); } _emailService.Add(mail); _emailService.Save(); var savePkId = mail.Id; var updateEmail = _emailService.GetAll().FirstOrDefault(x => x.Id == savePkId); try { smtp.Send(message); if (updateEmail == null) return; updateEmail.IsSent = true; updateEmail.SentDate = DateTime.Now; _emailService.Update(updateEmail); _emailService.Save(); } catch (Exception e) { if (updateEmail != null) { updateEmail.Exception = e.InnerException == null ? e.Message : e.Message + " --> " + e.InnerException.Message; updateEmail.LastTryDate = DateTime.Now; updateEmail.Retry = updateEmail.Retry++; _emailService.Update(updateEmail); _emailService.Save(); } } } catch (Exception ex) { #region Write Log dic = LogBusiness.GetDictionary(); dic.Add(LogFieldName.FullyQualifiedFunctionName, address); dic.Add(LogFieldName.ErrorMessage, ex.Message); dic.Add(LogFieldName.StackTrace, ex.StackTrace); LogBusiness.CustomLog(model.From, LogEvent.ErrorEvent, dic, dicParams); ApiRetry++; MailSmtpHost = MailSmtpHost2; if (ApiRetry<5) goto start; ApiRetry = 0; #endregion } finally { #region Write Log dic = LogBusiness.GetDictionary(); dic.Add(LogFieldName.FullyQualifiedFunctionName, address); dic.Add(LogFieldName.TimeElapsed, ((int)(DateTime.Now - dtEntry).TotalMilliseconds).ToString()); LogBusiness.CustomLog(model.From, LogEvent.MethodEnd, dic, dicParams); #endregion } } else { try { if (!string.IsNullOrEmpty(model.From)) { var fromList = model.From.Split('&'); message.From = new MailAddress(fromList[0], fromList[1]); } if (!string.IsNullOrEmpty(model.Subject)) { message.Subject = model.Subject; } if (!string.IsNullOrEmpty(model.Body)) { message.Body = model.Body; } if (!string.IsNullOrEmpty(model.To)) { var toList = model.To.Split(';'); foreach (var toRaw in toList) { var toRawList = toRaw.Split('&'); var addr = new MailAddress(toRawList[0], toRawList[1]); message.To.Add(addr); } } //CC 's if (!string.IsNullOrEmpty(model.Cc)) { var ccMails = model.Cc.Split(';').ToArray(); foreach (var ccEmail in ccMails) { var ccRawList = ccEmail.Split('&'); var ccaddr = new MailAddress(ccRawList[0], ccRawList[1]); message.CC.Add(ccaddr); } } //BCC 's if (!string.IsNullOrEmpty(model.Bcc)) { var bccMails = model.Bcc.Split(';').ToArray(); foreach (var bccEmail in bccMails) { var bccRawList = bccEmail.Split('&'); var bccaddr = new MailAddress(bccRawList[0], bccRawList[1]); message.Bcc.Add(bccaddr); } } if (model.EmailAttachments.Count > 0) { foreach (var attachment in model.EmailAttachments) { var attachmentMetaData = new Attachment(new MemoryStream(attachment.File), attachment.FileName, MediaTypeNames.Application.Octet); message.Attachments.Add(attachmentMetaData); } } var updateEmail = _emailService.GetAll().FirstOrDefault(x => x.Id == model.Id); start2: try { smtp.Send(message); if (updateEmail == null) return; updateEmail.SmtpServer = smtp.Host; updateEmail.Retry = model.Retry; updateEmail.IsSent = true; updateEmail.Exception = "Last Exception was :" + model.Exception; updateEmail.SentDate = DateTime.Now; updateEmail.LastTryDate = model.LastTryDate; _emailService.Update(updateEmail); _emailService.Save(); } catch (Exception e) { if (updateEmail != null) { updateEmail.SmtpServer = smtp.Host; updateEmail.Exception = e.InnerException == null ? e.Message : e.Message + " --> " + e.InnerException.Message; updateEmail.LastTryDate = model.LastTryDate; updateEmail.Retry = model.Retry; _emailService.Update(updateEmail); _emailService.Save(); } smtp.Host = MailSmtpHost2; goto start2; } } catch (Exception ex) { #region Write Log dic = LogBusiness.GetDictionary(); dic.Add(LogFieldName.FullyQualifiedFunctionName, address); dic.Add(LogFieldName.ErrorMessage, ex.Message); dic.Add(LogFieldName.StackTrace, ex.StackTrace); LogBusiness.CustomLog(model.From, LogEvent.ErrorEvent, dic, dicParams); #endregion } finally { #region Write Log dic = LogBusiness.GetDictionary(); dic.Add(LogFieldName.FullyQualifiedFunctionName, address); dic.Add(LogFieldName.TimeElapsed, ((int)(DateTime.Now - dtEntry).TotalMilliseconds).ToString()); LogBusiness.CustomLog(model.From, LogEvent.MethodEnd, dic, dicParams); #endregion } } } } } private static AlternateView CreateEmbeddedImage(string filePath) { var hiddenImage = new LinkedResource(filePath) { ContentId = Guid.NewGuid().ToString() }; var htmlBody = @"<img src='cid:" + hiddenImage + @"'/>"; var alternateView = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html); alternateView.LinkedResources.Add(hiddenImage); return alternateView; } } } <file_sep>/EmailWebApi/Model/EmailAttachment.cs namespace EmailWebApi.Model { public class EmailAttachment { public int EmailId { get; set; } public string FileName { get; set; } public byte[] File { get; set; } } }<file_sep>/README.md # E-Mail-Web-Api-Windows-Service<file_sep>/EmailWindowsService/Model/EmailAttachmentViewModel.cs namespace EmailWindowsService.Model { public class EMailAttachmentViewModel { public int EmailId { get; set; } public string FileName { get; set; } public byte[] File { get; set; } } } <file_sep>/EmailWindowsService/EmailWindowsService.cs using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.ServiceProcess; using System.Threading; using System.Threading.Tasks; using System.Timers; using System.Web.Http; using EmailWindowsService.Model; using YourProjectName.DataServices; using YourProjectName.Domain.Entities; using YourProjectName.Domain.Interfaces; using YourProjectName.Infrastructure; using YourProjectName.Logging; using Newtonsoft.Json; using Newtonsoft.Json.Bson; using Timer = System.Timers.Timer; namespace EmailWindowsService { public delegate Task DontStopAsync(); public partial class EmailWindowsService : ServiceBase { public static readonly YourProjectNameDbContext Db = new YourProjectNameDbContext(); public readonly IEmail EmailService = new EmailService(Db); public readonly IEmailAttachment EmailAttachmentService = new EmailAttachmentService(Db); private readonly int _timerInterval = int.Parse(ConfigurationManager.AppSettings["timerInterval"]); private readonly int _retryLimitation = int.Parse(ConfigurationManager.AppSettings["retryLimitation"]); private readonly string _apiUrl = ConfigurationManager.AppSettings["apiUrl"]; private readonly Timer _timer = new Timer(); private List<Email> _emails = new List<Email>(); private List<EmailAttachment> _emailAttachments = new List<EmailAttachment>(); private const string BaseAddress = "EmailWebApi.Controllers.MailController"; private readonly CancellationTokenSource _cts = new CancellationTokenSource(); private readonly CancellationToken _cancellationToken; public EmailWindowsService() { InitializeComponent(); #region Write Log DateTime dtEntry = DateTime.Now; const string address = BaseAddress + ".MailController(IEmail emailService)"; var dic = LogBusiness.GetDictionary(); dic.Add(LogFieldName.FullyQualifiedFunctionName, address); var dicParams = LogBusiness.GetDictionary(); dicParams.Add(LogFieldName.Token, dicParams); dic.Add(LogFieldName.TimeElapsed, ((int)(DateTime.Now - dtEntry).TotalMilliseconds).ToString()); LogBusiness.CustomLog("AnonymousUser", LogEvent.MethodStart, dic, dicParams); _cancellationToken = _cts.Token; #endregion } public void DebugStart(bool immediate) { OnStart(immediate ? new[] { "immediate" } : null); } protected override void OnStart(string[] args) { _timer.Enabled = true; _timer.Interval = _timerInterval; _timer.Elapsed += _timer_Elapsed; if (args == null || !args.Contains("immediate")) return; DontStopAsync dtAsync = WorkerAsync; Task.Factory.StartNew(dtAsync.Invoke, _cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Current) .ConfigureAwait(false); } protected override void OnStop() { _timer.Stop(); _timer.Dispose(); } private void _timer_Elapsed(object sender, ElapsedEventArgs e) { DontStopAsync dtAsync = WorkerAsync; Task.Factory.StartNew(dtAsync.Invoke, _cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Current) .ConfigureAwait(false); } [HttpPost] private async Task WorkerAsync() { _timer.Stop(); string fromMail = ""; try { _emails = EmailService.GetAll().Where(x => !x.IsSent).OrderBy(x => x.Id).ToList(); if (_emails.Count == 0){ _timer.Start(); return;} foreach (var email in _emails) { using (var client = new HttpClient()) { client.BaseAddress = new Uri(_apiUrl); using (var stream = new MemoryStream()) using (var bson = new BsonWriter(stream)) { var jsonSerializer = new JsonSerializer(); fromMail = email.From; _emailAttachments = EmailAttachmentService.GetAllNoTracking().Where(x => x.EmailId == email.Id).ToList(); var attachments = _emailAttachments.Select(attachment => new EMailAttachmentViewModel { File = attachment.File, FileName = attachment.FileName, EmailId = attachment.EmailId }).ToList(); if (email.Retry >= _retryLimitation) continue; var willBeSentAgainEmail = new EMailViewModel { Id = email.Id, From = email.From, To = email.To, Subject = email.Subject, Body = email.Body, Bcc = email.Bcc, Cc = email.Cc, Exception = email.Exception, Retry = ++email.Retry, SmtpServer = email.SmtpServer, IsRead = false, IsSent = false, LastTryDate = DateTime.Now, EmailAttachments = attachments }; jsonSerializer.Serialize(bson, willBeSentAgainEmail); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/bson")); var byteArrayContent = new ByteArrayContent(stream.ToArray()); byteArrayContent.Headers.ContentType = new MediaTypeHeaderValue("application/bson"); await client?.PostAsync("api/mail/sendemailasync", byteArrayContent, _cancellationToken); } } } _timer.Start(); } catch (Exception ex) { _timer.Start(); #region Write Log string address = BaseAddress + ".MailController(IEmail emailService)"; var dic = LogBusiness.GetDictionary(); dic.Add(LogFieldName.FullyQualifiedFunctionName, address); var dicParams = LogBusiness.GetDictionary(); dicParams.Add(LogFieldName.Token, dicParams); dic = LogBusiness.GetDictionary(); dic.Add(LogFieldName.FullyQualifiedFunctionName, address); dic.Add(LogFieldName.ErrorMessage, ex.Message); dic.Add(LogFieldName.StackTrace, ex.StackTrace); LogBusiness.CustomLog(fromMail, LogEvent.ErrorEvent, dic, dicParams); #endregion } _timer.Start(); } } }
2621741514663c782d2cfac341d9db1eafe281b7
[ "Markdown", "C#" ]
7
C#
erisonliang/E-Mail-Web-Api-Windows-Service
ec8032e83e1db25dfb298d466acebd4c57262ee6
f3bae4efc9f083049fe2a440f9dfe3b8ec568640