branch_name
stringclasses
22 values
content
stringlengths
18
81.8M
directory_id
stringlengths
40
40
languages
sequence
num_files
int64
1
7.38k
repo_language
stringlengths
1
23
repo_name
stringlengths
7
101
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>xneng0102/ESCI520FAST<file_sep>/doc/data.tex % data processing \section{Data processing} <file_sep>/doc/tmatch.tex % template \section{Template matching}
d39b83d4af48f35b9ec3aebec3f9aaa6aa882453
[ "TeX" ]
2
TeX
xneng0102/ESCI520FAST
af1b583bbe6cb4840ac925203011a0291b62138a
b4340289708236f78f74a7203dbd126fd109452c
refs/heads/master
<file_sep>import React, { Component } from 'react' export default class Grades extends Component { render() { return ( <div className="card-body"> Setting Up Grades Component </div> ) } } <file_sep>import React from 'react'; import { BrowserRouter as Router } from 'react-router-dom'; import Navbar from './Component/Layout/Navbar'; import Container from './Component/Layout/Container'; import Sidebars from './Component/Layout/Sidebar'; import Footer from './Component/Layout/Footer'; function App() { return ( <Router> <Sidebars /> <div className="main-content"> <Navbar /> <Container /> <Footer /> </div> </Router> ); } export default App; <file_sep>import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import { navbarAction } from '../../Action/assignmentAction'; import { connect } from 'react-redux'; class Sidebars extends Component { state = { menu: [], active: 'dashboard', view: null }; handleNavbar = e => { if (this.state.menu.includes(e.target.id)) { var index = this.state.menu.indexOf(e.target.id); this.state.menu.splice(index, 1); this.setState({ ...this.state.menu, active: e.target.id }); } else { this.setState({ menu: [...this.state.menu, e.target.id], active: e.target.id }); } if (!(e.target.id === 'dash_drop' || e.target.id === 'stud_drop')) { this.props.navbarAction(e.target.id); this.setState({ view: false }); } } render() { return ( <> <nav className="navbar navbar-vertical fixed-left navbar-expand-md navbar-light bg-white" id="sidenav-main"> <div className="container-fluid"> <button className="navbar-toggler" onClick={() => this.setState({ view: true })} type="button" data-toggle="collapse" data-target="#sidenav-collapse-main" aria-controls="sidenav-main" aria-expanded="false" aria-label="Toggle navigation"> <span className="navbar-toggler-icon" /> </button> <Link to='/' className="navbar-brand pt-0"> <img onClick={this.handleNavbar} id='dashboard' src="image/canyon.png" className="navbar-brand-img" alt="..." /> </Link> <div className={this.state.view ? "collapse navbar-collapse show" : "collapse navbar-collapse"} id="sidenav-collapse-main"> <div className="navbar-collapse-header d-md-none"> <div className="row"> <div className="col-6 collapse-brand"> </div> <div className="col-6 collapse-close"> <button type="button" onClick={() => this.setState({ view: false })} className="navbar-toggler" data-toggle="collapse" data-target="#sidenav-collapse-main" aria-controls="sidenav-main" aria-expanded="false" aria-label="Toggle sidenav"> <span /> <span /> </button> </div> </div> </div> <ul className="navbar-nav"> <li className="nav-item active "> <div onClick={this.handleNavbar} id='dash_drop' className={this.state.active === 'dash_drop' ? "nav-link active collapsed profileBar" : "nav-link profileBar"} data-toggle="collapse" aria-expanded={this.state.active === 'dash_drop' ? "true" : "false"}> <i className="fa fa-home" /> Home<i className="fa fa-caret-down caret-style" /> </div> <div id="collapseOne" className={this.state.menu.includes('dash_drop') ? "collapse show" : "collapsing"} > <ul className="list-unstyled text-center"> <li> <Link to='/' onClick={this.handleNavbar} id='dashboard 1' className={this.state.active === 'dashboard 1' ? "nav-link active" : "nav-link"}> <i className="fa fa-home" /> Home 1</Link> </li> <li> <Link to='/home_2' onClick={this.handleNavbar} id='dashboard 2' className={this.state.active === 'dashboard 2' ? "nav-link active" : "nav-link"}> <i className="fa fa-home" /> Home 2</Link> </li> <li> <Link to='/home_3' onClick={this.handleNavbar} id='dashboard 3' className={this.state.active === 'dashboard 3' ? "nav-link active" : "nav-link"}> <i className="fa fa-home" /> Home 3</Link> </li> </ul> </div> </li> <li className="nav-item"> <div onClick={this.handleNavbar} id='stud_drop' className={this.state.active === 'stud_drop' ? "nav-link active collapsed profileBar" : "nav-link collapsed profileBar"} data-toggle="collapse" href="#collapse2"> <i className="fa fa-user" /> Student Registration<i className="fa fa-caret-down caret-style" /> </div> <div id="collapse2" className={this.state.menu.includes('stud_drop') ? "collapse show" : "collapsing"}> <ul className="list-unstyled text-center"> <li> <Link to='/student_1' onClick={this.handleNavbar} id='student registration 1' className={this.state.active === 'student registration 1' ? "nav-link active" : "nav-link"}> <i className="fa fa-user" /> Registration 1</Link> </li> <li> <Link to='/student_2' onClick={this.handleNavbar} id='student registration 2' className={this.state.active === 'student registration 2' ? "nav-link active" : "nav-link"}> <i className="fa fa-user" /> Registration 2</Link> </li> <li> <Link to='/student_3' onClick={this.handleNavbar} id='student registration 3' className={this.state.active === 'student registration 3' ? "nav-link active" : "nav-link"}> <i className="fa fa-user" /> Registration 3</Link> </li> </ul> </div> </li> <li className="nav-item"> <Link to='/assignment_setup' onClick={this.handleNavbar} id='assignments' className={this.state.active === 'assignments' ? "nav-link active" : "nav-link"}> <i className="fa fa-mobile" /> Assignments Setup </Link> </li> <li className="nav-item"> <Link to='/payment' onClick={this.handleNavbar} id='payment batch' className={this.state.active === 'payment batch' ? "nav-link active" : "nav-link"}> <i className="fa fa-money" /> Payment Batch </Link> </li> <li className="nav-item"> <Link to='/receipt' onClick={this.handleNavbar} id='receipt and refunds' className={this.state.active === 'receipt and refunds' ? "nav-link active" : "nav-link"}> <i className="fa fa-thumbs-up" /> Receipts and Refunds </Link> </li> <li className="nav-item"> <Link to='/accounts' onClick={this.handleNavbar} id='student accounts' className={this.state.active === 'student accounts' ? "nav-link active" : "nav-link"}> <i className="fa fa-lock" /> Student Accounts </Link> </li> <li className="nav-item"> <Link to='/assignment_data' onClick={this.handleNavbar} id='assignment data entry' className={this.state.active === 'assignment data entry' ? "nav-link active" : "nav-link"}> <i className="fa fa-book" /> Assignments Data Entry </Link> </li> <li className="nav-item"> <Link to='/course' onClick={this.handleNavbar} id='course grades' className={this.state.active === 'course grades' ? "nav-link active" : "nav-link"}> <i className="fa fa-percent" /> Course Grades </Link> </li> <li className="nav-item"> <Link to='/transcripts' onClick={this.handleNavbar} id='printing of transcripts' className={this.state.active === 'printing of transcripts' ? "nav-link active" : "nav-link"}> <i className="fa fa-print" /> Printing of Transcripts </Link> </li> <li className="nav-item"> <Link to='/certificates' onClick={this.handleNavbar} id='printing of certificates' className={this.state.active === 'printing of certificates' ? "nav-link active" : "nav-link"}> <i className="fa fa-print" /> Printing of Certificates </Link> </li> <li className="nav-item"> <Link to='/id_cards' onClick={this.handleNavbar} id='student id cards' className={this.state.active === 'student id cards' ? "nav-link active" : "nav-link"}> <i className="fa fa-id-card" /> Student ID Cards </Link> </li> <li className="nav-item"> <Link to='/entries' onClick={this.handleNavbar} id='account general entries' className={this.state.active === 'account general entries' ? "nav-link active" : "nav-link"}> <i className="fa fa-pencil" /> Account General Entries </Link> </li> <li className="nav-item"> <Link to='/user' onClick={this.handleNavbar} id='user maintanance' className={this.state.active === 'user maintanance' ? "nav-link active" : "nav-link"}> <i className="fa fa-wrench" /> User Maintanance </Link> </li> <li className="nav-item"> <Link to='/course_detail' onClick={this.handleNavbar} id='setting up of course detail' className={this.state.active === 'setting up of course detail' ? "nav-link active" : "nav-link"}> <i className="fa fa-thumbs-up" /> Setting Up of Course Detail </Link> </li> <li className="nav-item"> <Link to='/grades' onClick={this.handleNavbar} id='setting up grades' className={this.state.active === 'setting up grades' ? "nav-link active" : "nav-link"}> <i className="fa fa-pencil" /> Setting up Grades </Link> </li> </ul> </div> </div> </nav> </> ) } } const mapDispatchToProps = dispatch => ({ navbarAction: name => dispatch(navbarAction(name)) }) export default connect(null, mapDispatchToProps)(Sidebars);<file_sep>import React, { Component } from 'react' import { connect } from 'react-redux' class Header extends Component { capital = (string) => { return string.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); }); } render() { // console.log(this.props) return ( <div> <div className="row "> <div className="col"> <h2 className="mb-1">{this.capital(this.props.navbar)} Setup</h2> <h6 className="text-uppercase text-muted ls-1 mb-0">Check for {this.props.navbar} Setup</h6> </div> </div> </div> ) } } const mapStateToProps = state => ({ navbar: state.navbar.navbar }); export default connect(mapStateToProps, null)(Header);<file_sep>import React, { Component } from 'react' export default class Home1 extends Component { render() { return ( <div className="card-body"> Dashboard Home 1 Component </div> ) } } <file_sep>import React, { Component } from 'react'; import Add from './Add'; import List from './List'; export default class Assignment extends Component { state = { load: false, submit: false, error: false, duedate: new Date() }; render() { return ( <div> <div className="card-body"> <Add /> <List /> </div> </div> ) } } <file_sep>import React, { Component } from 'react' export default class User extends Component { render() { return ( <div className="card-body"> User Maintanance Component </div> ) } } <file_sep>import React, { Component } from 'react' export default class Home3 extends Component { render() { return ( <div className="card-body"> Dashboard Home 3 Component </div> ) } } <file_sep>import React, { Component } from 'react' export default class Student2 extends Component { render() { return ( <div className="card-body"> Student Register 2 Component </div> ) } } <file_sep>import React, { Component } from 'react' import axios from 'axios'; import moment from 'moment'; import { connect } from 'react-redux'; import { addassignment } from '../../../Action/assignmentAction' class List extends Component { state = { data: null, deleteModal: false, id: null, deleted: false, delLoad: null } componentDidMount() { axios.get('http://167.172.242.107:8282/ps/assesments').then((res) => { if (res.status === 200) { this.props.addassignment(res.data); this.setState({ data: res.data }); } }); } deleteHandle = e => { this.setState({ deleteModal: true, id: e.target.id }); } deleteRecord = e => { e.preventDefault(); this.setState({ deleteModal: false, delLoad: true }) axios.delete('http://172.16.58.3:8282/ps/assesments/' + this.state.id).then((res) => { if (res.status === 200) { this.props.addassignment(res.data); this.setState({ deleted: true, delLoad: false }); setTimeout(() => { this.setState({ deleted: false }); }, 4000); } }); } render() { let { list } = this.props; let fullList = list ? list.map((value, i) => { return (<tr key={i}> <td>{i + 1}</td> <td>{value.course}</td> <td>{value.weight}</td> <td>{value.totalmarks}</td> <td>{moment(value.dueDate).format('DD/MM/YYYY')}</td> <td>{this.state.id === value.assId ? <button onClick={this.deleteHandle} id={value.assId} type="button" className="btn btn-dark btn-sm"><i className="fa fa-trash" /> Deleting</button> : <button onClick={this.deleteHandle} id={value.assId} type="button" className="btn btn-danger btn-sm"><i className="fa fa-trash" /> Delete</button>}</td> </tr>) }) : null; return ( <div> {this.state.deleted ? <div className="alert alert-danger" role="alert"> Record Deleted...! </div> : null } <div className="row"> <div className="col-lg-12 col-md-12 mt-3"> <div className="table-responsive"> <table className="table align-items-center table-flush"> <thead className="thead-light"> <tr> <th scope="col">No:</th> <th scope="col">Assignments</th> <th scope="col">Weight</th> <th scope="col">Marks</th> <th scope="col">Due Date</th> <th scope="col">Action</th> </tr> </thead> <tbody> {fullList} </tbody> </table> </div> </div> </div> <div className="row mt-3 justify-content-center"> <div className="col-lg-3 col-md-8"> <nav aria-label="Page navigation example"> <ul className="pagination justify-content-end"> <li className="page-item disabled"> <div className="page-link" tabIndex={-1}> <i className="fa fa-angle-left" /> <span className="sr-only">Previous</span> </div> </li> <li className="page-item active"><div className="page-link profileBar" >1</div></li> <li className="page-item"><div className="page-link profileBar" >2</div></li> <li className="page-item"><div className="page-link profileBar" >3</div></li> <li className="page-item profileBar"> <div className="page-link"> <i className="fa fa-angle-right" /> <span className="sr-only">Next</span> </div> </li> </ul> </nav> </div> </div> <div id="myModal" className={this.state.deleteModal ? "modal d-block" : "modal"} tabIndex={-1} role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div className="modal-dialog"> <div className="modal-content"> <div className="modal-header"> <h3 id="myModalLabel">Are You Sure to Delete?</h3> <button type="button" onClick={() => this.setState({ deleteModal: false, id: null })} className="close" data-dismiss="modal" aria-hidden="true">×</button> </div> <div className="modal-footer"> <button onClick={() => this.setState({ deleteModal: false, id: null })} className="btn" data-dismiss="modal" aria-hidden="true">Close</button> <button onClick={this.deleteRecord} className="btn btn-danger">Delete</button> </div> </div> </div> </div> </div> ) } } const mapStateToProps = state => ({ list: state.assignmentList.list, }); const mapDispatchToProps = (dispatch) => ({ addassignment: (list) => dispatch(addassignment(list)) }); export default connect(mapStateToProps, mapDispatchToProps)(List);<file_sep>import React, { Component } from 'react' export default class Certificates extends Component { render() { return ( <div className="card-body"> Printing Of Certificates Component </div> ) } } <file_sep>import React, { Component } from 'react'; import DatePicker from "react-datepicker"; import "react-datepicker/dist/react-datepicker.css"; import axios from 'axios'; import { connect } from 'react-redux'; import { addassignment } from '../../../Action/assignmentAction'; class Add extends Component { state = { load: false, submit: false, error: false, duedate: new Date(), year: '2015', exam: '', programme: '', weight: '', marks: '', desc: '', errors: {} }; updateValue = (e) => this.setState({ [e.target.name]: e.target.value }) selectHandle = (e, { name, value }) => this.setState({ [name]: value }) handleChange = date => { this.setState({ duedate: date }); }; handleValidation() { // let fields = this.state.fields; let errors = {}; let formIsValid = true; if (!this.state.programme) { formIsValid = false; errors["programme"] = "Select Programme"; } if (!this.state.unit) { formIsValid = false; errors["unit"] = "Select Units List"; } if (!this.state.course) { formIsValid = false; errors["course"] = "Select Course List"; } if (!this.state.rego) { formIsValid = false; errors["rego"] = "Select Rego Period"; } if (!this.state.exam) { formIsValid = false; errors["exam"] = "Exam Code cannot be empty"; } if (!this.state.weight) { formIsValid = false; errors["weight"] = "Weight cannot be empty"; } if (!this.state.marks) { formIsValid = false; errors["marks"] = "Total Marks cannot be empty"; } this.setState({ errors: errors }); return formIsValid; } handleSubmit = (e) => { this.setState({ load: true }); const { course, duedate, exam, programme, unit, rego, weight, marks, desc } = this.state; if (this.handleValidation()) { axios.post('http://192.168.3.11:8282/ps/assesments', { course: course, dueDate: duedate, examcode: exam, note: desc, program: programme, semester: rego, totalmarks: marks, units: unit, weight: weight } ).then((res) => { if (res.status === 200) { this.props.addassignment(res.data); this.setState({ load: false, submit: true, duedate: new Date(), course: '', unit: '', programme: '', rego: '', year: '2015', exam: '', weight: '', marks: '', desc: '' }); setTimeout(() => { this.setState({ submit: false }); }, 4000); } }); } else { this.setState({ load: false }); } } render() { return ( <div> {this.state.submit ? <div className="alert alert-success" role="alert"> Record Created Successfully...! </div> : null } <div className="row"> <div className="col-lg-4 col-md-6"> <div className="form-group"> <label className="label-style">Select Programme</label> <select className="form-control form-control-alternative" name='programme' value={this.state.programme} onChange={this.updateValue}> <option value={null}>{null}</option> <option value='Certificate Courses'>Certificate Courses</option> <option value='CIB-Certificate in Business'>CIB-Certificate in Business</option> </select> <span className='formError'>{this.state.errors["programme"] ? this.state.errors["programme"] : null}</span> </div> </div> <div className="col-lg-4 col-md-6"> <div className="form-group"> <label className="label-style">Course List</label> <select className="form-control form-control-alternative" name='course' value={this.state.course} onChange={this.updateValue}> <option value={null}>{null}</option> <option value='CHRM - Certificate in Human Resourse Management'>CHRM - Certificate in Human Resourse Management</option> <option value='CIA - Certificate in Accounting'>CIA - Certificate in Accounting</option> </select> <span className='formError'>{this.state.errors["course"] ? this.state.errors["course"] : null}</span> </div> </div> <div className="col-lg-4 col-md-6"> <div className="form-group"> <label className="label-style">Units List</label> <select className="form-control form-control-alternative" name='unit' value={this.state.unit} onChange={this.updateValue}> <option value={null}>{null}</option> <option value='1003 - Certificate in Business'>1003 - Certificate in Business</option> <option value='1002 - Business Communication'>1002 - Business Communication</option> <option value='1012 - Business Accounting'>1012 - Business Accounting</option> </select> <span className='formError'>{this.state.errors["unit"] ? this.state.errors["unit"] : null}</span> </div> </div> <div className="col-lg-4 col-md-6"> <div className="form-group"> <label className="label-style">Rego Period</label> <select className="form-control form-control-alternative" name='rego' value={this.state.rego} onChange={this.updateValue}> <option value={null}>{null}</option> <option value='Semester 1'>Semester 1</option> <option value='Semester 2'>Semester 2</option> </select> <span className='formError'>{this.state.errors["rego"] ? this.state.errors["rego"] : null}</span> </div> </div> <div className="col-lg-2 col-md-6"> <label className="label-style">Year</label> <input type="text" name='year' onChange={this.updateValue} value={this.state.year} className="form-control form-control-alternative" placeholder='2015' /> </div> <div className="col-lg-2 col-md-6"> <label className="label-style">Course</label> <div className="mt-2">CIB</div> </div> <div className="col-lg-4 col-md-6"> <label className="label-style">Unit Code</label> <div className="mt-2">1003 - Miscrosoft Office training</div> </div> <div className="col-lg-3 col-md-6"> <label className="label-style">Exam Code</label> <input type="text" name='exam' onChange={this.updateValue} value={this.state.exam} className="form-control form-control-alternative" placeholder='' /> <span className='formError'>{this.state.errors["exam"] ? this.state.errors["exam"] : null}</span> </div> <div className="col-lg-3 col-md-6"> <label className="label-style">Weight</label> <input type="text" name='weight' onChange={this.updateValue} value={this.state.weight} className="form-control form-control-alternative" placeholder='' /> <span className='formError'>{this.state.errors["weight"] ? this.state.errors["weight"] : null}</span> </div> <div className="col-lg-3 col-md-6"> <label className="label-style">Total Marks</label> <input type="text" name='marks' onChange={this.updateValue} value={this.state.marks} className="form-control form-control-alternative" placeholder='' /> <span className='formError'>{this.state.errors["marks"] ? this.state.errors["marks"] : null}</span> </div> <div className="col-lg-3 col-md-6"> <div className="form-group"> <label className="label-style">Due Date</label><br></br> <DatePicker label='Due Date' name='duedate' className="form-control form-control-alternative" selected={this.state.duedate} onSelect={this.selectHandle} onChange={this.handleChange} /> </div> </div> <div className="col-lg-12 col-md-12"> <div className="form-group"> <label className="label-style">Description</label> <textarea type="text" name='desc' value={this.state.desc} onChange={this.updateValue} className="form-control form-control-alternative" /> </div> </div> </div> <div className="row justify-content-center mt-3 mb-4"> <div className="col-lg-12 text-center col-md-12 btn-style-bk"> {/* <a href="#" className="btn btn-primary">Add New</a> */} {this.state.load ? <button className="btn btn-primary" type="button" disabled> <span className="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Loading... </button> : <input type='submit' onClick={this.handleSubmit} value="Add New" className='btn btn-primary' /> } </div> </div> </div> ) } } // const mapStateToProps=state=>({ // list:state.assignmentList.list, // }) const mapDispatchToProps = dispatch => ({ addassignment: (list) => dispatch(addassignment(list)) }); export default connect(null, mapDispatchToProps)(Add);<file_sep>import React, { Component } from 'react'; import Assignment from '../Pages/Assingment/Assignment'; import { Route } from 'react-router-dom'; import Home1 from '../Pages/Home/Home1'; import Home2 from '../Pages/Home/Home2'; import Home3 from '../Pages/Home/Home3'; import Header from './Header'; import Student3 from '../Pages/Student Registration/Student3'; import Student2 from '../Pages/Student Registration/Student2'; import Student1 from '../Pages/Student Registration/Student1'; import Accounts from '../Pages/Others/Accounts'; import AssignmentData from '../Pages/Others/AssignmentData'; import Certificates from '../Pages/Others/Certificates'; import Course from '../Pages/Others/Course'; import CourseDetail from '../Pages/Others/CourseDetail'; import Entries from '../Pages/Others/Entries'; import Grades from '../Pages/Others/Grades'; import IDCards from '../Pages/Others/IDCards'; import Payment from '../Pages/Others/Payment'; import Receipt from '../Pages/Others/Receipt'; import Transcripts from '../Pages/Others/Transcripts'; import User from '../Pages/Others/User'; class Container extends Component { render() { return ( <div> <div className="header bg-blue-clr pb-8 pt-5 pt-md-8"> <div className="container-fluid"> <div className="header-body"> </div> </div> </div> <div className="container-fluid mt--7"> <div className="row"> <div className="col-xl-12"> <div className="card bg-secondary shadow "> <div className="card-header bg-transparent"> <Header /> </div> <Route path='/grades'><Grades /></Route> <Route path='/course_detail'><CourseDetail /></Route> <Route path='/user'><User /></Route> <Route path='/entries'><Entries /></Route> <Route path='/id_cards'><IDCards /></Route> <Route path='/certificates'><Certificates /></Route> <Route path='/transcripts'><Transcripts /></Route> <Route path='/course'><Course /></Route> <Route path='/assignment_data'><AssignmentData /></Route> <Route path='/accounts'><Accounts /></Route> <Route path='/receipt'><Receipt /></Route> <Route path='/payment'><Payment /></Route> <Route path='/assignment_setup'><Assignment /></Route> <Route path='/student_3'><Student3 /></Route> <Route path='/student_2'><Student2 /></Route> <Route path='/student_1'><Student1 /></Route> <Route path='/home_3'><Home3 /></Route> <Route path='/home_2'><Home2 /></Route> <Route exact path='/' ><Home1 /></Route> </div> </div> </div> </div> </div> ) } } export default Container;<file_sep>export const addassignment = list => ({ type: 'ASSIGNMENT_LIST', payload: list }); export const navbarAction = name => ({ type: 'NAVBAR', payload: name });<file_sep>const assignmentReducer = (state = {}, action) => { switch (action.type) { case 'ASSIGNMENT_LIST': return state = { list: action.payload }; default: return state; } } const navbarReducer = (state = { navbar: 'dashboard' }, action) => { switch (action.type) { case 'NAVBAR': return state = { navbar: action.payload }; default: return state; } } export { assignmentReducer, navbarReducer };<file_sep>import React, { Component } from 'react' export default class Home2 extends Component { render() { return ( <div className="card-body"> Dashboard Home 2 Component </div> ) } }
3b40dd10731ce8628af8b8d239c0d5f325d83feb
[ "JavaScript" ]
16
JavaScript
SV-Mahesh/canyon
7f10a757c31246d232d463b6f78878c029be0f30
2df0adf9bee1f6a7b54b337113c009cf67a49ca6
refs/heads/master
<file_sep>var express = require('express'); var app = express(); var http = require('http').Server(app); var io = require('socket.io')(http); var users = {}; //this objects array use username as index, and store each users' object. var defaultname; class SingleUserDetail { //this class is for storing a user's socket. constructor(sokt) { this.sokt = sokt; } getSocket(){ return this.sokt; } } app.use('/bower_components', express.static(__dirname + '/bower_components')); //here just include the webcomponents'path app.get('/', function(req, res){ res.sendfile('index.html'); //will load the index.html to the browser }); http.listen(3000); //set the port to 3000. io.on('connection', function(socket){ socket.on('new user', function(data, callback){ //this part will check the whether the input username is valid if (data in users){ // or user want have a default username. callback(false); } else{ let i=0; if(data === ''){ while(true){ defaultname="Guest"; defaultname+=i; if(!(defaultname in users)){ socket.nickname = defaultname; defaultname="Guest"; users[socket.nickname] = new SingleUserDetail(socket); callback(socket.nickname); socket.broadcast.emit('usercome', {user: socket.nickname}); updateNicknames(); break; } i++; } }else{ socket.nickname = data; callback(socket.nickname); socket.broadcast.emit('usercome', {user: socket.nickname}); users[socket.nickname] = new SingleUserDetail(socket); updateNicknames(); } } }); function updateNicknames(){ //send all the keys of user array, let the front-side update io.sockets.emit('usernames', Object.keys(users)); //update the users's list } socket.on('checktyping', function(data){ //if the frontside selected a user from userlist, it means a if(data.type===true){ //private message, then if the sender is typing, the receiver will display users[data.value].getSocket().emit('changetypeStatus', {type: true, value: socket.nickname}); }else{ //the "send is typing" users[data.value].getSocket().emit('changetypeStatus', {type: false, value: ' '}); } }); socket.on('send message', function(data, callback){ //check the message, send the private message; var msg = data.trim(); //trim the space from message, prevent mistyping. var ind = msg.indexOf(' '); var name = msg.substring(0, ind); msg = msg.substring(ind + 1); if(name in users){ users[name].getSocket().emit('whisper', {msg: msg, touser: name, nick: socket.nickname}); users[socket.nickname].getSocket().emit('whisper', {msg: msg, touser: name, nick: socket.nickname}); } else{ callback('Error! Enter a valid user.'); } }); socket.on('send message to all', function(data){ // send the public message; var msg = data.trim(); io.sockets.emit('new message', {msg: msg, nick: socket.nickname}); }); socket.on('disconnect', function(){ //when user is offline, delete the object is the users{} if(!socket.nickname) return; //let the rest users receive a notification delete users[socket.nickname]; socket.broadcast.emit('userleave', {user: socket.nickname}); updateNicknames(); }); }); <file_sep> describe( "Convert library", function () { it("converts litres to gallons", function () { expect(true).toEqual(true); }); });
775fc717783ef47d46ea41e823c19155a1ea5e22
[ "JavaScript" ]
2
JavaScript
conerfly/myproject
617befed0ecbb8503feca718ade1b3062f2e8aad
b423573c007a5a0b11237c49ff63f471ce0fd281
refs/heads/master
<repo_name>Fritty96/p02-OldTimeyPhoto<file_sep>/main.cpp //Author <NAME> #include <iostream> #include<string> #include<vector> #include "bitmap.h" using namespace std; int main (){ Bitmap image; vector<vector <Pixel> > bmp; Pixel rgb; bool valid; do{ string userbmp; cout << "Please enter bmp file name: ex- machupicchu.bmp " << endl; cin >> userbmp; image.open(userbmp); valid = image.isImage(); } while (valid == false); if(valid == true){ bmp= image.toPixelMatrix(); for (int row = 0; row < bmp.size(); row++){ for (int col = 0; col < bmp[row].size(); col++){ rgb = bmp[row][col]; int average = (rgb.red + rgb.blue + rgb.green)/3; rgb.red = average; rgb.green = average; rgb.blue = average; bmp[row][col] = rgb; } } image.fromPixelMatrix(bmp); image.save("oldtimey.bmp"); } return 0; }
7746f152a30288481da6ae0215e9256cb67bb03b
[ "C++" ]
1
C++
Fritty96/p02-OldTimeyPhoto
5ee3cdf14773e7e2a16f6786970733d98e94cecd
87091be5864f14330cd0f28f68530ebc621923c3
refs/heads/master
<repo_name>EdisonChen0816/ner_toolkit<file_sep>/src/bert_bilstm_crf.py # encoding=utf-8 import tensorflow as tf from src.bert import modeling, tokenization import random import numpy as np import os class BertBiLstmCrf: def __init__(self, logger, train_path, eval_path, bert_path, max_length, num_units, batch_size, rate, epoch, loss, dropout, tf_config, model_path, summary_path, tag2label=None, encoder_layer=11): self.logger = logger self.train_path = train_path self.eval_path = eval_path self.bert_path = bert_path self.max_length = max_length self.num_units = num_units self.batch_size = batch_size self.rate = rate self.epoch = epoch self.loss = loss self.dropout = dropout self.encoder_layer = encoder_layer self.tf_config = tf_config self.model_path = model_path self.summary_path = summary_path vocab_file = os.path.join(self.bert_path, 'vocab.txt') self.tokenizer = tokenization.FullTokenizer(vocab_file=vocab_file) self.predictor = None if tag2label is None: tag2label = { 'O': 0, 'B-com': 1, 'I-com': 2, 'B-pos': 3, 'I-pos': 4 } self.tag2label = tag2label self.label2tag = {} for key in self.tag2label: self.label2tag[self.tag2label[key]] = key def get_input_feature(self, data_path): ''' 获取输入数据特征 :param data_path: :return: ''' data = [] sententce = '' label = [] # label = [self.tag2label['O']] # 对应起始[cls] with open(data_path, 'r', encoding='utf-8') as f: for line in f: if '\n' == line: seq_len = len(sententce) tokens = self.tokenizer.tokenize(sententce) tokens = ['[CLS]'] + tokens[:self.max_length - 2] + ['[SEP]'] input_ids = self.tokenizer.convert_tokens_to_ids(tokens) input_mask = [1] * len(input_ids) input_ids += [0] * (self.max_length - len(input_ids)) input_mask += [0] * (self.max_length - len(input_mask)) label += [self.tag2label['O']] * (self.max_length - 2 - len(label)) data.append([input_ids, input_mask, seq_len, label]) sententce = '' label = [] # label = [self.tag2label['O']] else: word, tag = line.replace('\n', '').split('\t') sententce += word label.append(self.tag2label[tag]) return data def batch_yield(self, data, shuffle=False): ''' 产生batch数据 :param data: :param shuffle: :return: ''' if shuffle: random.shuffle(data) input_ids, input_mask, seq_lens, labels = [], [], [], [] for (input_ids_, input_mask_, seq_len_, label_) in data: if len(input_ids) == self.batch_size: yield input_ids, input_mask, np.asarray(seq_lens), np.asarray(labels) input_ids, input_mask, seq_lens, labels = [], [], [], [] input_ids.append(input_ids_) input_mask.append(input_mask_) seq_lens.append(seq_len_) labels.append(label_) if len(input_ids) != 0: yield input_ids, input_mask, np.asarray(seq_lens), np.asarray(labels) def model(self, input_ids, input_mask, seq_lens, labels): ''' 构建模型 :param input_ids: :param input_mask: :param seq_lens: :param labels: :return: ''' bert_config_file = os.path.join(self.bert_path, 'bert_config.json') bert_config = modeling.BertConfig.from_json_file(bert_config_file) bert_model = modeling.BertModel( config=bert_config, is_training=False, input_ids=input_ids, input_mask=input_mask, use_one_hot_embeddings=False) bert_embedding = bert_model.get_all_encoder_layers()[self.encoder_layer] cell_fw = tf.nn.rnn_cell.LSTMCell(self.num_units) cell_fw = tf.nn.rnn_cell.DropoutWrapper(cell_fw, output_keep_prob=1-self.dropout) cell_bw = tf.nn.rnn_cell.LSTMCell(self.num_units) cell_bw = tf.nn.rnn_cell.DropoutWrapper(cell_bw, output_keep_prob=1-self.dropout) ((rnn_fw_outputs, rnn_bw_outputs), (rnn_fw_final_state, rnn_bw_final_state)) = tf.nn.bidirectional_dynamic_rnn( cell_fw=cell_fw, cell_bw=cell_bw, inputs=bert_embedding[:, 1:-1, :], sequence_length=seq_lens, dtype=tf.float32 ) rnn_outputs = tf.add(rnn_fw_outputs, rnn_bw_outputs) logits_seq = tf.layers.dense(rnn_outputs, len(self.tag2label)) log_likelihood, transition_matrix = tf.contrib.crf.crf_log_likelihood(logits_seq, labels, seq_lens) preds_seq, crf_scores = tf.contrib.crf.crf_decode(logits_seq, transition_matrix, seq_lens) return preds_seq, log_likelihood def fit(self): ''' 训练模型 :return: ''' train_data = self.get_input_feature(self.train_path) input_ids = tf.placeholder(shape=[None, None], dtype=tf.int32, name="input_ids") input_mask = tf.placeholder(shape=[None, None], dtype=tf.int32, name="input_mask") seq_lens = tf.placeholder(tf.int32, [None], name='seq_lens') labels = tf.placeholder(tf.int32, [None, None], name='labels') preds_seq, log_likelihood = self.model(input_ids, input_mask, seq_lens, labels) init_checkpoint = os.path.join(self.bert_path, 'bert_model.ckpt') tvars = tf.trainable_variables() assignment_map, _ = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map) tf.add_to_collection('preds_seq', preds_seq) loss = -log_likelihood / tf.cast(seq_lens, tf.float32) loss = tf.reduce_mean(loss) if 'sgd' == self.loss.lower(): train_op = tf.train.GradientDescentOptimizer(self.rate).minimize(loss) elif 'adam' == self.loss.lower(): train_op = tf.train.AdamOptimizer(self.rate).minimize(loss) else: train_op = tf.train.GradientDescentOptimizer(self.rate).minimize(loss) saver = tf.train.Saver(tf.global_variables()) with tf.Session(config=self.tf_config) as sess: sess.run(tf.global_variables_initializer()) for i in range(self.epoch): for step, (input_ids_batch, input_mask_batch, seq_lens_batch, labels_batch) in enumerate(self.batch_yield(train_data)): _, curr_loss = sess.run([train_op, loss], feed_dict={input_ids: input_ids_batch, input_mask: input_mask_batch, seq_lens: seq_lens_batch, labels: labels_batch}) if step % 10 == 0: self.logger.info('epoch:%d, batch: %d, current loss: %f' % (i, step + 1, curr_loss)) saver.save(sess, self.model_path) tf.summary.FileWriter(self.summary_path, sess.graph) self.evaluate(sess, input_ids, input_mask, seq_lens, labels, preds_seq) def evaluate(self, sess, input_ids, input_mask, seq_lens, labels, preds_seq): ''' 评估模型 :param sess: :param input_ids: :param input_mask: :param seq_lens: :param labels: :param preds_seq: :return: ''' eval_data = self.get_input_feature(self.eval_path) tp_com = 0 # 正类判定为正类 fp_com = 0 # 负类判定为正类 fn_com = 0 # 正类判定为负类 tp_pos = 0 # 正类判定为正类 fp_pos = 0 # 负类判定为正类 fn_pos = 0 # 正类判定为负类 for _, (input_ids_batch, input_mask_batch, seq_lens_batch, labels_batch) in enumerate(self.batch_yield(eval_data)): preds = sess.run(preds_seq, feed_dict={input_ids: input_ids_batch, input_mask: input_mask_batch, seq_lens: seq_lens_batch, labels: labels_batch}) for i in range(len(preds)): pred = preds[i] label = labels_batch[i] true_com, true_pos = self.label2entity(label[: seq_lens_batch[i]]) pred_com, pred_pos = self.label2entity(pred[: seq_lens_batch[i]]) tp_com += len(true_com & pred_com) fp_com += len(pred_com - true_com) fn_com += len(true_com - pred_com) tp_pos += len(true_pos & pred_pos) fp_pos += len(pred_pos - true_pos) fn_pos += len(true_pos - pred_pos) recall_com = tp_com / (tp_com + fn_com) precision_com = tp_com / (tp_com + fp_com) f1_com = (2 * recall_com * precision_com) / (recall_com + precision_com) recall_pos = tp_pos / (tp_pos + fn_pos) precision_pos = tp_pos / (tp_pos + fp_pos) f1_pos = (2 * recall_pos * precision_pos) / (recall_pos + precision_pos) self.logger.info('eval company recall:' + str(recall_com) + ', eval company precision:' + str(precision_com) + ', eval company f1:' + str(f1_com) + ', eval position recall:' + str(recall_pos) + ', eval position precision:' + str(precision_pos) + ', eval position f1:' + str(f1_pos)) def label2entity(self, label): ''' 将预测结果[0, 1, 2, 2, 2, 0, 3, 4]转成(com_1_4, pos_6_7),com公司实体,1是起始位置,4是结束位置,方便统计 :param label: :return: ''' com_set = set() pos_set = set() entity = '' count = 0 while count < len(label): if 'B-com' == self.label2tag[int(label[count])]: entity += 'com_' + str(count) count += 1 while count < len(label): if 'I-com' == self.label2tag[int(label[count])] and count == len(label) - 1: entity += '_' + str(count) break if 'I-com' != self.label2tag[int(label[count])]: entity += '_' + str(count - 1) break count += 1 s = entity.split('_') if 3 == len(s) and s[1] != s[2]: com_set.add(entity) entity = '' elif 'B-pos' == self.label2tag[int(label[count])]: entity += 'pos_' + str(count) count += 1 while count < len(label): if 'I-pos' == self.label2tag[int(label[count])] and count == len(label) - 1: entity += '_' + str(count) break if 'I-pos' != self.label2tag[int(label[count])]: entity += '_' + str(count - 1) break count += 1 s = entity.split('_') if 3 == len(s) and s[1] != s[2]: pos_set.add(entity) entity = '' else: count += 1 return com_set, pos_set def load(self, path): ''' 加载模型 :param path: :return: ''' self.pred_sess = tf.Session(config=self.tf_config) saver = tf.train.import_meta_graph(path + '/model.meta') saver.restore(self.pred_sess, tf.train.latest_checkpoint(path)) graph = tf.get_default_graph() self.input_ids = graph.get_tensor_by_name('input_ids:0') self.input_mask = graph.get_tensor_by_name('input_mask:0') self.labels = graph.get_tensor_by_name('labels:0') self.seq_lens = graph.get_tensor_by_name('seq_lens:0') self.preds_seq = tf.get_collection('preds_seq') def close(self): ''' 关闭session :return: ''' self.pred_sess.close() def _predict_text_process(self, text): ''' 对输入数据预处理 :param text: :return: ''' label = [] seq_len = len(text) tokens = self.tokenizer.tokenize(text) tokens = ['[CLS]'] + tokens[:self.max_length - 2] + ['[SEP]'] input_ids = self.tokenizer.convert_tokens_to_ids(tokens) input_mask = [1] * len(input_ids) input_ids += [0] * (self.max_length - len(input_ids)) input_mask += [0] * (self.max_length - len(input_mask)) label += [self.tag2label['O']] * (self.max_length - len(label)) return np.asarray([input_ids]), np.asarray([input_mask]), np.asarray([seq_len]), np.asarray([label]) def predict(self, text): ''' 预测 :param text: string类型 :return: ''' input_ids, input_mask, seq_len, label = self._predict_text_process(text) pred, _ = self.pred_sess.run(self.preds_seq, feed_dict={self.input_ids: input_ids, self.input_mask: input_mask, self.seq_lens: seq_len, self.labels: label}) return pred<file_sep>/src/ac_match.py # encoding=utf8 """ ac自动机匹配 """ import ahocorasick from src.util import load_dir_util class ACMatch: def __init__(self, path): self.A = ahocorasick.Automaton() for item in load_dir_util.load_data_from_dir(path): if len(item) == 3: self.A.add_word(item[0], "\t".join(item)) self.A.make_automaton() def ac_match(self, q): l = [] for item in self.A.iter(q): if len(l) > 0 and l[-1].split('\t')[0] in item[1].split('\t')[0]: l[-1] = item[1] else: l.append(item[1]) d = {} for ll in l: tts = ll.split('\t') d[tts[0]] = tts + [1.0] return d if __name__ == "__main__": s = ACMatch('../../data/entity') for e in s.ac_match('上海天气怎么样'): print(e) <file_sep>/src/bert/optimization.py # encoding=utf-8 import re import tensorflow as tf from tensorflow.python.training import optimizer from tensorflow.python.framework import ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import state_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import resource_variable_ops class AdamWeightDecayOptimizer(tf.train.Optimizer): def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-6, exclude_from_weight_decay=None, name='AdamWeightDecayOptimizer'): super(AdamWeightDecayOptimizer, self).__init__(False, name) self.learning_rate = learning_rate self.weight_decay_rate = weight_decay_rate self.beta_1 = beta_1 self.beta_2 = beta_2 self.epsilon = epsilon self.exclude_from_weight_decay = exclude_from_weight_decay def apply_gradients(self, grads_and_vars, global_step=None, name=None): assignments = [] for grad,param in grads_and_vars: if grad is None or param is None: continue param_name = self._get_variable_name(param.name) m = tf.get_variable( name=param_name+'/adam_m', shape=param.shape.as_list(), dtype=tf.float32, trainable=False, initializer=tf.zeros_initializer()) v = tf.get_variable( name=param_name+'/adam_v', shape=param.shape.as_list(), dtype=tf.float32, trainable=False, initializer=tf.zeros_initializer()) next_m = tf.multiply(self.beta_1, m)+tf.multiply(1.0-self.beta_1, grad) next_v = tf.multiply(self.beta_2, v)+tf.multiply(1.0-self.beta_2, tf.square(grad)) update = next_m/(tf.sqrt(next_v)+self.epsilon) if self._do_use_weight_decay(param_name): update += self.weight_decay_rate*param update_with_lr = self.learning_rate*update next_param = param-update_with_lr assignments.extend([param.assign(next_param), m.assign(next_m), v.assign(next_v)]) return tf.group(*assignments, name=name) def _get_variable_name(self, param_name): m = re.match('^(.*):\\d+$', param_name) if m is not None: param_name = m.group(1) return param_name def _do_use_weight_decay(self, param_name): if not self.weight_decay_rate: return False if self.exclude_from_weight_decay: for r in self.exclude_from_weight_decay: if re.search(r, param_name) is not None: return False return True class AdamWeightDecayOptimizerMulti(optimizer.Optimizer): def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-6, exclude_from_weight_decay=None, name='AdamWeightDecayOptimizer'): super(AdamWeightDecayOptimizerMulti, self).__init__(False, name) self.learning_rate = learning_rate self.weight_decay_rate = weight_decay_rate self.beta_1 = beta_1 self.beta_2 = beta_2 self.epsilon = epsilon self.exclude_from_weight_decay = exclude_from_weight_decay def _prepare(self): self.learning_rate_t = ops.convert_to_tensor( self.learning_rate, name='learning_rate') self.weight_decay_rate_t = ops.convert_to_tensor( self.weight_decay_rate, name='weight_decay_rate') self.beta_1_t = ops.convert_to_tensor(self.beta_1, name='beta_1') self.beta_2_t = ops.convert_to_tensor(self.beta_2, name='beta_2') self.epsilon_t = ops.convert_to_tensor(self.epsilon, name='epsilon') def _create_slots(self, var_list): for v in var_list: self._zeros_slot(v, 'm', self._name) self._zeros_slot(v, 'v', self._name) def _apply_dense(self, grad, var): learning_rate_t = math_ops.cast(self.learning_rate_t, var.dtype.base_dtype) beta_1_t = math_ops.cast(self.beta_1_t, var.dtype.base_dtype) beta_2_t = math_ops.cast(self.beta_2_t, var.dtype.base_dtype) epsilon_t = math_ops.cast(self.epsilon_t, var.dtype.base_dtype) weight_decay_rate_t = math_ops.cast(self.weight_decay_rate_t, var.dtype.base_dtype) m = self.get_slot(var, 'm') v = self.get_slot(var, 'v') next_m = (tf.multiply(beta_1_t, m)+tf.multiply(1.0-beta_1_t, grad)) next_v = (tf.multiply(beta_2_t, v)+tf.multiply(1.0-beta_2_t, tf.square(grad))) update = next_m/(tf.sqrt(next_v)+epsilon_t) if self._do_use_weight_decay(self._get_variable_name(var)): update += weight_decay_rate_t*var update_with_lr = learning_rate_t*update next_param = var-update_with_lr return control_flow_ops.group(*[var.assign(next_param), m.assign(next_m), v.assign(next_v)]) def _resource_apply_dense(self, grad, var): learning_rate_t = math_ops.cast(self.learning_rate_t, var.dtype.base_dtype) beta_1_t = math_ops.cast(self.beta_1_t, var.dtype.base_dtype) beta_2_t = math_ops.cast(self.beta_2_t, var.dtype.base_dtype) epsilon_t = math_ops.cast(self.epsilon_t, var.dtype.base_dtype) weight_decay_rate_t = math_ops.cast(self.weight_decay_rate_t, var.dtype.base_dtype) m = self.get_slot(var, 'm') v = self.get_slot(var, 'v') next_m = (tf.multiply(beta_1_t, m)+tf.multiply(1.0-beta_1_t, grad)) next_v = (tf.multiply(beta_2_t, v)+tf.multiply(1.0-beta_2_t, tf.square(grad))) update = next_m/(tf.sqrt(next_v)+epsilon_t) if self._do_use_weight_decay(var.name): update += weight_decay_rate_t*var update_with_lr = learning_rate_t*update next_param = var-update_with_lr return control_flow_ops.group(*[var.assign(next_param), m.assign(next_m), v.assign(next_v)]) def _apply_sparse_shared(self, grad, var, indices, scatter_add): learning_rate_t = math_ops.cast(self.learning_rate_t, var.dtype.base_dtype) beta_1_t = math_ops.cast(self.beta_1_t, var.dtype.base_dtype) beta_2_t = math_ops.cast(self.beta_2_t, var.dtype.base_dtype) epsilon_t = math_ops.cast(self.epsilon_t, var.dtype.base_dtype) weight_decay_rate_t = math_ops.cast(self.weight_decay_rate_t, var.dtype.base_dtype) m = self.get_slot(var, 'm') v = self.get_slot(var, 'v') m_t = state_ops.assign(m, m*beta_1_t, use_locking=self._use_locking) m_scaled_g_values = grad*(1-beta_1_t) with ops.control_dependencies([m_t]): m_t = scatter_add(m, indices, m_scaled_g_values) v_scaled_g_values = (grad*grad)*(1-beta_2_t) v_t = state_ops.assign(v, v*beta_2_t, use_locking=self._use_locking) with ops.control_dependencies([v_t]): v_t = scatter_add(v, indices, v_scaled_g_values) update = m_t/(math_ops.sqrt(v_t)+epsilon_t) if self._do_use_weight_decay(var.name): update += weight_decay_rate_t*var update_with_lr = learning_rate_t*update var_update = state_ops.assign_sub(var, update_with_lr, use_locking=self._use_locking) return control_flow_ops.group(*[var_update, m_t, v_t]) def _apply_sparse(self, grad, var): return self._apply_sparse_shared(grad.values, var, grad.indices, lambda x, i, v: state_ops.scatter_add(x, i, v, use_locking=self._use_locking)) def _resource_scatter_add(self, x, i, v): with ops.control_dependencies([resource_variable_ops.resource_scatter_add(x.handle, i, v)]): return x.value() def _resource_apply_sparse(self, grad, var, indices): return self._apply_sparse_shared(grad, var, indices, self._resource_scatter_add) def _do_use_weight_decay(self, param_name): if not self.weight_decay_rate: return False if self.exclude_from_weight_decay: for r in self.exclude_from_weight_decay: if re.search(r, param_name) is not None: return False return True def _get_variable_name(self, param_name): m = re.match('^(.*):\\d+$', param_name) if m is not None: param_name = m.group(1) return param_name def create_optimizer(loss, init_lr, num_train_steps, num_warmup_steps, hvd=None, num_gpus=1, use_fp16=False): global_step = tf.train.get_or_create_global_step() learning_rate = tf.train.polynomial_decay(tf.constant(value=init_lr, shape=[], dtype=tf.float32), global_step, num_train_steps, end_learning_rate=0.0, power=1.0, cycle=False) if num_gpus > 1: learning_rate = learning_rate*num_gpus global_steps = tf.cast(tf.cast(global_step, tf.int32), tf.float32) warmup_steps = tf.cast(tf.constant(num_warmup_steps, dtype=tf.int32), tf.float32) is_warmup = tf.cast(global_steps < warmup_steps, tf.float32) learning_rate = (1.0-is_warmup)*learning_rate+is_warmup*init_lr*global_steps/warmup_steps if num_gpus > 1: optimizer = AdamWeightDecayOptimizerMulti( learning_rate=learning_rate, weight_decay_rate=0.01, beta_1=0.9, beta_2=0.999, epsilon=1e-6, exclude_from_weight_decay=['LayerNorm', 'layer_norm', 'bias'] ) else: optimizer = AdamWeightDecayOptimizer( learning_rate=learning_rate, weight_decay_rate=0.01, beta_1=0.9, beta_2=0.999, epsilon=1e-6, exclude_from_weight_decay=['LayerNorm', 'layer_norm', 'bias'] ) if use_fp16: loss_scale_manager = tf.contrib.mixed_precision.ExponentialUpdateLossScaleManager( init_loss_scale=2**32, incr_every_n_steps=1000, decr_every_n_nan_or_inf=2, decr_ratio=0.5) optimizer = tf.contrib.mixed_precision.LossScaleOptimizer(optimizer, loss_scale_manager) if hvd is not None: from horovod.tensorflow.compression import Compression optimizer = hvd.DistributedOptimizer(optimizer, sparse_as_dense=True, compression=Compression.none) tvars = tf.trainable_variables() grads = tf.gradients(loss, tvars) is_finite = tf.reduce_all([tf.reduce_all(tf.is_finite(g)) for g in grads]) \ if use_fp16 else tf.constant(True, dtype=tf.bool) grads, _ = tf.clip_by_global_norm(grads, clip_norm=1.0, use_norm=tf.cond(is_finite, lambda: tf.global_norm(grads), lambda: tf.constant(1.0))) train_op = optimizer.apply_gradients(zip(grads, tvars), global_step=global_step) n_global_step = tf.cond(is_finite, lambda: global_step+1, lambda: global_step) return tf.group(train_op, [global_step.assign(n_global_step)])<file_sep>/requirements.txt gensim numpy requests pyahocorasick requests tensorflow==1.9.0 pyyaml<file_sep>/README.md # 命名实体识别工具(tensorflow版) ## 字向量模型 我们自己训练的模型,采用中文维基百科数据作为训练语料 模型存放在百度云中 链接:https://pan.baidu.com/s/1C1qB2b6HyzOpj3eqDehhEQ 提取码:5b6y 下载w2v.model.vectors.npy,放在 /model/w2v 目录下 ## 数据: ac自动机测试数据是省市区数据,来自网络。 数据来源:https://www.cluebenchmarks.com/introduce.html CLUENER细粒度命名实体识别 本demo只识别公司和职位,筛选含有公司和职位的数据,作为训练和验证数据 源数据:/data/raw_data 处理后的训练数据:/data/train.txt 处理后的验证数据:/data/eval.txt ## demo 详见:main.py ac自动机匹配: test_ac_match 1层bilstm_crf: test_bilstm_crf_1 2层bilstm_crf: test_bilstm_crf_2 3层bilstm_crf: test_bilstm_crf_3 4层bilstm_crf: test_bilstm_crf_4 bilstm_crf + attention: test_bilstm_crf_attention w2v + 1层bilstm_crf: test_w2v_bilstm_crf_1 w2v + 2层bilstm_crf: test_w2v_bilstm_crf_2 w2v + 1层bilstm_crf + attention: test_w2v_bilstm_crf_attention bert_crf: test_bert_crf bert + bilstm_crf: test_bert_bilstm_crf ## 模型参数及效果 /model中的模型训练参数如下: **(1) 1层bilstm_crf:** batch_size: 64, epoch: 200, loss: adam, rate: 0.01, num_unit: 256, dropout: 0.1 eval company recall:0.7301587301587301, eval company precision:0.7582417582417582, eval company f1:0.7439353099730458 eval position recall:0.7505773672055427, eval position precision:0.818639798488665, eval position f1:0.7831325301204818 **(2) 2层bilstm_crf:** batch_size: 64, epoch: 200, loss: adam, rate: 0.01, num_unit: 220, dropout: 0.0 eval company recall:0.6984126984126984, eval company precision:0.7213114754098361, eval company f1:0.7096774193548387 eval position recall:0.7251732101616628, eval position precision:0.7929292929292929, eval position f1:0.7575392038600723 **(3) 3层bilstm_crf:** batch_size: 128, epoch: 200, loss: adam, rate: 0.01, num_unit: 200, dropout: 0.1 eval company recall:0.6851851851851852, eval company precision:0.7442528735632183, eval company f1:0.7134986225895316 eval position recall:0.7090069284064665, eval position precision:0.7752525252525253, eval position f1:0.7406513872135103 **(4) 4层bilstm_crf:** batch_size: 128, epoch: 200, loss: adam, rate: 0.01, num_unit: 150, dropout: 0.0 eval company recall:0.6772486772486772, eval company precision:0.7272727272727273, eval company f1:0.7013698630136986 eval position recall:0.7251732101616628, eval position precision:0.7969543147208121, eval position f1:0.7593712212817412 **(5) 带attention的bilstm_crf:** batch_size: 64, epoch: 200, loss: adam, rate: 0.01, num_unit: 200, dropout: 0.1 eval company recall:0.7037037037037037, eval company precision:0.7327823691460055, eval company f1:0.717948717948718 eval position recall:0.7482678983833718, eval position precision:0.8120300751879699, eval position f1:0.7788461538461539 **(6) w2v + 一层bilstm_crf:** batch_size: 64, epoch: 200, loss: adam, rate: 0.01, num_unit: 200, dropout: 0.1 eval company recall:0.7433862433862434, eval company precision:0.7762430939226519, eval company f1:0.7594594594594595 eval position recall:0.7829099307159353, eval position precision:0.8411910669975186, eval position f1:0.8110047846889952 **(7) w2v + 两层bilstm_crf:** batch_size: 64, epoch: 200, loss: adam, rate: 0.01, num_unit: 200, dropout: 0.1 eval company recall:0.7354497354497355, eval company precision:0.7616438356164383, eval company f1:0.7483176312247644 eval position recall:0.792147806004619, eval position precision:0.8051643192488263, eval position f1:0.7986030267753202 **(8) w2v + bilstm_crf + attention:** batch_size: 64, epoch: 200, loss: adam, rate: 0.01, num_unit: 200, dropout: 0.1 eval company recall:0.7328042328042328, eval company precision:0.7824858757062146, eval company f1:0.7568306010928961 eval position recall:0.74364896073903, eval position precision:0.817258883248731, eval position f1:0.7787182587666264 **(9) bert_crf:** batch_size: 32, epoch: 500, loss: sgd, rate: 0.01, max_len: 64, encoder_layer: 11 eval company recall:0.6613756613756614, eval company precision:0.7246376811594203, eval company f1:0.6915629322268325 eval position recall:0.7222222222222222, eval position precision:0.78, eval position f1:0.7500000000000001 **(10) bert + bilstm_crf:** batch_size: 32, epoch: 500, loss: sgd, rate: 0.01, num_units: 128, dropout: 0.1, max_len: 64, encoder_layer: 11 eval company recall:0.7435897789091218, eval company precision:0.7846376811594203, eval company f1:0.7635624605658261 eval position recall:0.7832222222222222, eval position precision:0.8446376811594203, eval position f1:0.812771418764053 ## todo: 增加带词汇增强的命名实体识别方法 1,FLAT:参考论文《FLAT: Chinese NER Using Flat-Lattice Transformer》<file_sep>/src/bilstm_crf.py # encoding=utf-8 import tensorflow as tf import random import numpy as np class BiLstmCrf: def __init__(self, logger, train_path, eval_path, max_len, batch_size, epoch, loss, rate, num_units, num_layers, dropout, tf_config, model_path, summary_path, embedding_dim=300, tag2label=None, use_attention=False, attention_size=128): self.logger = logger self.train_path = train_path self.eval_path = eval_path self.max_len = max_len self.batch_size = batch_size self.epoch = epoch self.loss = loss self.rate = rate self.num_units = num_units self.num_layers = num_layers self.dropout = dropout self.tf_config = tf_config self.model_path = model_path self.summary_path = summary_path self.embedding_dim = embedding_dim self.use_attention = use_attention self.attention_size = attention_size if tag2label is None: tag2label = { 'O': 0, 'B-com': 1, 'I-com': 2, 'B-pos': 3, 'I-pos': 4 } self.tag2label = tag2label self.word2id, self.id2word, self.label2tag = self.get_mapping() self.pred_sess = None def get_mapping(self): word2id = { '<PAD>': 0, '<UNK>': 1 } id2word = { 0: '<PAD>', 1: '<UNK>' } label2tag = {} count = 2 with open(self.train_path, 'r', encoding='utf-8') as f: for line in f: if '\n' == line: continue word, _ = line.replace('\n', '').split('\t') if word not in word2id: word2id[word] = count id2word[count] = word count += 1 for key in self.tag2label: label2tag[self.tag2label[key]] = key return word2id, id2word, label2tag def get_input_feature(self, data_path): ''' 获取数据特征 :param data_path: :return: ''' data = [] seq = [] label = [] with open(data_path, 'r', encoding='utf-8') as f: for line in f: if '\n' == line: if len(label) != len(seq): raise('label and seq, length is not match') seq_len = len(seq) if seq_len > self.max_len: seq = seq[: self.max_len] label = label[: self.max_len] seq_len = self.max_len else: seq += [self.word2id['<PAD>']] * (self.max_len - seq_len) label += [self.tag2label['O']] * (self.max_len - seq_len) data.append([seq, seq_len, label]) seq = [] label = [] else: word, tag = line.replace('\n', '').split('\t') if word not in self.word2id: word = '<UNK>' seq.append(self.word2id[word]) label.append(self.tag2label[tag]) if len(seq) > 0 and len(seq) == len(label): seq_len = len(seq) if seq_len > self.max_len: seq = seq[: self.max_len] label = label[: self.max_len] else: seq += [self.word2id['<PAD>']] * (self.max_len - seq_len) label += [self.tag2label['O']] * (self.max_len - seq_len) data.append([seq, seq_len, label]) return np.asarray(data) def batch_yield(self, data, shuffle=False): ''' 产生batch数据 :param data: :param shuffle: :return: ''' if shuffle: random.shuffle(data) seqs, seq_lens, labels = [], [], [] for (seq, seq_len, label) in data: if len(seqs) == self.batch_size: yield np.asarray(seqs), np.asarray(seq_lens), np.asarray(labels) seqs, seq_lens, labels = [], [], [] seqs.append(seq) seq_lens.append(seq_len) labels.append(label) if len(seqs) != 0: yield np.asarray(seqs), np.asarray(seq_lens), np.asarray(labels) def attention(self, inputs): ''' 注意力层 :param inputs: :return: ''' hidden_size = inputs.shape[2].value w_omega = tf.Variable(tf.random_normal([hidden_size, self.attention_size], stddev=0.1)) b_omega = tf.Variable(tf.random_normal([self.attention_size], stddev=0.1)) u_omega = tf.Variable(tf.random_normal([self.attention_size], stddev=0.1)) v = tf.tanh(tf.tensordot(inputs, w_omega, axes=1) + b_omega) vu = tf.tensordot(v, u_omega, axes=1, name='vu') alphas = tf.nn.softmax(vu, name='alphas') output = tf.multiply(inputs, tf.expand_dims(alphas, -1)) output = tf.add(output, inputs) return output def model(self, seqs, seq_lens, labels, keep_prob): ''' 构建网络 :param seqs: :param seq_lens: :param labels: :param keep_prob: :return: ''' embedding_matrix = tf.get_variable('embedding_matrix', [len(self.word2id), self.embedding_dim], dtype=tf.float32) embedded = tf.nn.embedding_lookup(embedding_matrix, seqs) # cell_fw = tf.nn.rnn_cell.LSTMCell(self.num_units) # cell_bw = tf.nn.rnn_cell.LSTMCell(self.num_units) cell_fws = [] cell_bws = [] for _ in range(self.num_layers): cell_fw = tf.contrib.rnn.BasicLSTMCell(self.num_units, forget_bias=1.0, state_is_tuple=True) cell_fw = tf.contrib.rnn.DropoutWrapper(cell=cell_fw, input_keep_prob=1.0, output_keep_prob=keep_prob, state_keep_prob=1.0) cell_bw = tf.contrib.rnn.BasicLSTMCell(self.num_units, forget_bias=1.0, state_is_tuple=True) cell_bw = tf.contrib.rnn.DropoutWrapper(cell=cell_bw, input_keep_prob=1.0, output_keep_prob=keep_prob, state_keep_prob=1.0) cell_fws.append(cell_fw) cell_bws.append(cell_bw) stacked_lstm_fw = tf.contrib.rnn.MultiRNNCell(cell_fws) stacked_lstm_bw = tf.contrib.rnn.MultiRNNCell(cell_bws) ((rnn_fw_outputs, rnn_bw_outputs), (rnn_fw_final_state, rnn_bw_final_state)) = tf.nn.bidirectional_dynamic_rnn( cell_fw=stacked_lstm_fw, cell_bw=stacked_lstm_bw, inputs=embedded, sequence_length=seq_lens, dtype=tf.float32 ) rnn_outputs = tf.add(rnn_fw_outputs, rnn_bw_outputs) if self.use_attention: rnn_outputs = self.attention(rnn_outputs) logits_seq = tf.layers.dense(rnn_outputs, len(self.tag2label)) log_likelihood, transition_matrix = tf.contrib.crf.crf_log_likelihood(logits_seq, labels, seq_lens) preds_seq, crf_scores = tf.contrib.crf.crf_decode(logits_seq, transition_matrix, seq_lens) return preds_seq, log_likelihood def fit(self): ''' 训练模型 :return: ''' train_data = self.get_input_feature(self.train_path) seqs = tf.placeholder(tf.int32, [None, None], name='seqs') seq_lens = tf.placeholder(tf.int32, [None], name='seq_lens') labels = tf.placeholder(tf.int32, [None, None], name='labels') keep_prob = tf.placeholder(tf.float32, [], name='keep_prob') preds_seq, log_likelihood = self.model(seqs, seq_lens, labels, keep_prob) tf.add_to_collection('preds_seq', preds_seq) loss = -log_likelihood / tf.cast(seq_lens, tf.float32) loss = tf.reduce_mean(loss) if 'sgd' == self.loss.lower(): train_op = tf.train.GradientDescentOptimizer(self.rate).minimize(loss) elif 'adam' == self.loss.lower(): train_op = tf.train.AdamOptimizer(self.rate).minimize(loss) else: train_op = tf.train.GradientDescentOptimizer(self.rate).minimize(loss) saver = tf.train.Saver(tf.global_variables()) with tf.Session(config=self.tf_config) as sess: sess.run(tf.global_variables_initializer()) for i in range(self.epoch): for step, (seqs_batch, seq_lens_batch, labels_batch) in enumerate(self.batch_yield(train_data)): _, curr_loss = sess.run([train_op, loss], feed_dict={seqs: seqs_batch, seq_lens: seq_lens_batch, labels: labels_batch, keep_prob: 1-self.dropout}) if step % 10 == 0: self.logger.info('epoch:%d, batch: %d, current loss: %f' % (i, step+1, curr_loss)) saver.save(sess, self.model_path) tf.summary.FileWriter(self.summary_path, sess.graph) self.evaluate(sess, seqs, seq_lens, labels, keep_prob, preds_seq) def evaluate(self, sess, seqs, seq_lens, labels, keep_prob, preds_seq): ''' 评估模型 :param sess: :param seqs: :param seq_lens: :param labels: :param keep_prob: :param preds_seq: :return: ''' eval_data = self.get_input_feature(self.eval_path) tp_com = 0 # 正类判定为正类 fp_com = 0 # 负类判定为正类 fn_com = 0 # 正类判定为负类 tp_pos = 0 # 正类判定为正类 fp_pos = 0 # 负类判定为正类 fn_pos = 0 # 正类判定为负类 for _, (seqs_batch, seq_lens_batch, labels_batch) in enumerate(self.batch_yield(eval_data)): preds = sess.run(preds_seq, feed_dict={seqs: seqs_batch, seq_lens: seq_lens_batch, labels: labels_batch, keep_prob: 1.0}) for i in range(len(preds)): pred = preds[i] label = labels_batch[i] seq_len = seq_lens_batch[i] true_com, true_pos = self.label2entity(label[: seq_len]) pred_com, pred_pos = self.label2entity(pred[: seq_len]) tp_com += len(true_com & pred_com) fp_com += len(pred_com - true_com) fn_com += len(true_com - pred_com) tp_pos += len(true_pos & pred_pos) fp_pos += len(pred_pos - true_pos) fn_pos += len(true_pos - pred_pos) recall_com = tp_com / (tp_com + fn_com) precision_com = tp_com / (tp_com + fp_com) f1_com = (2 * recall_com * precision_com) / (recall_com + precision_com) recall_pos = tp_pos / (tp_pos + fn_pos) precision_pos = tp_pos / (tp_pos + fp_pos) f1_pos = (2 * recall_pos * precision_pos) / (recall_pos + precision_pos) self.logger.info('eval company recall:' + str(recall_com) + ', eval company precision:' + str(precision_com) + ', eval company f1:' + str(f1_com) + ', eval position recall:' + str(recall_pos) + ', eval position precision:' + str(precision_pos) + ', eval position f1:' + str(f1_pos)) def label2entity(self, label): ''' 将预测结果[0, 1, 2, 2, 2, 0, 3, 4]转成(com_1_4, pos_6_7),com公司实体,1是起始位置,4是结束位置,方便统计 :param label: :return: ''' com_set = set() pos_set = set() entity = '' count = 0 while count < len(label): if 'B-com' == self.label2tag[int(label[count])]: entity += 'com_' + str(count) count += 1 while count < len(label): if 'I-com' == self.label2tag[int(label[count])] and count == len(label) - 1: entity += '_' + str(count) break if 'I-com' != self.label2tag[int(label[count])]: entity += '_' + str(count - 1) break count += 1 s = entity.split('_') if 3 == len(s) and s[1] != s[2]: com_set.add(entity) entity = '' elif 'B-pos' == self.label2tag[int(label[count])]: entity += 'pos_' + str(count) count += 1 while count < len(label): if 'I-pos' == self.label2tag[int(label[count])] and count == len(label) - 1: entity += '_' + str(count) break if 'I-pos' != self.label2tag[int(label[count])]: entity += '_' + str(count - 1) break count += 1 s = entity.split('_') if 3 == len(s) and s[1] != s[2]: pos_set.add(entity) entity = '' else: count += 1 return com_set, pos_set def load(self, path): ''' 加载模型 :param path: :return: ''' self.pred_sess = tf.Session(config=self.tf_config) saver = tf.train.import_meta_graph(path + '/model.meta') saver.restore(self.pred_sess, tf.train.latest_checkpoint(path)) graph = tf.get_default_graph() self.seqs = graph.get_tensor_by_name('seqs:0') self.labels = graph.get_tensor_by_name('labels:0') self.seq_lens = graph.get_tensor_by_name('seq_lens:0') self.keep_prob = graph.get_tensor_by_name('keep_prob:0') self.preds_seq = tf.get_collection('preds_seq') def close(self): ''' 关闭session :return: ''' self.pred_sess.close() def _predict_text_process(self, text): ''' 对输入数据预处理 :param text: :return: ''' seq = [] label = [] for word in list(text): if word in self.word2id: seq.append(self.word2id[word]) else: seq.append(self.word2id['<UNK>']) label.append(-1) seq_len = len(seq) if seq_len > self.max_len: seq = seq[: self.max_len] label = label[: self.max_len] else: seq += [self.word2id['<PAD>']] * (self.max_len - seq_len) label += [self.tag2label['O']] * (self.max_len - seq_len) return np.asarray([seq]), np.asarray([seq_len]), np.asarray([label]) def predict(self, text): ''' 预测 :param text: string类型 :return: ''' seq_pred, seq_len_pred, label_pred = self._predict_text_process(text) pred, _ = self.pred_sess.run(self.preds_seq, feed_dict={self.seqs: seq_pred, self.seq_lens: seq_len_pred, self.labels: label_pred, self.keep_prob: 1.0}) return pred<file_sep>/src/util/load_dir_util.py # encoding=utf-8 import os def load_data_from_dir(path): for dir_path, dir_names, file_names in os.walk(path): for file in file_names: full_path = os.path.join(dir_path, file) for line in open(full_path, encoding='UTF-8'): yield line.strip().split("\t")<file_sep>/src/util/logger.py # encoding=utf-8 import logging def setlogger(config): cfg = {} for k in config: cfg[k] = config[k] logger = logging.getLogger(cfg['Server_Name']) if len(logger.handlers) > 0: return logger formatter = logging.Formatter(cfg['LogFormat']) logger.setLevel(10) # setup console setting if cfg['LogLevel_Console'] > 0: ch = logging.StreamHandler() ch.setLevel(cfg["LogLevel_Console"]) ch.setFormatter(formatter) logger.addHandler(ch) # setup file logging path if cfg['LogLevel_File'] > 0: fh = logging.FileHandler(cfg['LogFile'], encoding='utf-8', mode='a') fh.setLevel(cfg["LogLevel_File"]) fh.setFormatter(formatter) logger.addHandler(fh) return logger if __name__ == '__main__': config = {} logger = setlogger(config) text = input("input print info:") logger.info(text) logger.warning("it worked") <file_sep>/main.py # encoding=utf-8 from src.ac_match import ACMatch from src.util.logger import setlogger from src.util.yaml_util import loadyaml from src.bilstm_crf import BiLstmCrf import os import tensorflow as tf from gensim.models import KeyedVectors from src.w2v_bilstm_crf import W2VBiLstmCrf from src.bert_crf import BertCrf from src.bert_bilstm_crf import BertBiLstmCrf config = loadyaml('conf/NER.yaml') logger = setlogger(config) # tf配置 os.environ['CUDA_VISIBLE_DEVICES'] = '4' os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # default: 0 tf_config = tf.ConfigProto() tf_config.gpu_options.allow_growth = True tf_config.gpu_options.per_process_gpu_memory_fraction = 0.8 def test_ac_match(): ''' ac自动机匹配,基于词典的命名实体识别 :param text: :return: ''' s = ACMatch(config['ac_test_path']) for e in s.ac_match('上海天气怎么样'): print(e) logger.info(e) def test_bilstm_crf_1(): ''' 一层bilsm_crf :param texts: :return: ''' blc_cfg = { 'logger': logger, 'train_path': config['train_path'], 'eval_path': config['eval_path'], 'max_len': 50, 'batch_size': 64, 'epoch': 200, 'loss': 'adam', 'rate': 0.01, 'num_units': 256, 'num_layers': 1, 'dropout': 0.1, 'tf_config': tf_config, 'model_path': config['bilstm_crf_1_model_path'], 'summary_path': config['bilstm_crf_1_summary_path'], 'use_attention': False } model = BiLstmCrf(**blc_cfg) model.fit() model.load(config['bilstm_crf_1_predict_path']) print(model.predict('招商银行田惠宇行长在股东大会上致辞')) model.close() def test_bilstm_crf_2(): ''' 两层bilsm_crf :param texts: :return: ''' blc_cfg = { 'logger': logger, 'train_path': config['train_path'], 'eval_path': config['eval_path'], 'max_len': 50, 'batch_size': 64, 'epoch': 200, 'loss': 'adam', 'rate': 0.01, 'num_units': 220, 'num_layers': 2, 'dropout': 0.0, 'tf_config': tf_config, 'model_path': config['bilstm_crf_2_model_path'], 'summary_path': config['bilstm_crf_2_summary_path'], 'use_attention': False } model = BiLstmCrf(**blc_cfg) model.fit() model.load(config['bilstm_crf_2_predict_path']) print(model.predict('招商银行田惠宇行长在股东大会上致辞')) model.close() def test_bilstm_crf_3(): ''' 三层bilsm_crf :param texts: :return: ''' blc_cfg = { 'logger': logger, 'train_path': config['train_path'], 'eval_path': config['eval_path'], 'max_len': 50, 'batch_size': 128, 'epoch': 200, 'loss': 'adam', 'rate': 0.01, 'num_units': 200, 'num_layers': 3, 'dropout': 0.1, 'tf_config': tf_config, 'model_path': config['bilstm_crf_3_model_path'], 'summary_path': config['bilstm_crf_3_summary_path'], 'use_attention': False } model = BiLstmCrf(**blc_cfg) model.fit() model.load(config['bilstm_crf_3_predict_path']) print(model.predict('招商银行田惠宇行长在股东大会上致辞')) model.close() def test_bilstm_crf_4(): ''' 四层bilsm_crf :param texts: :return: ''' blc_cfg = { 'logger': logger, 'train_path': config['train_path'], 'eval_path': config['eval_path'], 'max_len': 50, 'batch_size': 128, 'epoch': 200, 'loss': 'adam', 'rate': 0.01, 'num_units': 150, 'num_layers': 4, 'dropout': 0.0, 'tf_config': tf_config, 'model_path': config['bilstm_crf_4_model_path'], 'summary_path': config['bilstm_crf_4_summary_path'], 'use_attention': False } model = BiLstmCrf(**blc_cfg) model.fit() model.load(config['bilstm_crf_4_predict_path']) print(model.predict('招商银行田惠宇行长在股东大会上致辞')) model.close() def test_bilstm_crf_attention(): ''' bilsm_crf + attention :param texts: :return: ''' blc_cfg = { 'logger': logger, 'train_path': config['train_path'], 'eval_path': config['eval_path'], 'max_len': 50, 'batch_size': 64, 'epoch': 200, 'loss': 'adam', 'rate': 0.01, 'num_units': 200, 'num_layers': 1, 'dropout': 0.1, 'tf_config': tf_config, 'model_path': config['bilstm_crf_attention_model_path'], 'summary_path': config['bilstm_crf_attention_summary_path'], 'use_attention': True } model = BiLstmCrf(**blc_cfg) model.fit() model.load(config['bilstm_crf_attention_predict_path']) print(model.predict('招商银行田惠宇行长在股东大会上致辞')) model.close() def test_w2v_bilstm_crf_1(): ''' 字w2v + 1层bilstm_crf :return: ''' w2v = KeyedVectors(config['w2v_path']) wblc_cfg = { 'logger': logger, 'train_path': config['train_path'], 'eval_path': config['eval_path'], 'w2v': w2v, 'max_len': 50, 'batch_size': 64, 'epoch': 200, 'loss': 'adam', 'rate': 0.01, 'dropout': 0.1, 'num_units': 200, 'num_layers': 1, 'tf_config': tf_config, 'model_path': config['w2v_bilstm_crf_1_model_path'], 'summary_path': config['w2v_bilstm_crf_1_summary_path'], 'use_attention': False } model = W2VBiLstmCrf(**wblc_cfg) model.fit() model.load(config['w2v_bilstm_crf_1_predict_path']) print(model.predict('招商银行田惠宇行长在股东大会上致辞')) model.close() def test_w2v_bilstm_crf_2(): ''' 字w2v + 两层bilstm_crf :return: ''' w2v = KeyedVectors.load(config['w2v_path']) wblc_cfg = { 'logger': logger, 'train_path': config['train_path'], 'eval_path': config['eval_path'], 'w2v': w2v, 'max_len': 50, 'batch_size': 64, 'epoch': 200, 'loss': 'adam', 'rate': 0.01, 'dropout': 0.1, 'num_units': 200, 'num_layers': 2, 'tf_config': tf_config, 'model_path': config['w2v_bilstm_crf_2_model_path'], 'summary_path': config['w2v_bilstm_crf_2_summary_path'], 'use_attention': True } model = W2VBiLstmCrf(**wblc_cfg) model.fit() model.load(config['w2v_bilstm_crf_2_predict_path']) print(model.predict('招商银行田惠宇行长在股东大会上致辞')) model.close() def test_w2v_bilstm_crf_attention(): ''' 字w2v + 带attention的bilstm_crf :return: ''' w2v = KeyedVectors.load(config['w2v_path']) wblc_cfg = { 'logger': logger, 'train_path': config['train_path'], 'eval_path': config['eval_path'], 'w2v': w2v, 'max_len': 50, 'batch_size': 64, 'epoch': 200, 'loss': 'adam', 'rate': 0.01, 'dropout': 0.1, 'num_units': 200, 'num_layers': 1, 'tf_config': tf_config, 'model_path': config['w2v_bilstm_crf_attention_model_path'], 'summary_path': config['w2v_bilstm_crf_attention_summary_path'], 'use_attention': True } model = W2VBiLstmCrf(**wblc_cfg) model.fit() model.load(config['w2v_bilstm_crf_attention_predict_path']) print(model.predict('招商银行田惠宇行长在股东大会上致辞')) model.close() def test_bert_crf(): bert_cfg = { 'logger': logger, 'train_path': config['train_path'], 'eval_path': config['eval_path'], 'bert_path': config['bert_path'], 'max_length': 64, 'batch_size': 32, 'rate': 0.01, 'epoch': 500, 'loss': 'sgd', 'encoder_layer': 11, 'tf_config': tf_config, 'model_path': config['bert_crf_model_path'], 'summary_path': config['bert_crf_summary_path'] } model = BertCrf(**bert_cfg) model.fit() model.load(config['bert_crf_predict_path']) print(model.predict('招商银行田惠宇行长在股东大会上致辞')) model.close() def test_bert_bilstm_crf(): bert_cfg = { 'logger': logger, 'train_path': config['train_path'], 'eval_path': config['eval_path'], 'bert_path': config['bert_path'], 'max_length': 64, 'batch_size': 32, 'rate': 0.01, 'num_units': 128, 'dropout': 0.1, 'epoch': 500, 'loss': 'sgd', 'encoder_layer': 11, 'tf_config': tf_config, 'model_path': config['bert_bilstm_crf_model_path'], 'summary_path': config['bert_bilstm_crf_summary_path'] } model = BertBiLstmCrf(**bert_cfg) model.fit() model.load(config['bert_bilstm_crf_predict_path']) print(model.predict('招商银行田惠宇行长在股东大会上致辞')) model.close() if __name__ == '__main__': # test_ac_match() # test_bilstm_crf_1() test_bilstm_crf_2() # test_bilstm_crf_3() # test_bilstm_crf_4() # test_w2v_bilstm_crf_1() # test_w2v_bilstm_crf_2() # test_w2v_bilstm_crf_attention() # test_bert_crf() # test_bert_bilstm_crf()
28d539aa92ac209e6a96e3c5c4e69d5e010a09e1
[ "Markdown", "Text", "Python" ]
9
Markdown
EdisonChen0816/ner_toolkit
87d6634de07eea5b8dae3979148efbfc5381c289
7250081deb956da7fafb6682f16338ab63003d28
refs/heads/master
<file_sep>json.array! @audiences, partial: 'audiences/audience', as: :audience <file_sep><!DOCTYPE html> <html> <head> <title>You're whatching a live video</title> </head> <body> <%= video_player src: { mp4: 'https://content.jwplatform.com/manifests/yp34SRmf.m3u8' }, controls: true %> </body> </html> <file_sep>Rails.application.routes.draw do resources :audiences end <file_sep>json.extract! audience, :id, :user_name, :user_email, :user_avatar_url, :created_at, :updated_at json.url audience_url(audience, format: :json) <file_sep>class AudiencesController < ApplicationController before_action :set_audience, only: [:show, :edit, :update, :destroy] # GET /audiences # GET /audiences.json def index @audiences = Audience.all end # GET /audiences/1 # GET /audiences/1.json def show end # GET /audiences/new def new @audience = Audience.new end # GET /audiences/1/edit def edit end # POST /audiences # POST /audiences.json def create @audience = Audience.new(audience_params) respond_to do |format| if @audience.save format.html { redirect_to @audience, notice: 'Audience was successfully created.' } format.json { render :show, status: :created, location: @audience } else format.html { render :new } format.json { render json: @audience.errors, status: :unprocessable_entity } end end end # PATCH/PUT /audiences/1 # PATCH/PUT /audiences/1.json def update respond_to do |format| if @audience.update(audience_params) format.html { redirect_to @audience, notice: 'Audience was successfully updated.' } format.json { render :show, status: :ok, location: @audience } else format.html { render :edit } format.json { render json: @audience.errors, status: :unprocessable_entity } end end end # DELETE /audiences/1 # DELETE /audiences/1.json def destroy @audience.destroy respond_to do |format| format.html { redirect_to audiences_url, notice: 'Audience was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_audience @audience = Audience.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def audience_params params.require(:audience).permit(:user_name, :user_email, :user_avatar_url) end end <file_sep>class Audience < ActiveRecord::Base end <file_sep><p id="notice"><%= notice %></p> <p> <strong>User name:</strong> <%= @audience.user_name %> </p> <p> <strong>User email:</strong> <%= @audience.user_email %> </p> <p> <strong>User avatar url:</strong> <%= @audience.user_avatar_url %> </p> <%= link_to 'Edit', edit_audience_path(@audience) %> | <%= link_to 'Back', audiences_path %>
b44397fefbb5808c3c68e5e0f5606ae533b95cf9
[ "HTML+ERB", "Ruby" ]
7
HTML+ERB
claudemirmendes/livenetshow
2af85d6bb8c9e963cdda1088efe3faf43d88d01a
121d0e2dca452c1b59746fe464ea6b443f885840
refs/heads/master
<file_sep>// // PDViewController.h // FramedArrangement // // Created by <NAME> on 4/26/15. // Copyright (c) 2015 DevMountain. All rights reserved. // #import <UIKit/UIKit.h> @interface PDViewController : UIViewController @property UIView *redView; @property UIView *greenView; @property UIView *blueView; @property UIView *yellowView; @end <file_sep>// // PDViewController.m // FramedArrangement // // Created by <NAME> on 4/26/15. // Copyright (c) 2015 DevMountain. All rights reserved. // #import "PDViewController.h" @interface PDViewController () @end @implementation PDViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view from its nib. self.redView = [[UIView alloc]init]; self.redView.backgroundColor = [UIColor redColor]; [self.view addSubview:self.redView]; self.greenView = [[UIView alloc]init]; self.greenView.backgroundColor = [UIColor greenColor]; [self.view addSubview:self.greenView]; self.blueView = [[UIView alloc]init]; self.blueView.backgroundColor = [UIColor blueColor]; [self.view addSubview:self.blueView]; self.yellowView = [[UIView alloc]init]; self.yellowView.backgroundColor = [UIColor yellowColor]; [self.view addSubview:self.yellowView]; //[self layoutSquares]; //[self layoutVerticalRectangles]; //[self layoutHorizontalRectangles]; [self layoutDiagonalSquares]; } - (void) layoutSquares { self.redView.frame = CGRectMake(20, 100, 100, 100); self.greenView.frame = CGRectMake(120, 100, 100, 100); self.blueView.frame = CGRectMake(20, 200, 100, 100); self.yellowView.frame = CGRectMake(120, 200, 100, 100); } - (void) layoutHorizontalRectangles { self.redView.frame = CGRectMake(0, 0, 300, 100); self.greenView.frame = CGRectMake(0, 100, 300, 100); self.blueView.frame = CGRectMake(0, 200, 300, 100); self.yellowView.frame = CGRectMake(0, 300, 300, 100); } - (void) layoutVerticalRectangles { // how to find the width // self.redView.frame = CGRectMake(0, 100, self.view.frame.size.width, 100); // NSLog(@"%f", self.view.frame.size.width); self.redView.frame = CGRectMake(0, 0, 80, 300); self.greenView.frame = CGRectMake(80, 0, 80, 300); self.blueView.frame = CGRectMake(160, 0, 80, 300); self.yellowView.frame = CGRectMake(240, 0, 80, 300); } - (void) layoutDiagonalSquares { self.redView.frame = CGRectMake(0, 0, 100, 100); self.greenView.frame = CGRectMake(100, 100, 100, 100); self.blueView.frame = CGRectMake(200, 200, 100, 100); self.yellowView.frame = CGRectMake(300, 300, 100, 100); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } /* #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ @end
e044b36fd34711932da47f09a5b63be8b30a36f0
[ "Objective-C" ]
2
Objective-C
parkerdonat/FramedArrangement
ac88f4cb407f752e5a30ef0cd4d24f567d3f5671
f491e59c9e870bd301b5dbd1b8b662eeeeabc116
refs/heads/main
<file_sep>#Encrypted By MAFIA-KILLER #WHATSAPP : +92132197796/DON,T TRY TO EDIT THIS TOOL/ import zlib, base64 exec(zlib.decompress(base64.b64decode("<KEY>
a4fd536859cab86d98d5b0218534cb655892d0f1
[ "Python" ]
1
Python
Mafia-Killer404/6and11
41ae8536d4d9e5693cbd9e554e6ae5c274adec41
51ce5babcf7f1af5b9a0178a4e98e46567e406f4
refs/heads/master
<repo_name>ShunOmine/for_season<file_sep>/javascripts/contact.js $(".contact").on('click', function () { $(".contact_modal").css("transform", "translateY(0%)") $(".back").show(); }) $(".back").on('click', function () { $(".contact_modal").css("transform", "translateY(200%)") $(".back").hide(); $("#thxMessage-box").css("transform", "translateY(200%)") }) $(".contact_form input").on("keyup", function () { if ($(".contact_form input").val() === "") { $("#submit").attr("disabled", true) } else { $("#submit").attr("disabled", false) } }) $(".contact_form textarea").on("keyup", function () { if ($(".contact_form textarea").val() === "") { $("#submit").attr("disabled", true) } else { $("#submit").attr("disabled", false) } }) function check_form(){ $("#thxMessage-box").css("transform", "translateY(0%)") $("#thxMessage-one").show() $("#thxMessage-two").show() $("#btn-line").show() $(".contact_modal").hide() }
fc62893b38756b2cf5565f3c8b7ff258d0ce65fe
[ "JavaScript" ]
1
JavaScript
ShunOmine/for_season
83a738a03b73c86b23b4c3c3764b06f37dd16be8
ef5c60eff48677debd207d33532e0d63c85d5c30
refs/heads/master
<file_sep>This is NoobCIT's first git project!
e9acbe3647c7c223313b37b27957ab5ea264d973
[ "Markdown" ]
1
Markdown
NoobCIT/git_test
0b7d7b77798e7a7f9ec2113575f680e32f598c0f
66352135f9556e457fe2ef252085f88703068c45
refs/heads/master
<file_sep>#The trained model is saved as the classifier.h5 #The predictor.py shows the way to use that seperately. import numpy as np from keras.models import load_model from keras.preprocessing import image #Make sure the version is correct classifier = load_model('classifier.h5') test_image = image.load_img('<URL of the testing image>', target_size=(64,64)) test_image = image.img_to_array(test_image) test_image = np.expand_dims(test_image, axis=0) result = classifier.predict(test_image) #print(np.argmax(result)) #print(result) {'dogs': 1, 'cats': 0} if result[0][0] == 1: prediction = 'dog' else: prediction = 'cat' print("Yes! It's a cute "+prediction) <file_sep># Convolutional Neural Network # Installing Tensorflow # pip install tensorflow-gpu # Installing Keras # pip install --upgrade keras # Part 1 - Building the CNN # Importing the Keras libraries and packages import keras from keras.layers import Conv2D from keras.layers import MaxPooling2D from keras.layers import Flatten from keras.layers import Dense from keras.utils import plot_model from keras.models import Sequential from datetime import datetime # Initialising the CNN classifier = Sequential() # Step 1 - Convolution #input_shape goes reverse if it is theano backend #Images are 2D classifier.add(Conv2D(32, (3, 3), input_shape = (64, 64, 3), activation = 'relu')) # Step 2 - Pooling #Most of the time it's (2,2) not loosing many. classifier.add(MaxPooling2D(pool_size = (2, 2))) # Adding a second convolutional layer #Inputs are the pooled feature maps of the previous layer classifier.add(Conv2D(32, (3, 3), activation = 'relu')) classifier.add(MaxPooling2D(pool_size = (2, 2))) # Step 3 - Flattening classifier.add(Flatten()) # Step 4 - Full connection #relu - rectifier activation function #128 nodes in the hidden layer classifier.add(Dense(units = 128, activation = 'relu')) #Sigmoid is used because this is a binary classification. For multiclass softmax classifier.add(Dense(units = 1, activation = 'sigmoid')) # Compiling the CNN #adam is for stochastic gradient descent classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy']) # Part 2 - Fitting the CNN to the images #Preprocess the images to reduce overfitting from keras.preprocessing.image import ImageDataGenerator train_datagen = ImageDataGenerator(rescale = 1./255, #All the pixel values would be 0-1 shear_range = 0.2, zoom_range = 0.2, horizontal_flip = True) test_datagen = ImageDataGenerator(rescale = 1./255) training_set = train_datagen.flow_from_directory('dataset/training_set/', target_size = (64, 64), batch_size = 32, class_mode = 'binary') test_set = test_datagen.flow_from_directory('dataset/test_set/', target_size = (64, 64), batch_size = 32, class_mode = 'binary') start_time = datetime.now() classifier.fit_generator(training_set, steps_per_epoch = 8000, #number of images in the training set epochs = 1, validation_data = test_set, validation_steps = 2000) end_time = datetime.now() print("execution time = "+ str(end_time-start_time)) import numpy as np from keras.preprocessing import image test_image = image.load_img('dataset/test_set/dogs/dog.4027.jpg', target_size=(64,64)) test_image = image.img_to_array(test_image) test_image = np.expand_dims(test_image, axis=0) result = classifier.predict(test_image) training_set.class_indices if result[0][0] == 1: prediction = 'dog' else: prediction = 'cat' print(prediction) print(training_set.class_indices) print(result) #Saing the model as a Hierarchical Data Format 5 file classifier.save('classifier.h5') #Keras version should be matched with the production version if the predictor is running in a seperate destination. import keras keras.__version__ <file_sep># CNN based Image Classifier for Cats & Dogs A simple CNN based Image Classifier using Keras (Tensorflow backend) for recognizing cat & dog images on the famous Kaggle competition.
e9d08003b60a5fbf3582ffd534dc5b44dcb936d3
[ "Markdown", "Python" ]
3
Markdown
bensterl15/AMS_573_Project_Copied
a51595c96113aaeabb1c9bbdd4d39f0440e3583b
b5c93c7b913205eb494d3d40f0231e6517ddbedb
refs/heads/main
<file_sep>#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Nov 24 13:07:52 2020 @author: david.hillmann """ # import & preprocess scoring data and trained model -------------------------- import pandas as pd import datetime import time import pickle path = '/Users/david.hillmann/Documents/FullStackDS/' topredict_df = pd.read_csv(path + "data/airline_delay_test.csv") scoring_df = topredict_df.drop(columns=['FlightDate']) # import trained model gbtmodel = pickle.load(open(path + 'flights_model.sav', 'rb')) # transform departure time def transformTimes(deptime): t1 = deptime.apply(lambda x: time.strptime(x, '%H:%M')) t2 = t1.apply(lambda x: datetime.timedelta(hours=x.tm_hour,minutes=x.tm_min,seconds=x.tm_sec).total_seconds()) return t2 / 3600 scoring_df['DepTime'] = transformTimes(scoring_df.DepTime) # one-hot encoding of categorical variables def encode_and_bind(original_dataframe, feature_to_encode): dummies = pd.get_dummies(original_dataframe[[feature_to_encode]]) res = pd.concat([original_dataframe, dummies], axis=1) return res.drop(columns=[feature_to_encode]) scoring_df = encode_and_bind(scoring_df, 'Day_of_Week') scoring_df = encode_and_bind(scoring_df, 'UniqueCarrier') scoring_df = encode_and_bind(scoring_df, 'Origin') scoring_df = scoring_df.drop(columns=['Dest']) # if label known X_scoring = scoring_df.drop(columns = 'dep_delayed_15min') Y_scoring = scoring_df['dep_delayed_15min'] # if label unknown # X_scoring = scoring_df # Get missing columns in the training scoring_df missing_cols = set(gbtmodel.feature_names) - set(X_scoring.columns) # Add a missing column in scoring_df set with default value equal to 0 for c in missing_cols: X_scoring[c] = 0 # Ensure the order of column in the scoring_df set is in the same order than in train set X_scoring = X_scoring[gbtmodel.feature_names] # predict & export ----------------------------------------------------------- from sklearn.metrics import precision_recall_fscore_support from sklearn.metrics import matthews_corrcoef from sklearn.metrics import roc_auc_score # # metrics: precision & recall! # print(precision_recall_fscore_support(Y_scoring, gbtmodel.predict(X_scoring))) # # mcc [-1;+1] Werte um Null ~ Zufall # print(matthews_corrcoef(Y_scoring, gbtmodel.predict(X_scoring))) # # Area Under the Curve (AUC) der ROC Kurve (0.5 ~ Zufall) # print(roc_auc_score(Y_scoring, gbtmodel.predict_proba(X_scoring)[:,1])) # # Kreuztabelle # print(pd.crosstab(gbtmodel.predict(X_scoring), Y_scoring)) # export predictions scores = gbtmodel.predict_proba(X_scoring)[:,1] topredict_df['delay_pred_prob'] = scores topredict_df['delay_pred_bin'] = scores >= 0.5 topredict_df.to_csv(path + 'predictions/predicted_delays.csv') <file_sep>#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Nov 24 13:07:52 2020 @author: david.hillmann """ import pandas as pd import datetime import time import pickle # import train --------------------------------------------------------------- path = '/Users/david.hillmann/Documents/FullStackDS/' train = pd.read_csv(path + "data/airline_delay_train.csv") # preprocess train ----------------------------------------------------------- train = train.drop(columns=['FlightDate']) # transform departure time def transformTimes(deptime): t1 = deptime.apply(lambda x: time.strptime(x, '%H:%M')) t2 = t1.apply(lambda x: datetime.timedelta(hours=x.tm_hour,minutes=x.tm_min,seconds=x.tm_sec).total_seconds()) return t2 / 3600 train['DepTime'] = transformTimes(train.DepTime) # one-hot encoding of categorical variables def encode_and_bind(original_dataframe, feature_to_encode): dummies = pd.get_dummies(original_dataframe[[feature_to_encode]]) res = pd.concat([original_dataframe, dummies], axis=1) return res.drop(columns=[feature_to_encode]) train = encode_and_bind(train, 'Day_of_Week') train = encode_and_bind(train, 'UniqueCarrier') train = encode_and_bind(train, 'Origin') def reduce_ohcols(df, regexpres, n_min): v1 = df.filter(regex =(regexpres)).apply(lambda x: sum(x)) cols2drop = v1[v1 < n_min].index.values return df.drop(columns=cols2drop) train = reduce_ohcols(train, 'Origin_', int(train.shape[0]*0.0025)) train = train.drop(columns=['Dest']) X_train = train.drop(columns = 'dep_delayed_15min') Y_train = train['dep_delayed_15min'] # hyperparameter tuning ------------------------------------------------------ from sklearn.ensemble import GradientBoostingClassifier from sklearn.model_selection import GridSearchCV # # Gradient Boosted Trees: Hyperparameter Search! # gbt = GradientBoostingClassifier() # parameters = {'max_depth':[1, 5, 10, 30], # 'n_estimators':[10, 20, 30], # 'learning_rate':[0.05, 0.1, 0.2]} # gsearch = GridSearchCV(gbt, parameters, cv = 5, scoring = 'f1', n_jobs = -1) # gsearch.fit(X_train, Y_train) # print(gsearch.cv_results_) # print(gsearch.best_params_) # print(gsearch.best_score_) # train model ---------------------------------------------------------------- gbtmodel = GradientBoostingClassifier(n_estimators=15, learning_rate=0.1, max_depth=30) gbtmodel.fit(X_train, Y_train) # save model gbtmodel.feature_names = list(X_train.columns.values) pickle.dump(gbtmodel, open(path + 'flights_model.sav', 'wb'))
2890a298a099c1f12c5d19596b306098a72c8828
[ "Python" ]
2
Python
HillmaDa/Full-Stack-DS-Course
27baca7e01867e3f41b87c782d04ffb784ef7a1a
98e58a5fdef789edbefb9a01bcb924b554a51ed2
refs/heads/main
<repo_name>skytotwo/AllsitePasswd<file_sep>/README.md # AllsitePasswd AllsitePasswd 是一款启用全站密码访问插件,支持自定义主题模板:@(呆滞) github地址:https://github.com/gogobody/AllsitePasswd 欢迎 fork,start ![](https://cdn.jsdelivr.net/gh/gogobody/blog-img/blogimg/20210311203610.png) ## 说明 插件默认自带一套模板 用户可以自定义模板,把你的html模板文件放进theme文件夹,html起名叫index.html 但注意引用图片,css,js等文件时需要使用绝对路径。 比如: -AllsitePasswd |- theme &nbsp;&nbsp; |- css/a.css &nbsp;&nbsp; |- js/b.js &nbsp;&nbsp; |- index.html 这个时候 index.html 里面引入a.css的路径为 ```css /usr/plugins/AllsitePasswd/theme/css/a.css ``` 同样引入 js 路径为 ```css /usr/plugins/AllsitePasswd/theme/js/b.js ``` 在 html 文件中可以用的替代变量,只需要把html对应位置换成以下变量即可。只针对 index.html 有效:@(鼓掌)。 ```css '{theme_base_path}',// 绝对路径,指向 /usr/plugins/AllsitePasswd/theme/ '{str_word}', // 后台配置的提示文字 '{url_pic}', // 后台配置的提示图片 '{err_msg}',// 密码错误输出消息 '{form_action}',// form表单提交的 url ,也就是 action='{form_action}' '{input_placeholder}',// 后台配置的输入框提示 '{submit_text}',// 后台配置的提交按钮 '{commic_pic}' // 插件自带的动漫图 api,比如:<img src="{commic_pic}"> ``` 还有就是输入密码那个 input 的name属性: ```css name="index_passwd" ``` 举个栗子:&(蛆音疑惑): ``` <form action="{form_action}"> <input name="index_passwd" type="password" placeholder="{input_placeholder}" /> <input type="submit" value="{submit_text}"> </form> ```<file_sep>/Plugin.php <?php if (!defined('__TYPECHO_ROOT_DIR__')) exit; /** * AllsitePasswd 是一款启用全站密码访问插件,支持自定义主题模板 * * @package AllsitePasswd * @author 即刻学术 * @version 1.0.0 * @link https://www.ijkxs.com */ class AllsitePasswd_Plugin implements Typecho_Plugin_Interface { /** * 激活插件方法,如果激活失败,直接抛出异常 * * @access public * @return void * @throws Typecho_Plugin_Exception */ public static function activate() { Typecho_Plugin::factory('admin/menu.php')->navBar = array('AllsitePasswd_Plugin', 'render'); // Typecho_Plugin::factory('index.php')->begin = array('AllsitePasswd_Plugin', 'main_fun'); Typecho_Plugin::factory('Widget_Archive')->headerOptions =array('AllsitePasswd_Plugin', 'main_fun'); } public static function main_fun() { Typecho_Widget::widget('Widget_Security')->to($security); if ($security->request->get('_') == $security->getToken($security->request->getReferer())){ return; } $Str_Msg_PSWERR=""; //检查密码 处理 cookies if ( isset($_POST['index_passwd']) ){ if ( trim($_POST['index_passwd'])== Typecho_Widget::widget('Widget_Options')->plugin('AllsitePasswd')->str_Pword ){ setcookie("index_passwd",trim($_POST['index_passwd']),time()+3600*24*7); echo '<meta http-equiv="refresh" content="0;url='.$_SERVER["REQUEST_URI"].'"> '; }else{ $Str_Msg_PSWERR="密码错误,请重新输入"; } } $plugin_optiosn = Typecho_Widget::widget('Widget_Options')->plugin('AllsitePasswd'); if(empty($_COOKIE["index_passwd"]) or trim($_POST['index_passwd'])!= Typecho_Widget::widget('Widget_Options')->plugin('AllsitePasswd')->str_Pword){ $html = file_get_contents(dirname(__FILE__) . '/theme/index.html'); // 替换内容 $template = str_replace( array( '{theme_base_path}', '{str_word}', '{url_pic}', '{err_msg}', '{form_action}', '{input_placeholder}', '{submit_text}', '{commic_pic}' ), array( Typecho_Common::url('AllsitePasswd/theme/', Helper::options()->pluginUrl), trim($plugin_optiosn->str_word), trim($plugin_optiosn->url_pic), trim($Str_Msg_PSWERR), trim($_SERVER["REQUEST_URI"]), trim($plugin_optiosn->placeholder), trim($plugin_optiosn->Submit), 'https://cloud.qqshabi.cn/api/images/api.php' ), $html ); die($template); ?> <!-- <!DOCTYPE html><html lang="en"><head><meta charset="UTF-8">--> <!-- <title>--><?php //echo htmlspecialchars(Typecho_Widget::widget('Widget_Options')->plugin('AllsitePasswd')->str_word)?><!--</title>--> <!-- <style>html {padding: 50px 10px;font-size: 16px;line-height: 1.4;color: #666;background: #F6F6F3;-webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%;}html,input { font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; }body {max-width: 500px;_width: 500px;padding: 30px 20px;margin: 0 auto;background: #FFF;}ul {padding: 0 0 0 40px;}.container {max-width: 380px;_width: 380px;margin: 0 auto;}</style>--> <!-- </head><body>--> <!-- <div class="container">--> <!-- <img src=" --><?php //echo htmlspecialchars(Typecho_Widget::widget('Widget_Options')->plugin('AllsitePasswd')->url_pic)?><!--" />--> <!-- <br>--> <!-- --><?php //echo Typecho_Widget::widget('Widget_Options')->plugin('AllsitePasswd')->str_word?> <!-- <br><span style="color:red">--><?php //echo $Str_Msg_PSWERR;?><!--</span><br>--> <!----> <!-- <form action="--><?php //echo $_SERVER["REQUEST_URI"];?><!--" method="post" >--> <!-- <input type="password" name="index_passwd" placeholder="--><?php //echo htmlspecialchars(Typecho_Widget::widget('Widget_Options')->plugin('AllsitePasswd')->placeholder)?><!--" /> --> <!-- --> <!-- <input type="submit" value="--><?php //echo htmlspecialchars(Typecho_Widget::widget('Widget_Options')->plugin('AllsitePasswd')->Submit)?><!--">--> <!-- </form>--> <!-- </div>--> <!-- </body></html>--> <?php //停止输出其他内容 exit(); }else{ //密码存在 什么都不做 } } /** * 禁用插件方法,如果禁用失败,直接抛出异常 * * @static * @access public * @return void * @throws Typecho_Plugin_Exception */ public static function deactivate(){} /** * 获取插件配置面板 * * @access public * @param Typecho_Widget_Helper_Form $form 配置面板 * @return void */ public static function config(Typecho_Widget_Helper_Form $form) { /** 分类名称 */ $str_word = new Typecho_Widget_Helper_Form_Element_Text('str_word', NULL, '网站已经启用全站加密,请输入密码访问', _t('提示文字')); $form->addInput($str_word); $placeholder = new Typecho_Widget_Helper_Form_Element_Text('placeholder', NULL, '输入密码查看精彩内容', _t('输入框提示')); $form->addInput($placeholder); $Submit = new Typecho_Widget_Helper_Form_Element_Text('Submit', NULL, '提交', _t('Submit按钮提示')); $form->addInput($Submit); $url_pic = new Typecho_Widget_Helper_Form_Element_Text('url_pic', NULL, 'http://typecho.org/usr/themes/bluecode/img/typecho-logo.svg', _t('提示图片')); $form->addInput($url_pic); $str_Pword = new Typecho_Widget_Helper_Form_Element_Text('str_Pword', NULL, '123456',_t('设置全站访问密码')); $form->addInput($str_Pword); //$enable_in_html = new Typecho_Widget_Helper_Form_Element_Radio('enable_in_html', array ('0' => '加密后内容依旧可以在html和搜索引擎中可见', '1' => '彻底隐藏数据'), '0', '是否完全隐藏内容:', ''); // $form->addInput($enable_in_html); } /** * 个人用户的配置面板 * * @access public * @param Typecho_Widget_Helper_Form $form * @return void */ public static function personalConfig(Typecho_Widget_Helper_Form $form){} /** * 插件实现方法 * * @access public * @return void */ public static function render() { echo '<a href="options-plugin.php?config=AllsitePasswd">全站密码</a>'; } }
661a192f9a0d7c294eb395aa50bf4b49b3c2a70a
[ "Markdown", "PHP" ]
2
Markdown
skytotwo/AllsitePasswd
11ec4229919c53a4ed00a55ca95cf2ece9b4152e
fd06cdd816260b4471193e6273e530fe99773353
refs/heads/master
<repo_name>LeleMeow/pythonTricks<file_sep>/README.md # pythonTricks A few tricks for Python
7ff178358dac78b34c1c3fc590c4c8efa558532f
[ "Markdown" ]
1
Markdown
LeleMeow/pythonTricks
a4723a20d61c44efb71b36f7e612adf994123047
23b2df963269bb4b68dfb055e8d447bb3fd7d8c5
refs/heads/master
<file_sep>ELM-C-- ======= Extreme Learning Machine - C++ library Implements linear ELM training and prediction facilities. Can be used both for classification and regression. Easy to include in an existing C++ project: plug and play. Single dependency: Eigen3 Matlab MEX interfaces for training and prediction are provided as well. <file_sep>load breast.mat %% cross-validation if 0 nhn_list = 1 : 10; C = 0.001; [trn vld] = cross_valid_ids( size(X,2), 10, [0.9 0.1 0] ); perf_valid = zeros( length(nhn_list), length(nhn_list) ); for hid = 1 : length(nhn_list) nhn = nhn_list(hid); for fid = 1 : 10 i = trn( :, fid ); j = vld( :, fid ); p = zeros(10,1); for rid = 1 : 10 [inW bias outW] = mexElmTrain( X(:,i), Y(i), nhn, C ); scores = mexElmPredict( inW, bias, outW, X(:,j) ); [~,Yhat] = max( scores, [], 1 ); p(rid) = sum( Yhat(:) == Y(j) ) / length(j); end perf_valid(fid,hid) = mean(p); end end surf( perf_valid ); end %% performance prediction nhn = 5; C = 1; [trn tst] = cross_valid_ids( size(X,2), 10, [0.9 0.1 0] ); perf_test = zeros( 1, 10 ); for fid = 1 : 10 i = trn( :, fid ); j = tst( :, fid ); p = zeros(10,1); for rid = 1 : 10 [inW bias outW] = mexElmTrain( X(:,i), Y(i), nhn, C ); scores = mexElmPredict( inW, bias, outW, X(:,j) ); [~,Yhat] = max( scores, [], 1 ); p(rid) = sum( Yhat(:) == Y(j) ) / length(j); end perf_test(fid) = mean(p); end <file_sep>// // Example generates some random data in the Eigen matrix and outputs it. // #include <Eigen/Core> #include <iostream> using namespace std; using namespace Eigen; int main() { const int nCols = 5; const int nRows = 4; MatrixXd X( nRows, nCols ); X.setRandom(); MatrixXd Y( nCols, nRows ); Y.setRandom(); MatrixXd Z = X.matrix() * Y.matrix(); cout << Z << endl; return 0; } <file_sep>#include <cmath> #include <iostream> using namespace std; // compare function int compare( const void *a, const void *b ) { double eps = 0.00000001; double diff = *(double *) a - *(double *) b; if ( abs(diff) <= eps ) return 0; if ( diff < 0 ) return -1; else return 1; } int main() { double d[10] = { 0.1, 5.3, 4.2, 1.1, 0.9, 6.5, 0.1, 7.0, 5.9, 2.4 }; qsort( d, 10, sizeof(double), compare ); for ( int i = 0 ; i < 10 ; i++ ) cout << d[i] << " "; cout << endl; return 0; } <file_sep>/******************************************************* A simple program that demonstrates the Eigen library. The program defines a random symmetric matrix and computes its eigendecomposition. For further details read the Eigen Reference Manual ********************************************************/ #include <stdlib.h> #include <time.h> #include <string.h> // the following two are needed for printing #include <iostream> #include <iomanip> /************************************** /* The Eigen include files */ #include <Eigen/Core> #include <Eigen/Eigenvalues> #include <Eigen/QR> /***************************************/ using namespace std; using namespace Eigen; int main(int argc, char **argv) { int M = 3, N = 5; MatrixXd X(M,N); // Define an M x N general matrix // Fill X by random numbers between 0 and 9 // Note that indexing into matrices in NewMat is 1-based! srand(time(NULL)); for (int i = 0; i < M; ++i) { for (int j = 0; j < N; ++j) { X(i,j) = rand() % 10; } } MatrixXd C; C = X * X.transpose(); // fill in C by X * X^t. cout << "The symmetrix matrix C" << endl; cout << C << endl; // compute eigendecomposition of C SelfAdjointEigenSolver<MatrixXd> es(C); MatrixXd D = es.eigenvalues().asDiagonal(); MatrixXd V = es.eigenvectors(); // Print the result cout << "The eigenvalues matrix:" << endl; cout << D << endl; cout << "The eigenvectors matrix:" << endl; cout << V << endl; // Check that the first eigenvector indeed has the eigenvector property VectorXd v1(3); v1(0) = V(0,0); v1(1) = V(1,0); v1(2) = V(2,0); VectorXd Cv1 = C * v1; VectorXd lambda1_v1 = D(0) * v1; cout << "The max-norm of the difference between C*v1 and lambda1*v1 is " << endl; cout << Cv1.cwiseMax(lambda1_v1) << endl << endl; // Build the inverse and check the result MatrixXd Ci = C.inverse(); MatrixXd I = Ci * C; cout << "The inverse of C is" << endl; cout << Ci << endl; cout << "And the inverse times C is identity" << endl; cout << I << endl; // Example for multiple solves VectorXd r1(3), r2(3); for (int i = 0; i < 3; ++i) { r1(i) = rand() % 10; r2(i) = rand() % 10; } ColPivHouseholderQR<MatrixXd> qr(C); // decomposes C VectorXd s1 = qr.solve(r1); VectorXd s2 = qr.solve(r2); cout << "solution for right hand side r1" << endl; cout << s1 << endl; cout << "solution for right hand side r2" << endl; cout << s2 << endl; return 0; } <file_sep>// // Example generates some random data in the Eigen matrix and outputs it. // #include <Eigen/Core> #include <iostream> using namespace std; using namespace Eigen; int main() { const int nCols = 5; const int nRows = 4; MatrixXd X( nRows, nCols ); X.setRandom(); cout << X << endl; return 0; } <file_sep>// // This example demonstrates the usage of Map in Eigen framework. // User-provided data is used to populate a Eigen matrix. // #include <Eigen/Core> #include <iostream> using namespace Eigen; using namespace std; int main() { // user data double data[6] = { 1, 2, 3, 4, 5 , 6 }; // creating a 3x2 matrix from user data MatrixXd mat = Map<MatrixXd>( data, 3, 2 ); // output it to see what is inside cout << mat << endl; return 0; }
967fa2d063e30dee74eec0e2f10063537749e8da
[ "Markdown", "C++", "MATLAB" ]
7
Markdown
xjsxujingsong/ELM-C--
4a0a4d809f31bb32916b1a26de704c8ed72ae0d2
199fe1238f2d84226d3f479d3038f7d9eea4c21c
refs/heads/master
<file_sep>### Project Overview Project on Sentiment Analysis-Part 2 ### Learnings from the project I learnt various methods like doc2bow(),pprint methods and ho to use it. ### Approach taken to solve the problem Firstly look at whats given in the question then break it into parts and start solving. ### Challenges faced Some methods like doc2bow were tough to understand. ### Additional pointers No
f6c71e15f06a024e8dc2348c9c9fbe99e6e669d6
[ "Markdown" ]
1
Markdown
praks802/domain-classification-text
9407bf5198061d314739c1ac38fb8363fa42dfb7
d9a8138bff3d3ae84a5871b4c898e23c0bd4affe
refs/heads/main
<repo_name>Dr-Asim/Plant-Disease-Detection<file_sep>/README.md # Fruit trees and Vegetable Plant Leaf Disease Detection and Classification The repository contain a source code for the Training and Testing process. Two type of datasets, the PlantVillage and local field images has been used for the training and testing of models. The dataset of PlantVillage was collected from the open source platform known as Kaggle. While, the local field images were collected from the farms of Tarnab. The sample images are presented in the sub-folder named as Tarnab-Images. A research paper has also been published and sent for the peer-review process in the journal of PLOS. The paper explained all the obtained results for different data splits. The link for paper is given below. ## Link for PlantVillage Dataset https://www.kaggle.com/abdallahalidev/plantvillage-dataset/version/1 ## Link for Research Paper https://www.preprints.org/manuscript/202009.0142/v3 ## For Citation <NAME>.; <NAME>.; <NAME>.;<NAME>.; <NAME>. Real-Time Plant Health Assessment via implementing Cloud-Based Scalable Transfer Learning on AWS DeepLens. Preprints 2020, 2020090142 (doi: 10.20944/preprints202009.0142.v3).
6ac788e74bef087cd9d959feb2b04c666a4a8880
[ "Markdown" ]
1
Markdown
Dr-Asim/Plant-Disease-Detection
3355de95b592014bb107198cd180b92869f4a64f
9c0d9ebada3d28c63f7c2a0ec2111715e4dd0715
refs/heads/master
<file_sep>package kafka.streams.sample.stream.global; import java.util.Properties; import kafka.streams.sample.avro.Order; import kafka.streams.sample.avro.User; import kafka.streams.sample.serde.MySerdes; import kafka.streams.sample.stream.SampleStreams; import org.apache.kafka.common.serialization.Serdes; import org.apache.kafka.common.utils.Bytes; import org.apache.kafka.streams.StreamsBuilder; import org.apache.kafka.streams.Topology; import org.apache.kafka.streams.kstream.Consumed; import org.apache.kafka.streams.kstream.GlobalKTable; import org.apache.kafka.streams.kstream.KStream; import org.apache.kafka.streams.kstream.Materialized; import org.apache.kafka.streams.kstream.Printed; import org.apache.kafka.streams.kstream.Produced; import org.apache.kafka.streams.state.KeyValueStore; public class GlobalTableStreams implements SampleStreams { private final Properties props; private final StreamsBuilder builder; private static final String MY_USER_ORDER_TOPIC = "my-user-order"; public static final String MY_GLOBAL_USERS = "my-global-users"; public static final String MY_GLOBAL_USERS_STORE = "my-global-users-store"; public static final String MY_ORDER_TOPIC = "my-order"; public GlobalTableStreams(GlobalTableConfig config) { this.props = config.getProps(); this.builder = new StreamsBuilder(); } @Override public Topology createTopology() { final KStream<String, Order> orders = this.builder.stream(MY_ORDER_TOPIC, Consumed.with(Serdes.String(), MySerdes.ORDER_SERDE)); final GlobalKTable<Long, User> users = this.builder.globalTable( MY_GLOBAL_USERS, Materialized.<Long, User, KeyValueStore<Bytes, byte[]>>as(MY_GLOBAL_USERS_STORE) .withKeySerde(Serdes.Long()) .withValueSerde(MySerdes.USER_SERDE)); final KStream<String, String> userOrders = orders.join( users, (orderId, order) -> order.getUserId(), (order, user) -> order.getState() + ":" + user.getName()); userOrders.print(Printed.toSysOut()); userOrders.to(MY_USER_ORDER_TOPIC, Produced.with(Serdes.String(), Serdes.String())); return this.builder.build(this.props); } @Override public Properties getProperties() { return this.props; } } <file_sep>package kafka.streams.sample.stream.event.processor; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import kafka.streams.sample.stream.event.Store; import kafka.streams.sample.stream.event.Utils; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.apache.kafka.streams.KeyValue; import org.apache.kafka.streams.kstream.Windowed; import org.apache.kafka.streams.processor.Processor; import org.apache.kafka.streams.processor.ProcessorContext; import org.apache.kafka.streams.processor.PunctuationType; import org.apache.kafka.streams.state.WindowStore; @Slf4j public class AggregationByUserIdProcessor implements Processor<Long, Long> { private ProcessorContext context; private WindowStore<Long, Long> store; private static final int INTERVAL_SECONDS = 30; @Override @SuppressWarnings("unchecked") public void init(ProcessorContext context) { this.store = (WindowStore<Long, Long>) context.getStateStore(Store.USER_ID_AGGREGATION.getName()); this.context = context; this.context.schedule( Duration.ofSeconds(INTERVAL_SECONDS), PunctuationType.WALL_CLOCK_TIME, (timestamp) -> { log.info( "schedule every {} sec: {}", INTERVAL_SECONDS, Utils.getLocalDateTime(timestamp)); val fromTime = Instant.ofEpochMilli(timestamp).truncatedTo(ChronoUnit.DAYS); val iter = this.store.fetchAll(fromTime.toEpochMilli(), timestamp); while (iter.hasNext()) { KeyValue<Windowed<Long>, Long> entry = iter.next(); log.info( "key: {}, value: {}, window: {}", entry.key.key(), entry.value, entry.key.window().startTime()); this.context.forward(entry.key.key(), entry.value); } iter.close(); this.context.commit(); log.info("--------------------------------"); }); } @Override public void process(Long key, Long value) { log.info("got key: {}, value: {}", key, value); val timestamp = this.context.timestamp(); val date = Instant.ofEpochMilli(timestamp).truncatedTo(ChronoUnit.DAYS).toEpochMilli(); Long aggregate = this.store.fetch(key, date); if (aggregate == null) { aggregate = 0L; } this.store.put(key, aggregate + value, date); } @Override public void close() { // nothing to do } } <file_sep>package kafka.streams.sample.stream.event; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import lombok.val; public class Utils { private Utils() { throw new IllegalStateException("utility class"); } public static final ZoneId UTC = ZoneId.of("UTC"); public static final ZoneId ASIA_TOKYO = ZoneId.of("Asia/Tokyo"); public static LocalDateTime getLocalDateTime(Instant time) { return time.atZone(ASIA_TOKYO).toLocalDateTime(); } public static String getLocalDateTime(long timestamp) { val dt = getLocalDateTime(Instant.ofEpochMilli(timestamp)); return dt.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME); } } <file_sep>package kafka.streams.sample.processor; import kafka.streams.sample.avro.User; import org.apache.kafka.common.serialization.Serializer; import org.apache.kafka.common.serialization.StringSerializer; import org.apache.kafka.common.utils.Utils; import org.apache.kafka.streams.processor.StreamPartitioner; public class UserPatitioner implements StreamPartitioner<Long, User> { private static final Serializer<String> SERIALIZER = new StringSerializer(); @Override public Integer partition(String topic, Long key, User value, int numPartitions) { final byte[] keyBytes = SERIALIZER.serialize(topic, value.getName()); return Utils.toPositive(Utils.murmur2(keyBytes)) % numPartitions; } } <file_sep>package kafka.streams.sample.producer; import io.confluent.kafka.serializers.AbstractKafkaSchemaSerDeConfig; import io.confluent.kafka.serializers.KafkaAvroSerializer; import java.security.SecureRandom; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.Random; import kafka.streams.sample.avro.User; import kafka.streams.sample.stream.Constant; import kafka.streams.sample.stream.user.UserStreams; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.common.serialization.LongSerializer; @Slf4j public class OldUserProducer { private final Properties props; private final Random rand; private Properties createProperties() { val p = new Properties(); p.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, Constant.BOOTSTRAP_SERVERS); p.put(ProducerConfig.ACKS_CONFIG, "all"); p.put(ProducerConfig.RETRIES_CONFIG, 0); p.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, LongSerializer.class.getName()); p.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, KafkaAvroSerializer.class.getName()); p.put(AbstractKafkaSchemaSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG, Constant.SCHEMA_REGISTRY_URL); return p; } public OldUserProducer() { this.props = this.createProperties(); this.rand = new SecureRandom(); } private User createUser(long userId, String name, String email) { val loggedIn = userId % 2 == 0; val age = this.rand.nextInt(80); return new User(userId, name, email, loggedIn, age); } private List<User> createUsers(long n) { val users = new ArrayList<User>((int) n); for (long i = 0; i < n; i++) { val userId = i; val name = "user" + userId; val email = name + "@example.com"; users.add(this.createUser(userId, name, email)); } return users; } public void publishUserInternal( KafkaProducer<Long, User> producer, long userId, String name, String email) throws InterruptedException { val user = this.createUser(userId, name, email); val record = new ProducerRecord<Long, User>(UserStreams.USER_TOPIC, userId, user); producer.send(record); log.info(String.format("sent record: %s", user.toString())); Thread.sleep(100L); producer.flush(); } public void publishUser(long userId, String name, String email) { try (val producer = new KafkaProducer<Long, User>(this.props)) { this.publishUserInternal(producer, userId, name, email); } catch (InterruptedException e) { log.warn("sleeping is interrupted: {}", e.getMessage()); Thread.currentThread().interrupt(); } } public void publishUsers(long n) { try (val producer = new KafkaProducer<Long, User>(this.props)) { for (val user : this.createUsers(n)) { val record = new ProducerRecord<Long, User>(UserStreams.USER_TOPIC, user.getId(), user); producer.send(record); log.info(String.format("sent record: %s", user.toString())); } Thread.sleep(100L); producer.flush(); log.info(String.format("sent %d users", n)); } catch (InterruptedException e) { log.warn("sleeping is interrupted: {}", e.getMessage()); Thread.currentThread().interrupt(); } } } <file_sep>package kafka.streams.sample.producer; import java.time.Instant; import java.util.Random; import kafka.streams.sample.avro.Event; import kafka.streams.sample.avro.EventType; import kafka.streams.sample.serde.MySerdes; import kafka.streams.sample.stream.event.Topic; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.common.serialization.StringSerializer; @Slf4j public class EventProducer extends AbstractProducer { public EventProducer() { super(); this.props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); this.props.put( ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, MySerdes.EVENT_SERDE.serializer().getClass()); } private EventType getEventType(int id) { if (id % 3 == 0) { return EventType.VIEW; } else if (id % 3 == 1) { return EventType.STOCK; } else { return EventType.BUY; } } private Event createEvent() { val userId = new Random().nextInt(8); val customId = new Random().nextInt(1024); val type = this.getEventType(userId); return Event.newBuilder() .setUserId(userId) .setCustomId(customId) .setType(type) .setAction("some") .setCreatedAt(Instant.now()) .build(); } @Override public void run() { try (val producer = new KafkaProducer<String, Event>(this.props)) { while (true) { val key = this.createKey(); val value = this.createEvent(); val record = new ProducerRecord<String, Event>(Topic.MY_EVENT.getName(), key, value); producer.send(record); producer.flush(); log.info("sent event: {}", value); Thread.sleep(1000L); } } catch (InterruptedException e) { log.warn("sleeping is interrupted: {}", e.getMessage()); Thread.currentThread().interrupt(); } } public static void main(String[] args) { val producer = new EventProducer(); producer.run(); } } <file_sep>package kafka.streams.sample.stream.event.processor; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.apache.kafka.streams.processor.Processor; import org.apache.kafka.streams.processor.ProcessorContext; @Slf4j public class UserIdRepartitionProcessor implements Processor<String, Long> { private ProcessorContext context; @Override public void init(ProcessorContext context) { this.context = context; } @Override public void process(String key, Long value) { val userId = Long.valueOf(key.split("_")[0]); this.context.forward(userId, value); } @Override public void close() { // nothing to do } } <file_sep>package kafka.streams.sample.serde; import io.confluent.kafka.serializers.AbstractKafkaSchemaSerDeConfig; import java.util.Map; import kafka.streams.sample.stream.Constant; import lombok.val; public class MySerdes { private MySerdes() { throw new IllegalStateException("utility class"); } private static final Map<String, String> SERDE_CONFIG = Map.of( AbstractKafkaSchemaSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG, Constant.SCHEMA_REGISTRY_URL); public static final EventSerde EVENT_SERDE = getEventSerde(); public static final OrderSerde ORDER_SERDE = getOrderSerde(); public static final UserSerde USER_SERDE = getUserSerde(); private static EventSerde getEventSerde() { val eventSerde = new EventSerde(); eventSerde.configure(SERDE_CONFIG, false); return eventSerde; } private static OrderSerde getOrderSerde() { val orderSerde = new OrderSerde(); orderSerde.configure(SERDE_CONFIG, false); return orderSerde; } private static UserSerde getUserSerde() { val userSerde = new UserSerde(); userSerde.configure(SERDE_CONFIG, false); return userSerde; } } <file_sep>plugins { id 'application' id 'java' id 'com.commercehub.gradle.plugin.avro' version '0.20.0' id 'com.github.sherter.google-java-format' version '0.9' } java { toolchain { languageVersion.set(JavaLanguageVersion.of(11)) } } repositories { mavenCentral() jcenter() maven { url = 'https://packages.confluent.io/maven/' } } dependencies { // for type inference annotationProcessor 'org.projectlombok:lombok:1.18.16' compileOnly 'org.projectlombok:lombok:1.18.16' testAnnotationProcessor 'org.projectlombok:lombok:1.18.16' testCompileOnly 'org.projectlombok:lombok:1.18.16' // for logging implementation 'ch.qos.logback:logback-classic:1.2.3' implementation 'org.slf4j:slf4j-api:1.7.30' // kafka and kafka streams implementation 'org.apache.kafka:kafka-streams:2.6.0' implementation 'org.apache.kafka:kafka-clients:2.6.0' testImplementation 'org.apache.kafka:kafka-streams-test-utils:2.6.0' // kafka streams examples implementation 'org.apache.kafka:kafka-streams-examples:2.6.0' // avro implementation 'org.apache.avro:avro:1.10.1' implementation 'io.confluent:kafka-streams-avro-serde:6.0.1' implementation 'io.confluent:kafka-avro-serializer:6.0.1' // others implementation 'com.google.guava:guava:30.1-jre' testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0' } application { mainClassName = 'kafka.streams.sample.stream.user.UserStreamsMain' } compileJava.dependsOn tasks.googleJavaFormat test { useJUnitPlatform() if (System.getProperty('DEBUG', 'false') == 'true') { jvmArgs '-Xdebug', '-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005' } } avro { dateTimeLogicalType = 'JSR310' createOptionalGetters = true } tasks.withType(JavaExec) { jvmArgs '--add-opens', 'java.base/java.lang=ALL-UNNAMED' if (System.getProperty('DEBUG', 'false') == 'true') { jvmArgs '-Xdebug', '-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005' } } // streams task runEventStreamsDSL(type: JavaExec) { group = 'Execution' description = 'Run event streams main class' classpath = sourceSets.main.runtimeClasspath main = 'kafka.streams.sample.stream.event.dsl.EventStreamsMain' } task runEventStreamsProcessor(type: JavaExec) { group = 'Execution' description = 'Run event streams main class' classpath = sourceSets.main.runtimeClasspath main = 'kafka.streams.sample.stream.event.processor.EventStreamsMain' } task runStream(type: JavaExec) { group = 'Execution' description = 'Run SampleStreams main class' classpath = sourceSets.main.runtimeClasspath main = 'kafka.streams.sample.stream.StreamsMain' } // producers task runEventProducer(type: JavaExec) { group = 'Execution' description = 'Run event producer main class' classpath = sourceSets.main.runtimeClasspath main = 'kafka.streams.sample.producer.EventProducer' } task runOrderProducer(type: JavaExec) { group = 'Execution' description = 'Run order producer main class' classpath = sourceSets.main.runtimeClasspath main = 'kafka.streams.sample.producer.OrderProducer' } task runUserProducer(type: JavaExec) { group = 'Execution' description = 'Run user producer main class' classpath = sourceSets.main.runtimeClasspath main = 'kafka.streams.sample.producer.UserProducer' } // consumers task runUserConsumer(type: JavaExec) { group = 'Execution' description = 'Run user consumer main class' classpath = sourceSets.main.runtimeClasspath main = 'kafka.streams.sample.consumer.UserConsumer' } // to be refactored task runProducer(type: JavaExec) { group = 'Execution' description = 'Run producer main class' classpath = sourceSets.main.runtimeClasspath main = 'kafka.streams.sample.cli.ProducerMain' } task runConsumer(type: JavaExec) { group = 'Execution' description = 'Run consumer main class' classpath = sourceSets.main.runtimeClasspath main = 'kafka.streams.sample.cli.ConsumerMain' } <file_sep>package kafka.streams.sample.stream; import java.util.Properties; import org.apache.kafka.streams.Topology; public interface SampleStreams { Topology createTopology(); Properties getProperties(); } <file_sep>package kafka.streams.sample.stream.event; import org.apache.kafka.streams.processor.StreamPartitioner; public class ChunkNumPartitioner implements StreamPartitioner<String, Long> { public Integer partition(String topic, String key, Long value, int numPartitions) { return Integer.valueOf(key.split("_")[1]) % numPartitions; } } <file_sep>package kafka.streams.sample.processor; import kafka.streams.sample.avro.User; import kafka.streams.sample.stream.global.GlobalTableStreams; import lombok.extern.slf4j.Slf4j; import org.apache.kafka.streams.processor.Processor; import org.apache.kafka.streams.processor.ProcessorContext; import org.apache.kafka.streams.state.KeyValueStore; @Slf4j public class GlobalUserProcessor implements Processor<Long, User> { private ProcessorContext context; private KeyValueStore<Long, User> store; @Override @SuppressWarnings("unchecked") public void init(ProcessorContext context) { this.context = context; this.store = (KeyValueStore<Long, User>) this.context.getStateStore(GlobalTableStreams.MY_GLOBAL_USERS_STORE); } @Override public synchronized void process(Long key, User value) { log.info("called process: key: {}, value: {}", key, value); this.store.put(key, value); } @Override public void close() { // nothing to do } } <file_sep>package kafka.streams.sample.stream.event.dsl; import com.google.common.annotations.VisibleForTesting; import java.time.Duration; import java.util.Properties; import kafka.streams.sample.avro.Event; import kafka.streams.sample.serde.MySerdes; import kafka.streams.sample.stream.event.ChunkNumPartitioner; import kafka.streams.sample.stream.event.EventStreamsConfig; import kafka.streams.sample.stream.event.Store; import kafka.streams.sample.stream.event.Topic; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.apache.kafka.common.serialization.Serdes; import org.apache.kafka.common.utils.Bytes; import org.apache.kafka.streams.StreamsBuilder; import org.apache.kafka.streams.Topology; import org.apache.kafka.streams.kstream.Consumed; import org.apache.kafka.streams.kstream.Grouped; import org.apache.kafka.streams.kstream.KStream; import org.apache.kafka.streams.kstream.Materialized; import org.apache.kafka.streams.kstream.Produced; import org.apache.kafka.streams.kstream.Suppressed; import org.apache.kafka.streams.kstream.Suppressed.BufferConfig; import org.apache.kafka.streams.kstream.TimeWindows; import org.apache.kafka.streams.state.WindowStore; @Slf4j public class EventStreams { private final Properties props; private final StreamsBuilder builder; public EventStreams(EventStreamsConfig config) { this.props = config.getProps(); this.builder = new StreamsBuilder(); } @VisibleForTesting void buildEventAggregation(KStream<String, Event> source) { KStream<String, Long> aggregated = source .groupBy( (key, value) -> { val chunkNum = String.valueOf(value.getCustomId() % 4); return String.format("%d_%s", value.getUserId(), chunkNum); }, Grouped.with(Serdes.String(), MySerdes.EVENT_SERDE)) .windowedBy(TimeWindows.of(Duration.ofSeconds(10)).grace(Duration.ofSeconds(1))) .aggregate( () -> 0L, (key, value, aggregate) -> { Long total = aggregate; switch (value.getType()) { case VIEW: case STOCK: total += 2; break; case BUY: total += 10; break; default: total += 1; break; } return total; }, Materialized.<String, Long, WindowStore<Bytes, byte[]>>as( Store.CHUNK_NUM_AGGREGATION.getName()) .withKeySerde(Serdes.String()) .withValueSerde(Serdes.Long())) .suppress(Suppressed.untilWindowCloses(BufferConfig.unbounded())) .toStream((windowedKey, value) -> windowedKey.key()); aggregated.process(MyQueueProcessor::new); aggregated.to( Topic.MY_QUEUE.getName(), Produced.with(Serdes.String(), Serdes.Long()) .withStreamPartitioner(new ChunkNumPartitioner())); } @VisibleForTesting void buildAggregationByUserId(KStream<String, Long> source) { Materialized<Long, Long, WindowStore<Bytes, byte[]>> materialized = Materialized.<Long, Long, WindowStore<Bytes, byte[]>>as(Store.USER_ID_AGGREGATION.getName()) .withKeySerde(Serdes.Long()) .withValueSerde(Serdes.Long()); KStream<Long, Long> aggregated = source .groupBy( (key, value) -> Long.valueOf(key.split("_")[0]), Grouped.with(Serdes.Long(), Serdes.Long())) .windowedBy(TimeWindows.of(Duration.ofDays(1))) .aggregate(() -> 0L, (key, value, aggregate) -> value + aggregate, materialized) .toStream((windowedKey, value) -> windowedKey.key()); aggregated.to(Topic.MY_AGGREGATION.getName(), Produced.with(Serdes.Long(), Serdes.Long())); } @VisibleForTesting Topology createTopology() { KStream<String, Event> event = this.builder.stream( Topic.MY_EVENT.getName(), Consumed.with(Serdes.String(), MySerdes.EVENT_SERDE) .withName(Topic.MY_EVENT.getName())); KStream<String, Long> queue = this.builder.stream( Topic.MY_QUEUE.getName(), Consumed.with(Serdes.String(), Serdes.Long()).withName(Topic.MY_QUEUE.getName())); KStream<Long, Long> aggregation = this.builder.stream( Topic.MY_AGGREGATION.getName(), Consumed.with(Serdes.Long(), Serdes.Long()).withName(Topic.MY_AGGREGATION.getName())); this.buildEventAggregation(event); this.buildAggregationByUserId(queue); aggregation.process(MyAggregationProcessor::new); val topology = builder.build(this.props); return topology; } } <file_sep>package kafka.streams.sample.stream.event.dsl; import lombok.extern.slf4j.Slf4j; import org.apache.kafka.streams.processor.Processor; import org.apache.kafka.streams.processor.ProcessorContext; @Slf4j public class MyAggregationProcessor implements Processor<Long, Long> { @Override public void init(ProcessorContext context) { // nothing to do } @Override public void process(Long key, Long value) { log.info("userId: {}, aggregatedValue: {}", key, value); } @Override public void close() { // nothing to do } } <file_sep>package kafka.streams.sample.serde; import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde; import kafka.streams.sample.avro.Order; public class OrderSerde extends SpecificAvroSerde<Order> {} <file_sep>package kafka.streams.sample.stream.global; import io.confluent.kafka.serializers.AbstractKafkaSchemaSerDeConfig; import io.confluent.kafka.serializers.KafkaAvroDeserializerConfig; import java.util.Properties; import kafka.streams.sample.stream.Constant; import lombok.Getter; import lombok.ToString; import lombok.val; import org.apache.kafka.common.serialization.Serdes; import org.apache.kafka.streams.StreamsConfig; @Getter @ToString public class GlobalTableConfig { private static final String APPLICATION_ID = "global-table-stremas"; private final Properties props; public GlobalTableConfig() { this.props = this.createProperties(); } private Properties createProperties() { val p = new Properties(); p.put(StreamsConfig.APPLICATION_ID_CONFIG, APPLICATION_ID); p.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, Constant.BOOTSTRAP_SERVERS); p.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass()); p.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass()); p.put(StreamsConfig.NUM_STREAM_THREADS_CONFIG, 2); p.put(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG, 3000); p.put(KafkaAvroDeserializerConfig.SPECIFIC_AVRO_READER_CONFIG, true); p.put(StreamsConfig.REPLICATION_FACTOR_CONFIG, "1"); p.put(AbstractKafkaSchemaSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG, Constant.SCHEMA_REGISTRY_URL); return p; } void setBootstrapServer(String servers) { this.props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, servers); } } <file_sep>package kafka.streams.sample.stream; public class Constant { private Constant() { throw new IllegalStateException("utility class"); } public static final String BOOTSTRAP_SERVERS = "localhost:9092"; public static final String SCHEMA_REGISTRY_URL = "http://localhost:8081"; } <file_sep># kafka-streams-sample Kafka Streams sample code ## How to build/run Start kafka broker and schema registry servers on localhost. ### EventStreams #### Use Processor API ```bash $ ./gradlew runEventStreamsProcessor ``` ``` Topologies: Sub-topology: 0 Source: my-event (topics: [my-event]) --> EventAggregationProcessor Processor: EventAggregationProcessor (stores: [chunk-num-aggregation]) --> my-queue-sink <-- my-event Sink: my-queue-sink (topic: my-queue) <-- EventAggregationProcessor Sub-topology: 1 Source: my-queue (topics: [my-queue]) --> UserIdRepartitionProcessor Processor: UserIdRepartitionProcessor (stores: []) --> my-repartition-sink <-- my-queue Sink: my-repartition-sink (topic: my-repartition) <-- UserIdRepartitionProcessor Sub-topology: 2 Source: my-repartition (topics: [my-repartition]) --> AggregationByUserIdProcessor Processor: AggregationByUserIdProcessor (stores: [user-id-aggregation]) --> my-aggregation-sink <-- my-repartition Sink: my-aggregation-sink (topic: my-aggregation) <-- AggregationByUserIdProcessor ``` #### Use Streams DSL ```bash $ ./gradlew runEventStreamsDSL ``` Topologies ``` Topologies: Sub-topology: 0 Source: my-event (topics: [my-event]) --> KSTREAM-KEY-SELECT-0000000003 Processor: KSTREAM-KEY-SELECT-0000000003 (stores: []) --> chunk-num-aggregation-repartition-filter <-- my-event Processor: chunk-num-aggregation-repartition-filter (stores: []) --> chunk-num-aggregation-repartition-sink <-- KSTREAM-KEY-SELECT-0000000003 Sink: chunk-num-aggregation-repartition-sink (topic: chunk-num-aggregation-repartition) <-- chunk-num-aggregation-repartition-filter Sub-topology: 1 Source: my-queue (topics: [my-queue]) --> KSTREAM-KEY-SELECT-0000000011 Processor: KSTREAM-KEY-SELECT-0000000011 (stores: []) --> user-id-aggregation-repartition-filter <-- my-queue Processor: user-id-aggregation-repartition-filter (stores: []) --> user-id-aggregation-repartition-sink <-- KSTREAM-KEY-SELECT-0000000011 Sink: user-id-aggregation-repartition-sink (topic: user-id-aggregation-repartition) <-- user-id-aggregation-repartition-filter Sub-topology: 2 Source: my-aggregation (topics: [my-aggregation]) --> KSTREAM-PROCESSOR-0000000019 Processor: KSTREAM-PROCESSOR-0000000019 (stores: []) --> none <-- my-aggregation Sub-topology: 3 Source: chunk-num-aggregation-repartition-source (topics: [chunk-num-aggregation-repartition]) --> KSTREAM-AGGREGATE-0000000004 Processor: KSTREAM-AGGREGATE-0000000004 (stores: [chunk-num-aggregation]) --> KTABLE-TOSTREAM-0000000008 <-- chunk-num-aggregation-repartition-source Processor: KTABLE-TOSTREAM-0000000008 (stores: []) --> KSTREAM-KEY-SELECT-0000000009 <-- KSTREAM-AGGREGATE-0000000004 Processor: KSTREAM-KEY-SELECT-0000000009 (stores: []) --> KSTREAM-SINK-0000000010 <-- KTABLE-TOSTREAM-0000000008 Sink: KSTREAM-SINK-0000000010 (topic: my-queue) <-- KSTREAM-KEY-SELECT-0000000009 Sub-topology: 4 Source: user-id-aggregation-repartition-source (topics: [user-id-aggregation-repartition]) --> KSTREAM-AGGREGATE-0000000012 Processor: KSTREAM-AGGREGATE-0000000012 (stores: [user-id-aggregation]) --> KTABLE-TOSTREAM-0000000016 <-- user-id-aggregation-repartition-source Processor: KTABLE-TOSTREAM-0000000016 (stores: []) --> KSTREAM-KEY-SELECT-0000000017 <-- KSTREAM-AGGREGATE-0000000012 Processor: KSTREAM-KEY-SELECT-0000000017 (stores: []) --> KSTREAM-SINK-0000000018 <-- KTABLE-TOSTREAM-0000000016 Sink: KSTREAM-SINK-0000000018 (topic: my-aggregation) <-- KSTREAM-KEY-SELECT-0000000017 ``` ### GlobalTableStreams ```bash $ ./gradlew --info runStream --args='GlobalTableStreams' ``` ``` Topologies: Sub-topology: 0 Source: KSTREAM-SOURCE-0000000000 (topics: [my-order]) --> KSTREAM-LEFTJOIN-0000000003 Processor: KSTREAM-LEFTJOIN-0000000003 (stores: []) --> KSTREAM-PRINTER-0000000004, KSTREAM-SINK-0000000005 <-- KSTREAM-SOURCE-0000000000 Processor: KSTREAM-PRINTER-0000000004 (stores: []) --> none <-- KSTREAM-LEFTJOIN-0000000003 Sink: KSTREAM-SINK-0000000005 (topic: my-user-order) <-- KSTREAM-LEFTJOIN-0000000003 Sub-topology: 1 for global store (will not generate tasks) Source: KSTREAM-SOURCE-0000000001 (topics: [my-global-users]) --> KTABLE-SOURCE-0000000002 Processor: KTABLE-SOURCE-0000000002 (stores: [my-global-users-store]) --> none <-- KSTREAM-SOURCE-0000000001 ``` ## How to run producer ### for EventStreams To send records for EventStreams into kafka, run like this. ```bash $ ./gradlew runEventProducer ... 10:56:08.849 [main] INFO k.s.sample.producer.EventProducer - sent event: {"user_id": 6, "action": "some", "type": "VIEW", "created_at": 2020-07-31T01:56:08.846Z} 10:56:09.851 [main] INFO k.s.sample.producer.EventProducer - sent event: {"user_id": 4, "action": "some", "type": "STOCK", "created_at": 2020-07-31T01:56:09.850Z} ... ``` ### for GlobalTableStreams Send user info for Global Table. ```bash $ ./gradlew runUserProducer ``` Send order messages to join Global Table (user). ```bash $ ./gradlew runOrderProducer ``` ## How to run consumer ### for GlobalTableStreams ```bash $ ./gradlew runUserConsumer ``` ## Reference * https://kafka.apache.org/documentation/streams/ * https://docs.confluent.io/current/schema-registry/index.html * https://docs.confluent.io/current/streams/code-examples.html * https://github.com/confluentinc/kafka-streams-examples <file_sep>package kafka.streams.sample.cli; import kafka.streams.sample.consumer.OldUserConsumer; import kafka.streams.sample.env.EnvVar; import lombok.extern.slf4j.Slf4j; import lombok.val; @Slf4j public class ConsumerMain { public static void main(String[] args) { log.info("ConsumerMain start"); val consumer = new OldUserConsumer(); consumer.pool(EnvVar.WITH_ASYNC.getBoolValue()); log.info("ConsumerMain end"); } } <file_sep>package kafka.streams.sample.cli; import kafka.streams.sample.env.EnvVar; import kafka.streams.sample.producer.OldUserProducer; import lombok.extern.slf4j.Slf4j; import lombok.val; @Slf4j public class ProducerMain { public static void main(String[] args) { log.info("ProducerMain start"); val producer = new OldUserProducer(); val userNums = EnvVar.USER_NUMS.getLongValue(); if (userNums.longValue() == 0) { producer.publishUser( EnvVar.USER_ID.getLongValue(), EnvVar.USER_NAME.getValue(), EnvVar.USER_EMAIL.getValue()); } else { producer.publishUsers(userNums); } log.info("ProducerMain end"); } } <file_sep>package kafka.streams.sample.producer; import io.confluent.kafka.serializers.AbstractKafkaSchemaSerDeConfig; import java.security.SecureRandom; import java.util.Properties; import java.util.Random; import java.util.UUID; import kafka.streams.sample.stream.Constant; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.apache.kafka.clients.producer.ProducerConfig; @Slf4j public abstract class AbstractProducer { protected final Properties props; protected final Random rand; protected AbstractProducer() { this.props = this.createProperties(); this.rand = new SecureRandom(); } protected Properties createProperties() { val p = new Properties(); p.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, Constant.BOOTSTRAP_SERVERS); p.put(ProducerConfig.ACKS_CONFIG, "all"); p.put(ProducerConfig.RETRIES_CONFIG, 0); p.put(AbstractKafkaSchemaSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG, Constant.SCHEMA_REGISTRY_URL); return p; } protected String createKey() { val uuid = UUID.randomUUID(); return uuid.toString(); } public abstract void run(); } <file_sep>package kafka.streams.sample.stream.event; import com.google.common.base.CaseFormat; public enum Topic { MY_EVENT, MY_QUEUE, MY_REPARTITION, MY_AGGREGATION; private final String topicName; Topic() { this.topicName = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_HYPHEN, this.name()); } public String getName() { return this.topicName; } } <file_sep>package kafka.streams.sample.stream.event.processor; import java.util.concurrent.CountDownLatch; import kafka.streams.sample.stream.event.EventStreamsConfig; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.apache.kafka.streams.KafkaStreams; @Slf4j public class EventStreamsMain { public static void main(String[] args) { log.info("start"); val config = new EventStreamsConfig(); val eventStreams = new EventStreams(config); val topology = eventStreams.createTopology(); log.info("\n{}", topology.describe()); val streams = new KafkaStreams(topology, config.getProps()); val latch = new CountDownLatch(1); // attach shutdown handler to catch control-c Runtime.getRuntime() .addShutdownHook( new Thread("streams-shutdown-hook") { @Override public void run() { streams.close(); latch.countDown(); } }); try { streams.start(); latch.await(); } catch (Exception e) { System.exit(1); } log.info("end"); System.exit(0); } } <file_sep>package kafka.streams.sample.processor; import java.time.Duration; import kafka.streams.sample.stream.user.UserStreams; import kafka.streams.sample.util.DateTimeUtil; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.apache.kafka.streams.processor.Processor; import org.apache.kafka.streams.processor.ProcessorContext; import org.apache.kafka.streams.processor.PunctuationType; import org.apache.kafka.streams.state.KeyValueStore; @Slf4j public class PrintUserProcessor implements Processor<String, Long> { private static final long SCHEDULE_DURATION_SEC = 10; private ProcessorContext context; private KeyValueStore<String, Long> store; @Override @SuppressWarnings("unchecked") public void init(ProcessorContext context) { log.info("called init()"); this.context = context; this.store = (KeyValueStore<String, Long>) this.context.getStateStore(UserStreams.STORE_COUNTS); this.context.schedule( Duration.ofSeconds(SCHEDULE_DURATION_SEC), PunctuationType.STREAM_TIME, timestamp -> { log.info("called context.schedule(): {}", DateTimeUtil.getLocalDateTime(timestamp)); try (val iter = this.store.all()) { while (iter.hasNext()) { val kv = iter.next(); log.info(" - " + kv.toString()); } } this.context.commit(); }); } @Override public synchronized void process(String key, Long value) { log.info("called process(): {}, {}", key, value.toString()); var count = this.store.putIfAbsent(key, 0L); if (count == null) { count = 0L; } this.store.put(key, count + value); } @Override public void close() { log.info("called close()"); } }
b5d94978d2f3a72c528306bbfb86da643e7218f4
[ "Java", "Markdown", "Gradle" ]
24
Java
t2y/kafka-streams-sample
845b897df08eb36e53ae77d7ed6677901c466e65
f576db61a7a78376ed3136bccc06969204b8a140
refs/heads/master
<repo_name>daclv/test<file_sep>/html.go package main const ( html = `<!doctype html> <html> <head> <!-- Compiled and minified CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.0/css/materialize.min.css"> <!-- Compiled and minified JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.0/js/materialize.min.js"></script> <title>Frontend Web Server</title> </head> <body> <div class="container"> <div class="row"> <div class="col s2">&nbsp;</div> <div class="col s8"> <div class="card blue"> <div class="card-content white-text"> <div class="card-title">Backend that serviced this request</div> </div> <div class="card-content white"> <table class="bordered"> <tbody> <tr> <td>Name</td> <td>{{.Name}}</td> </tr> <tr> <td>Version</td> <td>{{.Version}}</td> </tr> <tr> <td>ID</td> <td>{{.Id}}</td> </tr> <tr> <td>Hostname</td> <td>{{.Hostname}}</td> </tr> <tr> <td>Zone</td> <td>{{.Zone}}</td> </tr> <tr> <td>Project</td> <td>{{.Project}}</td> </tr> <tr> <td>Internal IP</td> <td>{{.InternalIP}}</td> </tr> <tr> <td>External IP</td> <td>{{.ExternalIP}}</td> </tr> </tbody> </table> </div> </div> <div class="card blue"> <div class="card-content white-text"> <div class="card-title">Proxy that handled this request</div> </div> <div class="card-content white"> <table class="bordered"> <tbody> <tr> <td>Address</td> <td>{{.ClientIP}}</td> </tr> <tr> <td>Request</td> <td>{{.LBRequest}}</td> </tr> <tr> <td>Error</td> <td>{{.Error}}</td> </tr> </tbody> </table> </div> </div> </div> <div class="col s2">&nbsp;</div> </div> </div> </html>` )
2191cbee9b6e9d982c4d3f3c99ec489d517d8935
[ "Go" ]
1
Go
daclv/test
232c4a7577de0ec861cab79bf6e2cdee28979bbe
0e0e438c20c3e901a6ad52d492e2706e437d0efb
refs/heads/main
<repo_name>Zhaoqing-Li/Gas_sensing_data_analysis<file_sep>/DrawFigures.m clc; clear; % figure(1) % x=[5,10,20,50,100]; % y=[51132100/19107600,59965100/12802600,63278900/7938370,60401700/3418090,51319400/2087330]; % plot(x,y,'-or'); % axis([0,110,0,30]); % xlabel("乙醇浓度(ppm)"); % ylabel("响应比"); % export_fig C:\Users\26914\Desktop\Pictures\concentration.png -transparent % x=xlsread("C:\Users\26914\Desktop\Data.xlsx","Time"); % y=xlsread("C:\Users\26914\Desktop\Data.xlsx","Channel"); % figure('color',[1,1,1]); % y1=51132100./y; % plot(x,y1,'LineWidth',4); % xlabel("时间/秒"); % ylabel("约化响应比"); % axis([0,5000,0,30]); % set(gcf,'position',[0,0,1000,1000]); % set(gca,'FontSize',20); % box off % ax2 = axes('Position',get(gca,'Position'),... % 'XAxisLocation','top',... % 'YAxisLocation','right',... % 'Color','none',... % 'XColor','k','YColor','k'); % set(ax2,'YTick', []); % set(ax2,'XTick', []); % box on % set(gca,'LineWidth',2); % export_fig C:\Users\26914\Desktop\Pictures\Standarlized_Ratio-Time.png x=xlsread("C:\Users\26914\Desktop\Data.xlsx","Time"); y=xlsread("C:\Users\26914\Desktop\Data.xlsx","Channel"); % [x,y]=Delete(x,y,839,1163); % [x,y]=Delete(x,y,809,839); % % [x,y]=Delete(x,y,1672,2092); % [x,y]=Delete(x,y,3391,3831); % [x,y]=Delete(x,y,595,616); % [x,y]=Delete(x,y,1377,1396); % [x,y]=Delete(x,y,3053,3069); % % [x,y]=Delete(x,y,1882,2736); % [x,y]=Delete(x,y,2730,3300); % % [x,y]=Delete(x,y,1619,1632); % % [x,y]=Delete(x,y,1616,1906); % [x,y]=Delete(x,y,0,237); % [x,y]=Delete(x,y,342,358); % [x,y]=Delete(x,y,535,847); % [x,y]=Delete(x,y,1602,1613); % [x,y]=Delete(x,y,0,1508); % [x,y]=Delete(x,y,2445,5340); % y=Shift(x,y,0,346,-4.4e6); [x,y]=Delete(x,y,0,1424); [x,y]=Delete(x,y,1583,6000); [x,y]=Delete(x,y,321,347); figure('color',[1,1,1]); plot(x,y,'LineWidth',1); xlabel("时间/秒"); ylabel("电阻/Ω"); axis([0,1200,0,7e7]); set(gcf,'position',[0,0,1600,800]); set(gca,'FontSize',20); box off % ax2 = axes('Position',get(gca,'Position'),... % 'XAxisLocation','top',... % 'YAxisLocation','right',... % 'Color','none',... % 'XColor','k','YColor','k'); % set(ax2,'YTick', []); % set(ax2,'XTick', []); box on set(gca,'LineWidth',2); export_fig C:\Users\26914\Desktop\Pictures\Resistance-Time.png<file_sep>/README.md # Gas_sensing_data_analysis This is a matlab program that can work as the substitute of an exe of a particular kind of gas sensing instrument to draw pictures from the output txt file. Contact me: <EMAIL>
892dd1d1653f41d4cfad9bf7e9d560b28c14d4bb
[ "MATLAB", "Markdown" ]
2
MATLAB
Zhaoqing-Li/Gas_sensing_data_analysis
457090b38bc7d43afcc82a29dca6543d6923fe27
bd7816a792ac75ba6a8bf852755274b0a8fbb6a3
refs/heads/master
<repo_name>microgigz/mailcatcher-actionmailer<file_sep>/config/environments/development.rb Mymailer::Engine.configure do # ActionMailer::Base.delivery_method = :smtp # ActionMailer::Base.smtp_settings = { # address: "localhost", #{}"smtp.gmail.com", # #port: 587, # port: 1025, # domain: "localhost", # authentication: "plain", # enable_starttls_auto: true, # user_name: "muneeb.test1", # password: "<PASSWORD>" # } end <file_sep>/test/mymailer_test.rb require 'test_helper' class MymailerTest < ActiveSupport::TestCase test "truth" do assert_kind_of Module, Mymailer end end <file_sep>/config/routes.rb Mymailer::Engine.routes.draw do root :to => redirect('http://localhost:1080') end <file_sep>/lib/mymailer/engine.rb module Mymailer class Engine < ::Rails::Engine isolate_namespace Mymailer mailcatcher ="mailcatcher" #exec(mailcatcher) #pid = Process.fork(exec(mailcatcher)) # Detach the spawned process #Process.detach pid t = Thread.start do system mailcatcher end t.kill end end <file_sep>/lib/mymailer.rb require "mymailer/engine" module Mymailer end <file_sep>/README.md mailcatcher-actionmailer ======================== Configuration less mailcatcher<file_sep>/test/dummy/config/routes.rb Rails.application.routes.draw do mount Mymailer::Engine => "/mymailer" end <file_sep>/README.rdoc = Mymailer This project rocks and uses MIT-LICENSE.<file_sep>/app/helpers/mymailer/application_helper.rb module Mymailer module ApplicationHelper end end
87d63b52585b6b9c0f6f4bad58ce6f994741517e
[ "Markdown", "RDoc", "Ruby" ]
9
Markdown
microgigz/mailcatcher-actionmailer
01c9822bd2cacf155ef093371f7f7c56a5126f3c
50c012e5dacb8d631a09cd5ae60993fedb7e9261
refs/heads/main
<repo_name>wzy0766/JPMorgan_Chase_SDE<file_sep>/README.md # JPMorgan_Chase_SDE JPMorgan Chase Software Engineering Virtual Experience
b8141975d7234d62c67fd8323a01447b5273327c
[ "Markdown" ]
1
Markdown
wzy0766/JPMorgan_Chase_SDE
f11275e64878fc120d4d55b37731aa184a9a425f
aabcac848ce5ea0650c4a9af8b1fc7664791cb68
refs/heads/master
<repo_name>theRealYoshi/blogger<file_sep>/app/helpers/articles_helper.rb module ArticlesHelper #takes params hash from page, allows to take the whole "article hash" # then permits only the title and body hash to be taken def article_params params.require(:article).permit(:title, :body, :tag_list, :image) end end
321f1e897c9fe0b6b307511ee27a7953f75e208c
[ "Ruby" ]
1
Ruby
theRealYoshi/blogger
5940394c3a8284006ab56f718a4bcf26797477c2
ce4aa441b0f1a79dceb7c5cf1fbc6d42804f3eae
refs/heads/main
<repo_name>Leticiapp/jogo-da-capital<file_sep>/README.md # O Jogo da Capital
8413e50d1f7e34df7ebe49085b729bc801ea4cf3
[ "Markdown" ]
1
Markdown
Leticiapp/jogo-da-capital
3db03f2742e6a44fdce3e8cee6dca02a019582e3
ef2539fb5ed99c48669063628fc6c8f677102005
refs/heads/master
<file_sep>from typing import List from fastapi import APIRouter from models.organization import Organization from models.team import Team router = APIRouter() @router.get( "/", response_model=List[Organization], description="쓰샘이 설치된 기관의 포인트로 내림차순으로 정렬된 리스트 조회", ) async def organization_list(): pass @router.get( "/{organization_name}", response_model=Organization, description="입력한 기관 이름으로 정보 조회", ) async def organization_detail(organization_name: str): pass @router.get( "/{organization_name}/teams", response_model=List[Team], description="기관에 속한 팀의 리스트 조회", ) async def organization_team_list(organization_name: str): pass @router.get( "/{organization_name}/teams/{team_name}", response_model=Team, description="기관에 속한 팀의 정보 조회", ) async def organization_team_detail(organization_name: str, team_name: str): pass <file_sep>import 'package:flutter/material.dart'; import 'frame/home.dart'; void main() { runApp(InuobusApp()); } class InuobusApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'INOBUS application', home: HomeFrame( title: 'INOBUS', backgroundColor: Colors.green, pointColor: Colors.white, ), ); } } <file_sep># 분리배출의 민족 팀페이지 주소 : https://kookmin-sw.github.io/capstone-2021-3/ ## 1. 프로젝트 소개 ![프로젝트 소개](./Docs/img/0001.jpg) 이 프로젝트는 Image Classification을 이용하여 사용자에게 버리는 물품을 인식하여 어떻게 분리배출을 하는지 알려주어 올바른 분리배출을 할 수 있도록 도와주는 애플리케이션입니다. 이로 하여금 올바른 분리배출 방법을 인식하고 실천할 수 있도록 분리배출 문화를 조성합니다. ## 2. 소개 ### 애플리케이션 기능 소개 ![애플리케이션 기능](./Docs/img/0005.jpg) ![애플리케이션 상세](./Docs/img/0007.jpg) ![애플리케이션 상세](./Docs/img/0008.jpg) ## 3. 팀 소개 ``` 허태정 Student ID : 20181708 E-Mail : <EMAIL> Role : 팀장, Github : [@Aqudi](https://github.com/Aqudi) ``` ``` 동설아 Student ID : 20171618 E-Mail : <EMAIL> Role : Github : [@gychoics](https://github.com/gychoics) ``` ``` 박정섭 Student ID : 20181616 E-Mail : <EMAIL> Role : Github : [@ParkJeongseop](https://github.com/ParkJeongseop) ``` ``` 허민호 Student ID : 20143115 E-Mail : <EMAIL> Role : Github : [@minoring](https://github.com/minoring) ``` ## 4. 사용법 ### Deep Learning 환경 설정 - Python 3.8 Virtual Environments 설정 - "deep_learning/" 폴더에서 `pip install -r requirements.txt` 실행 ```shell # Example cd deep_learning python3 -m venv <venv_name> source <venv_path>/bin/activate pip3 install -r requirements.txt ``` - #### 데이터 준비 - "deep_learning/recycle_dataset/" 폴더에서 `tfds build` 실행 - `python recycle_dataset_test.py` 실행으로 데이터 테스트 - "data_example.ipynb" 으로 데이터 사용예제 확인 ```shell # Example cd deep_learning/recycle_dataset/ tfds build # 데이터 다운로드, 준비 jupyter lab # 예제 노트북 확인 ``` ### Application 개발 + lefthook 설치 + [설치 가이드](https://github.com/Arkweid/lefthook/blob/master/docs/full_guide.md) + Windows10을 사용하는 경우 + [release 링크](https://github.com/Arkweid/lefthook/releases)로 접속해서 .exe 파일을 받고 환경변수로 해당 파일 지정하면 바로 사용 가능. + 설치 완료 후 root 폴더에서 `lefthook install` 실행 ## 5. 기타 추가적인 내용은 자유롭게 작성하세요. <file_sep>from typing import List from fastapi import APIRouter from models.device import Device router = APIRouter() @router.get( "/", response_model=List[Device], description="모든 쓰샘 기기의 리스트 조회", ) async def deivce_list(): pass @router.get( "/nearby", response_model=List[Device], description="사용자 근처 쓰샘 리스트 반환", ) async def device_nearby_list(latitude: float, longitude: float): pass <file_sep>from typing import Optional from pydantic import BaseModel, Field from utils.pyobjectid import ObjectId, PyObjectId class User(BaseModel): """User Base 모델""" id: Optional[PyObjectId] = Field(alias="_id") device_id: str = Field(description="기기별 사용자 식별 id") team: str = Field(description="사용자가 속한 팀 (닉네임)") class UserIn(User): """User DB 모델""" class Config: json_encoders = {ObjectId: str} schema_extra = { "example": { "id": "1", "device_id": "9C287922-EE26-4501-94B5-DDE6F83E1475", "team": "소융대18", } } class UserOut(User): """User Response 모델""" point: int = Field(description="유저의 누적 포인트") class Config: json_encoders = {ObjectId: str} schema_extra = { "example": { "id": "1", "device_id": "9C287922-EE26-4501-94B5-DDE6F83E1475", "team": "소융대18", "point": 0, } } <file_sep># INOBUS Backend ## 폴더 구조 ``` . ├── main.py # 애플리케이션 진입점 ├── models # API에 사용되는 모델들을 정의한 폴더 ├── routes # API router 들을 정의한 폴더 └── utils # util 모음 폴더 ``` ## 설치 ```shell pip install -r requirements.txt ``` ## 실행 ```shell uvicorn main:app ``` ## Swagger 접속 http://localhost:8000/docs <file_sep>import 'package:flutter/material.dart'; class RankPage extends StatefulWidget { RankPage(); @override _RankPage createState() => _RankPage(); } class _RankPage extends State<RankPage> { @override Widget build(BuildContext context) { // 반응형으로 만들기 위한 변수 final mediaQuery = MediaQuery.of(context); return Scaffold( body: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.center, children: [ RankIcon( rankColor: Colors.grey, rankSize: mediaQuery.size.width * 0.2, rankText: "222222222222"), RankIcon( rankColor: Colors.yellow, rankSize: mediaQuery.size.width * 0.25, rankText: "11111111111"), RankIcon( rankColor: Colors.brown, rankSize: mediaQuery.size.width * 0.15, rankText: "33333333333"), ]), Padding( padding: EdgeInsets.only( left: mediaQuery.size.width * 0.1, ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ RankText( bottomHeight: mediaQuery.size.height * 0.05, rankeText: "4등 : 444444444444"), RankText( bottomHeight: mediaQuery.size.height * 0.05, rankeText: "5등 : 5555555555555"), RankText( bottomHeight: mediaQuery.size.height * 0.05, rankeText: "6등 : 6666666666666") ], ), ) ], )); } } // 아이콘으로 등수 표현 class RankIcon extends StatelessWidget { final double rankSize; final String rankText; final Color rankColor; RankIcon({Key key, this.rankSize, this.rankText, this.rankColor}) : super(key: key); @override Widget build(BuildContext context) { return Column( children: [ Text(rankText), Icon( Icons.emoji_events, color: rankColor, size: rankSize, ), if (rankColor == Colors.yellow) Text("1등") else if (rankColor == Colors.grey) Text("2등") else if (rankColor == Colors.brown) Text("3등") ], ); } } // 텍스트로 등수 표현 class RankText extends StatelessWidget { final double bottomHeight; final String rankeText; RankText({Key key, this.bottomHeight, this.rankeText}) : super(key: key); @override Widget build(BuildContext context) { return Padding( padding: EdgeInsets.only(bottom: bottomHeight), child: Row( mainAxisAlignment: MainAxisAlignment.start, children: [Text(rankeText)]), ); } } <file_sep>import 'package:flutter/material.dart'; import '../page/map.dart'; import '../page/qr.dart'; import '../page/rank.dart'; import '../page/menu.dart'; class HomeFrame extends StatefulWidget { HomeFrame({Key key, this.title, this.backgroundColor, this.pointColor}) : super(key: key); final String title; final Color backgroundColor; final Color pointColor; @override _HomeFrame createState() => _HomeFrame(); } class _HomeFrame extends State<HomeFrame> { int selectedIndex; PageController pagecontroller; @override void initState() { super.initState(); this.selectedIndex = 0; this.pagecontroller = PageController( initialPage: this.selectedIndex, ); } @override void dispose() { pagecontroller.dispose(); super.dispose(); } // 네비게이션 버튼을 눌렀을 때 void onItemTapped(int index) { setState(() { selectedIndex = index; pagecontroller.animateToPage(selectedIndex, duration: Duration(milliseconds: 100), curve: Curves.linear); }); } // 손으로 페이지를 넘겼을 때 void pageChanged(int index) { setState(() { selectedIndex = index; }); } final List<Widget> bodyCenter = [MapPage(), QRPage(), RankPage(), MenuPage()]; @override Widget build(BuildContext context) { return Scaffold( // 앱바 appBar: AppBar( backgroundColor: widget.backgroundColor, title: Text(widget.title), ), // 내용 body: PageView( controller: pagecontroller, children: bodyCenter, onPageChanged: (index) { pageChanged(index); }, ), // 네비게이션 바 bottomNavigationBar: BottomNavigationBar( type: BottomNavigationBarType.fixed, backgroundColor: widget.backgroundColor, selectedItemColor: widget.pointColor, unselectedItemColor: widget.pointColor.withOpacity(.60), currentIndex: selectedIndex, onTap: onItemTapped, items: <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: Icon(Icons.map), label: 'Map', ), BottomNavigationBarItem( icon: Icon(Icons.camera_alt), label: 'QR Scan', ), BottomNavigationBarItem( icon: Icon(Icons.emoji_events), label: 'Rank', ), BottomNavigationBarItem( icon: Icon(Icons.menu), label: 'Menu', ), ], ), ); } } <file_sep># 분리배출의 민족 ## 1. 프로젝트 소개 ![프로젝트 소개](./Docs/img/0001.jpg) 이 프로젝트는 Image Classification을 이용하여 사용자에게 버리는 물품을 인식하여 어떻게 분리배출을 하는지 알려주어 올바른 분리배출을 할 수 있도록 도와주는 애플리케이션입니다. 이로 하여금 올바른 분리배출 방법을 인식하고 실천할 수 있도록 분리배출 문화를 조성합니다. ## 2. 소개 ### 애플리케이션 기능 소개 ![애플리케이션 기능](./Docs/img/0005.jpg) ![애플리케이션 상세](./Docs/img/0007.jpg) ![애플리케이션 상세](./Docs/img/0008.jpg) ## 3. 팀 소개 ``` 허태정 Student ID : 20181708 E-Mail : <EMAIL> Role : 팀장, Github : [@Aqudi](https://github.com/Aqudi) ``` ``` 동설아 Student ID : 20171618 E-Mail : <EMAIL> Role : Github : [@gychoics](https://github.com/gychoics) ``` ``` 박정섭 Student ID : 20181616 E-Mail : <EMAIL> Role : Github : [@ParkJeongseop](https://github.com/ParkJeongseop) ``` ``` 허민호 Student ID : 20143115 E-Mail : <EMAIL> Role : Github : [@minoring](https://github.com/minoring) ``` ## 4. 사용법 #### **Python 환경 설정** - Python 3.7 Virtual Environments 설정 - 프로젝트 루트에서 `pip install -r requirements.txt` 실행 #### **데이터 준비** - `cd deep_learning/recycle_dataset` 실행 - `tfds build` 실행 - `python recycle_dataset_test.py` 실행으로 데이터 테스트 - "data_example.ipynb" 으로 데이터 사용예제 확인 ## 5. 기타 추가적인 내용은 자유롭게 작성하세요. <file_sep>from pydantic import BaseModel, Field class Team(BaseModel): """팀 모델 (사용자의 닉네임)""" name: str = Field(description="팀 이름") point: int = Field(description="팀의 누적 포인트") class Config: schema_extra = { "example": { "name": "소융대18", "point": 30, } }
f6950335a6e71f9daddb45ec8b44ea87a429784a
[ "Markdown", "Dart", "Python" ]
10
Markdown
TongSeola/capstone-2021-3
126a3f139fdf6b3ccaa36e4a5eb8bec5ad4bd078
6d1adfe53e7db5d2d949ce5f820c803ccf112a3c
refs/heads/master
<file_sep># wflfei-leetcode my own leetcode code
421b4afea9b6c528289cdc61e79417c94edeb63d
[ "Markdown" ]
1
Markdown
wflfei/wflfei-leetcode
3b57382a465e246f063d77a8e30007c508a6e8c7
7c476bc3dd2642f9b06a4c7ab1652e80cacb5304
refs/heads/master
<repo_name>Lasha/Test-Project<file_sep>/home.php <?php // put something here ?>
a4adc6c1b516019e00e5a5c8ad39efe927cc1524
[ "PHP" ]
1
PHP
Lasha/Test-Project
9a220e3c9eb9f975ad823e437ed400f9604598ad
800d362e16743f3f82570aa1ca069a7035ad613d
refs/heads/main
<repo_name>Madhujaya/Dukhan-UFT_Demo<file_sep>/README.md # Dukhan-UFT_Demo Demo_Repository
10df990c91f42240707fbbd6e684f5537fd83e4a
[ "Markdown" ]
1
Markdown
Madhujaya/Dukhan-UFT_Demo
89d3189f948628feca15151230988011b1239ace
56d626227a38c7bf30a69ccd6ee1eab752bf5e32
refs/heads/master
<repo_name>ColqueRicardo/v-version<file_sep>/pruebas/pruebas aisladas/archivos xml.py import xml.etree.ElementTree as ET bd=ET.Element("base") ventana=ET.SubElement(bd,"ventana", name="ventana-consultas") ventana_hide=ET.SubElement(ventana,"ventana-hide",) ventana_hide.set("option-hide","false") ET.dump(bd) tree = ET.ElementTree(bd) tree.write("C:/Users/ricar/Desktop/pruebas v1/pruebasv1.xml") estructura_xml = ET.parse("C:/Users/ricar/Desktop/pruebas v1/pruebasv1.xml") # Obtiene el elemento raíz: raiz = estructura_xml.getroot() '''for ventana in raiz.findall('ventana'): print(ventana) print("espacio1") print(ventana.get("option-hide")) print("nada") ''' for ventana in raiz.iter('ventana'): print("get: "+str(ventana.get("option-hide"))) ventana.set("option-hide","0") print(ventana.get("option-hide")) estructura_xml.write("C:/Users/ricar/Desktop/pruebas v1/pruebasv1.xml") <file_sep>/v-2/pruebas/envio de archivos por socket/servidor.py import socket from io import open import pickle import sys r="C:/Users/ricar/Desktop/prueba v2.docx" r2="C:/Users/ricar/Desktop/pruebav2" r3=r2+"/v2.docx" s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) '''s.bind(('localhost',8000))''' s.bind(('localhost',8000)) s.listen(10) conexiones=[] i=0 while True: conexion, direccion= s.accept() conexiones.append(conexion) peticion =(pickle.loads(conexiones[i].recv(1024))) print(peticion) peticion2=conexiones[i].recv(peticion*1.1) print(sys.getsizeof(peticion2)) print(peticion2) c = open(r3, "wb") c.write(peticion2) c.close() conexiones[i].close() i += 1<file_sep>/pruebas/prueba servidor-cliente/jugadores_gui.py from tkinter import * # Carga módulo tk (widgets estándar) from tkinter import ttk # Carga ttk (para widgets nuevos 8.5+) import socket import sys import datetime from tkinter import messagebox import time import threading from threading import Lock import random 'sys.path.append("C:/Users/ricar/PycharmProjects/v-version/venv/prueba servidor-cliente/prueba.py")' from prueba import * class gui_pong(): def __init__(self): self.jugador_id=None self.blocker=Lock() self.ventana=Tk() self.x = int(self.ventana.winfo_screenwidth()) self.y = int(self.ventana.winfo_screenheight()) xy = "{0}x{0}+" +"0" + "+" + "0" self.ventana.geometry((xy.format(self.x, self.y))) self.puntuacion_j1=0 self.puntuacion_j2=0 self.tamaño_barra=0 self.canvas= Canvas(self.ventana,bg="black") self.canvas.place(relx=0,rely=0,relheight=1,relwidth=1) self.canvas.focus_set() self.canvas.create_line(30,self.y//2,30,(self.y//2)*1.2,fill="white",width=15,tags="jugador1") self.canvas.create_line(self.x-30,self.y//2,self.x-30,(self.y//2)*1.2,fill="white",width=15,tags="jugador2") self.canvas.create_rectangle((self.x//2)-15,(self.y//2)-15,(self.x//2)+15,(self.y//2)+15,fill="white",tags="pelota") self.canvas.bind("<Key>",lambda event:self.mover(event)) self.canvas.move(self.canvas.find_withtag("jugador1"), 30, 0) ''' coneccion_estable=FALSE msg=FALSE while not msg or not coneccion_estable: msg =messagebox.askyesno(message="¿reintentar?", title="espere al otro jugador") 'funcion para reintentar la conecxion' coneccion_estable= self.reintentar() ''' self.reintentar() self.hilo_actualizar=threading.Timer(0.01,lambda :self.actualizar()) self.hilo_actualizar.start() ''' self.hilo_mainloop=threading.Thread(self.ventana.mainloop()) self.hilo_mainloop.start() ''' self.ventana.mainloop() def entablar_conexion(self,mensaje): 'self.blocker.acquire()' self.socket = socket.socket() self.socket.connect(('localhost', 8000)) mensaje_codificado=codificar_mensaje(mensaje) self.socket.sendto(mensaje_codificado,('localhost',8000)) respuesta = decoficar_mensaje(self.socket.recv(1024).decode()) self.socket.close() 'self.blocker.release()' return respuesta def reintentar(self): msg=["jugador esperando"],[self.x],[self.y] respuesta=self.entablar_conexion(msg) if respuesta[0]=="se puede": self.jugador_id=respuesta[1] self.tamaño_barra=int(respuesta[2]) self.inicio_y=[] self.inicio_y.append(int(respuesta[3])) self.inicio_y.append(int(respuesta[4])) return TRUE else: print(respuesta,"fallo") def mover(self,event): self.canvas.update() print(event.char) if event.char=="w": msg=["arriba"],[self.jugador_id] respuesta=(self.entablar_conexion(msg)) mensaje=["actualizar"],[self.jugador_id] respuesta=self.entablar_conexion(mensaje) print(respuesta[0]) print(self.inicio_y[0]) self.canvas.move(self.canvas.find_withtag("jugador1"),0,int(respuesta[0])-int(self.inicio_y[0])) self.inicio_y[0]=int(respuesta[0]) 'self.actualizar(int(respuesta[0]),int(respuesta[0]),230,230)' 'self.canvas.create_line(30,int(respuesta[0]), 30,int(respuesta[0])+self.tamaño_barra, fill="white", width=15,tags=str(self.jugador_id))' '''self.inicio_j1_y=self.inicio_j1_y+ (10*self.velocidad_jugador) self.canvas.create_line(30,self.inicio_j1_y,30,self.inicio_j1_y+200,fill="white",width=15,tags="jugador1") ''' elif event.char=="s": msg=["abajo"],[self.jugador_id] respuesta=(self.entablar_conexion(msg)) print(respuesta[0]) print(self.inicio_y[0]) self.canvas.move(self.canvas.find_withtag("jugador1"),0,int(respuesta[0])-int(self.inicio_y[0])) self.inicio_y[0]=int(respuesta[0]) 'self.canvas.create_line(30,int(respuesta[0]), 30,int(respuesta[0])+self.tamaño_barra, fill="white", width=15,tags=str(self.jugador_id))' ''' if self.inicio_j1_y>30: self.canvas.delete("jugador1") self.inicio_j1_y = self.inicio_j1_y - (10*self.velocidad_jugador) self.canvas.create_line(30, self.inicio_j1_y, 30, self.inicio_j1_y + 200, fill="white", width=15, tags="jugador1") else: print("muy arriba") ''' def actualizar(self): while TRUE: mensaje=["actualizar"],[self.jugador_id] respuesta=self.entablar_conexion(mensaje) print("empiezasss",respuesta) '[self.inicio_jugadores[0]],[self.inicio_jugadores[1]],[self.pelota_posicion[int(peticion[0])][0]],[self.pelota_posicion[int(peticion[0])][1]]' 'inicio "y" de j1 y j2 , posicion de la pelota dependiendo de j1 o j2 ' self.canvas.move(self.canvas.find_withtag("jugador1"),30,int(respuesta[0])) ''' self.canvas.create_line(30,int(respuesta[0]),30,int(respuesta[0])+self.tamaño_barra,fill="white",width=15) self.canvas.create_line(self.x-30,int(respuesta[1]),self.x-30,int(respuesta[1])+self.tamaño_barra,fill="white",width=15) self.canvas.create_rectangle((int(respuesta[2])//2)-15,(int(respuesta[3])//2)-15,(int(respuesta[2])//2)+15,(int(respuesta[3])//2)+15,fill="white",tags="pelota") ''' gui=gui_pong() <file_sep>/pruebas/pruebas aisladas/v1.py from tkinter import * # Carga módulo tk (widgets estándar) from tkinter import ttk # Carga ttk (para widgets nuevos 8.5+) def cargardato(): if textvariable.get()=="": list.append(" ") else: list.append(textvariable.get()) muestral.set("") for i in range(0, len(list)): muestral.set(muestral.get() + list[i]) print(list) rc= Tk() rc.geometry("500x500") #cargar list = [] #text textvariable=StringVar() text=Entry(rc,text="Escriba",textvariable=textvariable).place(x=30,y=10) boton = Button(rc,text="cargar",command=cargardato,cursor="hand1",width=35).place(x=30,y=50) #mostrar muestral= StringVar() muestralista=Entry(rc,textvariable=muestral).place(x=30,y=100) rc.mainloop()<file_sep>/v-2/algoritmo modificado del vecino mas cercano/mod.py print("hola") print "sad" <file_sep>/pruebas/clase bd/usuario_data.py import socket import pickle import datetime import io import sys class datos_usuarios(): def __init__(self,usuario,password,privilegios): self.usuario = usuario self.password = <PASSWORD> self.usuario_privilegios = privilegios self.last_connection = datetime.date.today() self.max_connections=1 self.connectiosn_actuales=0 '''self.usuario_privilegios--> 1°-->privilegios de crear usuarios,bd,etc 2°-->privilegios de insert 3°-->privilegios de update 4°-->privilegios de delete°''' def __del__(self): del self.usuario del self.password del self.last_connection del self.usuario_privilegios def serializar(ruta,objeto): with open(ruta,"wb") as f: pickle.dump(objeto, f) def deserializar(ruta): with open(ruta, "rb") as f: b = pickle.load(f) return b ''' usuario=datos_usuarios() usuario.instanciar_usuario("rc","123456789","1111") print(usuario) serializar("C:/Users/ricar/Desktop/pruebas v1/base/usuarios/usuarios",usuario) usu=deserializar("C:/Users/ricar/Desktop/pruebas v1/base/usuarios/usuarios") print(usu) '''<file_sep>/pruebas/prueba v1/subpruebav1 servers/cliente.py import socket import threading from tkinter import * class hola(): def __init__(self): self.fin=0 self.ip = socket.gethostbyname(socket.gethostname()) self.establecer_coneccion_envia() self.texto_recivido="" self.ventana=Tk() self.ventana.geometry("1000x500") self.button2=Button(self.ventana,text="envia",command=self.boton_2) self.button2.place(x=100, y=200, width=100, height=50) self.text1=Entry(self.ventana) self.text1.place(x=250,y=100,height=150,width=700) self.text2 = Entry(self.ventana) self.text2.place(x=250, y=300, height=150, width=700) self.hilo1=threading.Thread(name="s", target=self.recive) self.hilo1.start() self.hilo_main=threading.Thread(name="main", target=self.ventana.mainloop()) self.hilo_main.start() def recive(self): self.i=0 while True: self.i+=1 self.texto_recivido=self.conexion.recv(1024).decode() print("se a recivido: ",self.texto_recivido) self.text1.insert(0,self.texto_recivido) if self.i>10: self.text1.delete(0,'end') self.i=0 if (self.fin == 1): break conexion.close() def establecer_coneccion_envia(self): puerto = 8000 self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server.bind((self.ip, puerto)) self.server.listen(1) self.conexion, self.direccion = self.server.accept() puerto = 8001 self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.s.connect((self.ip, puerto)) def boton_2(self): self.s.send("mensaje".encode('utf-8')) self.text2.insert(0, "se a enviado") h=hola()<file_sep>/pruebas/pruebas aisladas/cliente-servidor/otra forma/cliente.py import socket s = socket.socket() '''esto si nesecita la direccion para conectarse y el puerto''' s.connect(('localhost',8000)) mensaje="hola servidor" s.send(mensaje.encode('utf-8')) '''peso esperado''' respuesta= s.recv(1024) print(respuesta) 's.close()'<file_sep>/pruebas/pruebas aisladas/hilos/hilos.py import threading import time def s(a): while True: print(a) z=threading.Thread(name="1",target=s,args="1") x=threading.Thread(name="2",target=s,args="2") x.start() z.start()<file_sep>/pruebas/clase bd/servidor_usuario.py import socket import sys sys.path.append("C:/Users/ricar/PycharmProjects/v-version/venv/clase bd/usuario_gestor.py") from usuario_gestor import gestor_usuarios from prueba import * gestor_usuarios= gestor_usuarios() print("empieza") s= socket.socket() s.bind(('localhost',8000)) s.listen(1) while True: conexion, direccion= s.accept() '''tengo q medir lo q se envia''' peticion=conexion.recv(1024) peticion=peticion.decode() print(decoficar_mensaje(str(peticion))) peticion =decoficar_mensaje(str(peticion)) if peticion[0]=="obtener_secion": resolucion= gestor_usuarios.iniciar_secion(peticion[1],peticion[2]) del peticion conexion.send(resolucion.encode('utf-8')) conexion.close() <file_sep>/v-2/pruebas/manejo de archivos/gestordearchivos.py import sys from timeit import timeit from time import time class archivo(): def __init__(self,nombre): self.id="" self.visible=1 w=self.sacar_extencion(nombre) self.nombre=w[0] self.extencion=w[1] self.contenido=-1 del w def asignar_id(self,id): self.id=id return self def asignar_contenido(self,contenido): self.contenido=contenido def sacar_extencion(self,nombre): w = [] w.append("") w.append("") i = len(nombre) while w[1] =="" and i > 0: if nombre[i - 1:i] == ".": w[0]=nombre[0:i-1] w[1]=nombre[i:len(nombre)] break i -= 1 if w[1] == "": w[1] = "none" return w class archivo_contenido(): def __init__(self): self.archivo_contenido= [] def len_archivo(self): return len(self.archivo_contenido) def agregar(self,contenido): self.archivo_contenido.append(contenido) class carpeta(): def __init__(self,nombre): self.id="" self.visible=1 self.nombre=nombre self.contenido=[] self.gestior_id=0 def asignar_id(self,id): self.id=id return self def agregar_contenido(self,contenido): self.contenido.append(contenido.asignar_id(self.gestior_id)) self.gestior_id+=1 def recorrer(c): for i in c.contenido: if type(i)==carpeta: print("nombre: " ,i.nombre,"id: ",i.id) recorrer(i) if type(i)==archivo: print("nombre: ", i.nombre,".",i.extencion,"id: ",i.id) def busqueda_completa(c,v,w,s): p=None for i in c.contenido: if i.id==v[w]: if type(i) == carpeta: 'print("nombre: ", i.nombre, "id: ", i.id)' p=busqueda_completa(i,v,w+1,s) if type(i) == archivo: print("encontrado: nombre: ", i.nombre, ".", i.extencion, "id: ", i.id) return i return p def busqueda_id(dir_actual,v): try: for i in v: if type(dir_actual)== carpeta: dir_actual = dir_actual.contenido[i] if type(dir_actual)== archivo: return dir_actual 'print("encontrado:", dir_actual.nombre, dir_actual.extencion)' except: 'print("no se encontro o ruta desconocida")' return None ''' cargar y recorrer una 2 carpetas con 13 archivos cada una c=carpeta("master") c.asignar_id(0) for i in range(10): c.agregar_contenido(archivo(str(i)+".exe")) c.agregar_contenido(carpeta("carpeta 1")) c.agregar_contenido(carpeta("carpeta 2")) for i in c.contenido: if type(i)==carpeta: for l in range(5): i.agregar_contenido(archivo(str(l)+".jpg")) 'print("nombre: ", c.nombre, "id: ", c.id)' recorrer(c) ''' 'v=[]' 'archivo existente' '''v.append(11) v.append(0)''' 'archivo inexistente' '''v.append(12) v.append(2)''' ''' 'primer metodo' start_time = time() s=(busqueda_completa(c,v,0,None)) if s!=None: print(s.nombre,".",s.extencion) else: print("archivo no encontrado") elapsed_time = time() - start_time print("termino",elapsed_time) ''' 'segundo de busqueda ' ''' start_time = time() s=busqueda_id(c,v) if s!=None: print(s.nombre,".",s.extencion) else: print("no se encontro") elapsed_time = time() - start_time print("termino",elapsed_time) '''<file_sep>/pruebas/clase bd/gui_usuario.py from tkinter import * # Carga módulo tk (widgets estándar) from tkinter import ttk # Carga ttk (para widgets nuevos 8.5+) import socket import sys import datetime from tkinter import messagebox '''sys.path.append("C:/Users/ricar/PycharmProjects/v-version/venv/clase bd/usuario_gestor.py") ''' '''sys.path.append("C:/Users/ricar/PycharmProjects/v-version/venv/clase bd/usuario_secion.py") ''' '''sys.path.append("C:/Users/ricar/PycharmProjects/v-version/venv/clase bd/prueba.py")''' from usuario_secion import usuario_secion from usuario_gestor import gestor_usuarios from prueba import * class usuarios(): def __init__(self): self.ventana=Tk() x=int(self.ventana.winfo_screenwidth()*0.3) y=int(self.ventana.winfo_screenheight()*0.2) xy="{0}x{0}+"+str(x)+"+"+str(y) self.ventana.geometry((xy.format(500, 300))) self.usuario_variable = StringVar() self.usuario_label=Label(self.ventana,text="Ingrese el nombre del usuario") self.usuario_label.place(relx=0.15,rely=0.05,relwidth=0.7,relheight=0.05) self.usuario_textbox = Entry(self.ventana) self.usuario_textbox.place(relx=0.15,rely=0.1,relwidth=0.7,relheight=0.05) self.password_label=Label(self.ventana,text="Ingrese la contraseña del usuario") self.password_label.place(relx=0.15,rely=0.15,relwidth=0.7,relheight=0.05) self.password_variable=StringVar() self.password_textbox= Entry(self.ventana) self.password_textbox.place(relx=0.15,rely=0.2,relwidth=0.7,relheight=0.05) self.inicio_secion = Button(self.ventana,command=lambda: usuarios.obtener_secion_boton(self),text="iniciar") self.inicio_secion.place(relx=0.2,rely=0.35,relwidth=0.2,relheight=0.05) self.cancelar_secion= Button(self.ventana,command=lambda:usuarios.cancelar_secion_boton(self),text="cancelar") self.cancelar_secion.place(relx=0.6,rely=0.35,relwidth=0.2,relheight=0.05) self.ventana.mainloop() def obtener_secion_boton(self): s = socket.socket() s.connect(('localhost', 8000)) vec=["obtener_secion"],[self.usuario_textbox.get()],[self.password_textbox.get()] mensaje=codificar_mensaje(vec) s.send(mensaje.encode()) '''peso esperado (un objeto vacio deberia pesar almenos 20bytes) ''' respuesta = s.recv(1024).decode() s.close() if respuesta=="aceptado": self.secion_usuario=usuario_secion(self.usuario_textbox.get(),self.password_textbox.get()) messagebox.showinfo(message="bienvenido "+ self.secion_usuario.usuario, title="secion iniciada") print(self.secion_usuario.usuario) print(self.secion_usuario.password) print(self.secion_usuario.pc_ip) print(self.secion_usuario.pc_name) print(self.secion_usuario.expiracion_secion<datetime.date.today()+datetime.timedelta(days=0)) print(self.secion_usuario.usuario_privilegios) elif respuesta=="el usuario a exedido el numero de conecciones": messagebox.showerror(message=respuesta, title="Advertencia") elif respuesta=="contraseña no coinciden": messagebox.showerror(message=respuesta,title="advertencia") elif respuesta=="no existe el usuario": messagebox.showerror(message=respuesta, title="advertencia") def cancelar_secion_boton(self): sys.exit(0) '''debe cerrar todo otro dia vere''' s=usuarios() <file_sep>/v-2/pruebas/envio de archivos por socket/cliente.py import socket import pickle import sys r="C:/Users/ricar/Desktop/prueba v2.docx" r2="C:/Users/ricar/Desktop/pruebav2" r3=r2+"/v2.docx" c=open(r,"rb") lectura=c.read() t=sys.getsizeof(lectura) '''mensaje=[] mensaje.append(c.read()) mensaje.append(r3) mensaje=pickle.dumps(mensaje) tamaño=sys.getsizeof(mensaje)''' s = socket.socket() s.connect(('localhost',8000)) s.send(pickle.dumps(t)) print(t) s.send(lectura) print(type(lectura)) '''peso esperado''' s.close()<file_sep>/pruebas/prueba servidor-cliente/servidor.py from tkinter import * # Carga módulo tk (widgets estándar) from tkinter import ttk # Carga ttk (para widgets nuevos 8.5+) import socket import sys import datetime from tkinter import messagebox import time import threading import random sys.path.append("C:/Users/ricar/PycharmProjects/v-version/venv/prueba servidor-cliente/prueba.py") from prueba import * class pong(): def __init__(self): self.jugadores_id=0 'dimenciones x,y de los jugadores' self.dimenciones=[["",""],["",""]] self.tamaño_barra=[] 'int(self.ventana.winfo_screenheight())' xy = "{0}x{0}+" +"0" + "+" + "0" ' self.ventana.geometry((xy.format(500, 500)))' self.velocidad_jugador=0.5 self.direccion=random.randint(0,3) 'donde inicia la barra' self.inicio_jugadores=[] self.turno=random.randint(0,1) self.velocidad_pelota_x=15 self.velocidad_pelota_y=20 'se define todo en el inicio de secion' ''' self.pelota_x=[self.dimenciones[0]//2],[self.dimenciones[2]//2] self.pelota_y=[self.dimenciones[1]//2],[self.dimenciones[3]//2] ''' self.pelota_posicion=[[0,0],[0,0]] self.puntuacion_jugadores=[0],[0] self.timer=time ''' self.servidor.hilo= threading.Timer(0.01,self.servidor_ejecucion()) self.servidor.hilo.start() ''' self.servidor_ejecucion() '''self.hilo_tiempo = threading.Timer(1, lambda: self.tiempo_ejecucion()) self.hilo_tiempo.start() self.hilo_mainloop=threading.Thread(self.ventana.mainloop()) self.hilo_mainloop.start() ''' def servidor_ejecucion(self): print("empieza") s = socket.socket() s.bind(('localhost', 8000)) s.listen(20) while True: conexion, direccion = s.accept() peticion = conexion.recv(1024).decode() peticion=decoficar_mensaje(peticion) if peticion[0] == "jugador esperando" and self.jugadores_id<2: self.dimenciones[self.jugadores_id][0]=peticion[1] self.dimenciones[self.jugadores_id][1]=peticion[2] self.tamaño_barra.append(int(self.dimenciones[self.jugadores_id][1])//5) self.inicio_jugadores.append(int(self.dimenciones[self.jugadores_id][1])//2) self.inicio_jugadores.append(int(self.dimenciones[self.jugadores_id][1])//2) self.pelota_posicion[self.jugadores_id][0]=int(self.dimenciones[self.jugadores_id][0]) // 2 self.pelota_posicion[self.jugadores_id][1]=int(self.dimenciones[self.jugadores_id][1]) // 2 self.pelota_posicion[self.jugadores_id+1][0]=int(self.dimenciones[self.jugadores_id][0]) // 2 self.pelota_posicion[self.jugadores_id+1][1]=int(self.dimenciones[self.jugadores_id][1]) // 2 mensaje=["se puede"],[self.jugadores_id],[self.tamaño_barra[self.jugadores_id]],[self.inicio_jugadores[0]],[self.inicio_jugadores[1]] self.jugadores_id=self.jugadores_id+1 conexion.send(codificar_mensaje(mensaje)) elif peticion[0] == "abajo": self.inicio_jugadores[int(peticion[1])] =int( self.inicio_jugadores[int(peticion[1])] + (10 * self.velocidad_jugador)) print(codificar_mensaje([self.inicio_jugadores[int(peticion[1])]]),"arriba") conexion.send(codificar_mensaje([self.inicio_jugadores[int(peticion[1])]])) elif peticion[0] == "arriba": self.inicio_jugadores[int(peticion[1])] = int(self.inicio_jugadores[int(peticion[1])] - (10 * self.velocidad_jugador)) print(codificar_mensaje([self.inicio_jugadores[int(peticion[1])]]),"abajo") conexion.send(codificar_mensaje([self.inicio_jugadores[int(peticion[1])]])) elif peticion[0]=="actualizar": respuesta=[self.inicio_jugadores[0]],[self.inicio_jugadores[1]],[self.pelota_posicion[int(peticion[1])][0]],[self.pelota_posicion[int(peticion[1])][1]] conexion.send(codificar_mensaje(respuesta)) print(respuesta,"actualizar") conexion.close() def mover(self,event,jugador): if event.char=="s": if self.inicio_jugadores[jugador]<self.dimenciones[(jugador+1)*2]*0.8: self.inicio_jugadores[jugador]=self.inicio_jugadores[jugador]+(10*self.velocidad_jugador) return str(self.inicio_jugadores[jugador]) else: return "muy abajo" elif event.char=="w": if self.inicio_jugadores[jugador]<self.dimenciones[(jugador+1)*2]*0.8: self.inicio_jugadores[jugador] = self.inicio_jugadores[jugador] - (10 * self.velocidad_jugador) return str(self.inicio_jugadores[jugador]) else: return "muy arriba" def tiempo_ejecucion(self): while self.puntuacion_j1 < 10 and self.puntuacion_j2 < 10: if self.turno == "jugador1": self.choque_margen_x() self.timer.sleep(0.05) def choque_margen_x(self): y=self.pelota_y-self.pelota_y_ant x=self.pelota_x-self.pelota_x_ant self.canvas.delete("pelota") if self.y-150<=self.pelota_y: if self.direccion==3: self.direccion =1 self.mover_pelota() print("paso por 1") elif self.direccion==2: self.direccion =0 self.mover_pelota() print("paso por 2") elif self.pelota_y<30: if self.direccion==1: self.cambio_direccion(3) self.mover_pelota() print("paso por 3") elif self.direccion==0: self.cambio_direccion(2) self.mover_pelota() print("paso por 4") if self.x-30<self.pelota_x: if self.direccion==1: self.cambio_direccion(0) self.mover_pelota() print("paso por 5") elif self.direccion==3: self.cambio_direccion(2) self.mover_pelota() print("paso por 6") if self.pelota_y>=self.inicio_j1_y and self.pelota_y<=self.inicio_j1_y+200 and self.pelota_x<=50 and self.pelota_x>40: print("paso por aqui xd") if self.direccion==0: self.cambio_direccion(1) self.mover_pelota() elif self.direccion==2: self.cambio_direccion(3) self.mover_pelota() if self.pelota_x<30: print("punto para el j1") if self.y-150>=self.pelota_y and self.pelota_y>30 and self.x-30>self.pelota_x and self.pelota_x>=30: print("paso por 9") self.mover_pelota() 'self.canvas.create_line(50, self.inicio_j1_y, 50, self.inicio_j1_y + 200, fill="white", width=15, tags="jugador1")' def mover_pelota(self): y=self.pelota_y-self.pelota_y_ant x=self.pelota_x-self.pelota_x_ant self.pelota_y_ant=self.pelota_y self.pelota_x_ant=self.pelota_x if x<0: x=x*-1 if y<0: y=y*-1 if self.direccion==0: self.pelota_y = self.pelota_y_ant - y self.pelota_x = self.pelota_x_ant - x elif self.direccion==1: self.pelota_y = self.pelota_y_ant - y self.pelota_x = self.pelota_x_ant + x elif self.direccion==2: self.pelota_y = self.pelota_y_ant + y self.pelota_x = self.pelota_x_ant - x elif self.direccion==3: self.pelota_y = self.pelota_y_ant + y self.pelota_x = self.pelota_x_ant + x self.canvas.create_rectangle(self.pelota_x - 15, self.pelota_y - 15, self.pelota_x + 15, self.pelota_y + 15, fill="white", tags="pelota") def cambio_direccion(self,direccion): self.direccion=direccion self.velocidad_pelota_y=random.randint(10,25) self.velocidad_pelota_y=random.randint(10,25) pong = pong() ''' root = Tk() def key(event,ro): print ("pressed", repr(event.char)) print(ro) def callback(event): print ("clicked at", event.x, event.y) print(root) canvas= Canvas(root) canvas.place(x=0,y=0,height=100,width=100) canvas.focus_set() canvas.bind("<Key>",lambda event: key(event,root)) canvas.bind("<Button-1>", callback) canvas.pack() root.mainloop() '''<file_sep>/pruebas/pruebas aisladas/pickes dump load.py import io import pickle import venv import sys sys.path.append("C:/Users/ricar/PycharmProjects/v-version/venv/pruebas aisladas/objetos pruebas") from ob1 import arbol a=arbol() a.crece() a.mostrar() a.obtener_vec() with open("C:/Users/ricar/PycharmProjects/v-version/venv/pruebas aisladas/objetos pruebas/pickled_obj", "wb") as f: pickle.dump(a, f) with open("C:/Users/ricar/PycharmProjects/v-version/venv/pruebas aisladas/objetos pruebas/pickled_obj", "rb") as f: b = pickle.load(f) print(a==b) print(a,b) a.mostrar() b.mostrar()<file_sep>/v-2/algoritmo modificado del vecino mas cercano/vmp mod.py from tkinter import * import tkinter as tk import random import pickle import sys import time import threading class vmp(): def __init__(self): 'iteraciones' self.cantidad_iteraciones=100 self.rango_maximo=200 self.cantidad_nodos=10 self.vent=Tk() self.vent.geometry("1250x750") self.canvas= Canvas(self.vent,bg="white") self.canvas.place(x=250,y=0,width=1000,height=750) self.b = Button(self.vent, command=self.vent_matriz, text="mostrar matriz") self.b.place(x=50, y=100, width=150, height=50) self.boton_maquina_type = Button(self.vent, command=self.inicio_mt , text="comenzar "+str(self.cantidad_iteraciones)+" pruebas") self.boton_maquina_type.place(x=50, y=150, width=150, height=50) '''self.resultado = Text(self.vent) self.resultado.place(x=25, y=200, relheight=0.5, width=200)''' 'self.hilo_mainloop=threading.Thread(name="mainloop",target= self.vent.mainloop())' self.hilo_creador= threading.Thread(name="creador",target=self.maquina_type1) self.vent.mainloop() def inicio_mt(self): 'self.hilo_creador.start()' self.maquina_type1() def maquina_type1(self): suma_vmp=0 suma_vmp_mod=0 mejora_nodos=0 self.iteraciones_actual = 1 cantidad_aplicada=0 for i in range(self.cantidad_iteraciones): t=random.randint(4,self.cantidad_nodos) self.generador_matriz(random.randint(0,t-1),t) self.mostrar_nodos() self.proceso_tsp() a=self.camino_final() suma_vmp+=a[0] suma_vmp_mod+= a[1] mejora_nodos+=(a[0]-a[1])/a[2] if (a[0] != a[1]): cantidad_aplicada+=1 '''if(a[0]!=a[1]) and self.iteraciones_actual>450 and a[2]<7: break''' print("iteracion: ",self.iteraciones_actual) print("----------------------------") print("datos generales: ") print("cantidad de pruebas: ",self.cantidad_iteraciones) print("rango posible para los nodos generados: ", self.rango_maximo) 'print("---------------------------------------------")' print("total de unidades reccorridas por el algoritmo Heurístico del vecino más próximo: ",suma_vmp) print("total de unidades reccorridas por la modificacion: ",suma_vmp_mod) print("total de unidades ahorradas: ",suma_vmp-suma_vmp_mod) print("se aplico en un total de: ", cantidad_aplicada, "casos, es decir", 100*(cantidad_aplicada/self.cantidad_iteraciones),"%") print("promedio de mejora por todas las iteraciones: ",(suma_vmp-suma_vmp_mod)/self.cantidad_iteraciones) print("promedio de mejora solo en las modificaciones",(suma_vmp-suma_vmp_mod)/cantidad_aplicada ) print("porcentaje de mejora en funcion de su camino reccorrido: ",(1- (suma_vmp_mod/suma_vmp))*100,"%") print("mejora en funcion de sus nodos", mejora_nodos/cantidad_aplicada) def generador_matriz(self,nodo_inicio,tamaño_matriz): 'inicio de matriz distancias' self.matriz = [] 'definicion de nodo inicio' self.nodo_inicio = nodo_inicio self.tamaño = tamaño_matriz 'generacion aleatorea de una matriz' for i in range(self.tamaño): self.matriz.append([]) for j in range(self.tamaño): self.matriz[i].append(random.randint(0, self.rango_maximo)) 'guardar matriz' ''' r2 = "C:/Users/ricar/OneDrive/Desktop/Nueva carpeta (3)/prueba.txt" c = open(r2, "wb") c.write(pickle.dumps(self.matriz)) c.close() ''' 'cargar matriz' ''' r2 = "C:/Users/ricar/OneDrive/Desktop/Nueva carpeta (3)/prueba.txt" c = open(r2, "rb") self.matriz = pickle.loads(c.read()) c.close()''' def mostrar_nodos(self): self.canvas.delete("all") tam=750//self.tamaño columnas=int((self.tamaño**(0.5))//1) l=0 x=0 y=75 'vector de nodos random.randint(0,tam/2)' self.canvas.create_text(150, 20, fill="black", font="Times 12 italic bold", text="el nodo inicial es :"+str(self.nodo_inicio+1) + " Iteracion actual: "+str(self.iteraciones_actual), tags=str(l)) 'define el lugar donde esta cada nodo' self.iteraciones_actual+=1 self.nodos =[] while(l!=self.tamaño): if (l%columnas==0): y+=random.randint(tam//4,tam) x=random.randint(tam//4,tam) x+=random.randint(tam//4,tam) l+=1 self.nodos.append((x,y)) self.canvas.create_text(x, y, fill="black", font="Times 20 italic bold", text=str(l),tags=str(l)) 'carga vista de la matriz en otra ventana ahora inrrelevante' 'self.vent_matriz()' 'creacion de las relaciones en el canvas' for i in range(self.tamaño): for j in range(self.tamaño): if self.matriz[i][j]!=0: self.canvas.create_line(self.nodos[i],self.nodos[j], fill="orange") def proceso_tsp(self): 'proceso de tsp' self.caminos = [] 'despues vemos' 'self.nodos_sin_coneccion = []' self.nodos_libres = [] self.nodos_usados = [] self.vuelta = [] for i in range(0,self.tamaño): if i!=self.nodo_inicio: self.nodos_libres.append(i) self.nodos_usados.append(self.nodo_inicio) 'print(self.nodos_libres, "libres", self.nodo_inicio," usados",self.nodos_usados)' 'print(self.matriz)' o=0 while True: 'empieza lo molesto' self.nodos_usados.append(self.obtener_sgte_camino(self.nodos_libres,self.nodos_usados[len(self.nodos_usados)-1])) 'print("usados",self.nodos_usados)' self.nodos_libres.remove(self.nodos_usados[len(self.nodos_usados)-1]) 'print("libres", self.nodos_libres, len(self.nodos_libres))' aux= self.nodos_libres.copy() self.vuelta= self.obtener_camino_de_vuelta(aux) 'print("vuelta",self.vuelta)' 'print("libres", self.nodos_libres,len(self.nodos_libres))' 'arma los posibles caminos' aux=self.vuelta.copy() aux.reverse() self.caminos.append(self.nodos_usados+ aux) 'print("-----------------------------")' if (self.obtener_sgte_camino(self.nodos_libres,self.nodos_usados[len(self.nodos_usados)-1])==self.vuelta[len(self.vuelta)-1]): self.vuelta.reverse() self.caminos.append(self.nodos_usados+self.vuelta) break if len(self.nodos_libres)<=2: self.vuelta.reverse() self.caminos.append(self.nodos_usados + self.vuelta) break else: o+=1 if o==self.tamaño*2: print("termino por o") break self.caminos.append(self.puro_vmp()) def camino_final(self): 'obtiene el camino mas corto y lo marca' min = self.obtener_resultado(self.caminos[0])[self.tamaño] id = 0 a = -1 for i in self.caminos: a += 1 '''print("camino n°",a,i,"posee un resultado total de: ",self.obtener_resultado(i) ) print('resultado',self.obtener_resultado(i)[self.tamaño],"min",min)''' if self.obtener_resultado(i)[self.tamaño] <= min: min = self.obtener_resultado(i)[self.tamaño] id = a print(self.caminos[id], "final", self.obtener_resultado(self.caminos[id])) print(self.caminos[len(self.caminos) - 1], "vmp", self.obtener_resultado(self.caminos[len(self.caminos) - 1])) for i in range(self.tamaño): self.canvas.create_line(self.nodos[self.caminos[id][i]], self.nodos[self.caminos[id][i + 1]], fill="blue") regreso=[] regreso.append(self.obtener_resultado(self.caminos[len(self.caminos) - 1])[self.tamaño]) regreso.append (self.obtener_resultado(self.caminos[id])[self.tamaño]) regreso.append(self.tamaño) return regreso 'carga todo en un formato para el txt pero ahora no importa, ' ''' print(self.caminos[id], "final", self.obtener_resultado(self.caminos[id])) print(self.caminos[len(self.caminos) - 1], "vmp", self.obtener_resultado(self.caminos[len(self.caminos) - 1])) resultado="El camino optimo esta dado por el recorrido :\n" for i in range(self.tamaño+1): resultado+="nodo "+str(self.caminos[id][i]+1) + ", " resultado+="con un resultado total de :"+str(self.obtener_resultado(self.caminos[id])[self.tamaño])+"\n" resultado+="en comparacion con su vmp puro = "+ str(self.caminos[len(self.caminos) - 1])+ "vmp" +str( self.obtener_resultado(self.caminos[len(self.caminos) - 1])) self.resultado.insert(tk.END,resultado)''' def puro_vmp(self): v=[] v.append(self.nodo_inicio) nodos_libres=[] for i in range(0,self.tamaño): if i!=self.nodo_inicio: nodos_libres.append(i) 'print(nodos_libres)' for i in range(0,self.tamaño-2): v.append(self.obtener_sgte_camino(nodos_libres,v[len(v)-1])) nodos_libres.remove(v[len(v)-1]) 'print(nodos_libres)' v.append(nodos_libres[0]) '''if (self.matriz[v[len(v)-1]][0]>self.matriz[v[len(v)-1]][1]): v.append(nodos_libres[1]) v.append(nodos_libres[0]) else: v.append(nodos_libres[0]) v.append(nodos_libres[1])''' v.append(self.nodo_inicio) return v def obtener_resultado(self,vect): s=[] for i in range(len(vect)-1): s.append(self.matriz[vect[i]][vect[i+1]]) sum=0 for i in range(len(s)): sum+=s[i] s.append(sum) return s def obtener_sgte_camino(self,vector,nodo_actual): 'pasar solo el vector con los nodos libres' if(nodo_actual==0): sgte=vector[1] else: sgte=vector[0] for i in range(len(vector)): 'print("vector [",i,"]",vector[i])' if(self.matriz[nodo_actual][vector[i]]<self.matriz[nodo_actual][sgte]) and (self.matriz[nodo_actual][vector[i]]!=0): sgte=vector[i] 'devuelve el sgte nodo a usar' return sgte def obtener_camino_de_vuelta(self,vector): 'pasar solo los nodos que son para el camino de vuelta, sin los usados, es decir los libres' l=0 camino=[] pivote=self.nodo_inicio camino.append(pivote) x=True tamaño=len(vector) while x: 'print("vector",vector)' min=vector[0] for i in vector: if (self.matriz[pivote][i]<self.matriz[pivote][min]) and (self.nodo_inicio!=i) and (self.matriz[pivote][i]!=0) : min=i vector.remove(min) camino.append(min) pivote=min if len(camino)==tamaño+1: x=False return camino def vent_matriz(self): vent=Tk() vent.geometry("750x750") for i in range(self.tamaño): for j in range(self.tamaño): if j!=i: x=str(self.matriz[i][j]) a=Entry(vent) a.grid(row=i,column=j) a.insert(0,x) else: Label(vent,text="---").grid(row=i,column=j) vmp()<file_sep>/pruebas/pruebas aisladas/p1.py from tkinter import * # Carga módulo tk (widgets estándar) from tkinter import ttk # Carga ttk (para widgets nuevos 8.5+) rc=Tk() rc.title("Panel de pestañas en Tcl/Tk") rc.geometry("500x250") frame1 = Frame(rc,bd=5,cursor="hand1",bg="blue") frame1.config(width=480,height=320) frame1.pack(side=BOTTOM) redbutton = Button(frame1, text="Red", fg="red") redbutton.pack( side = LEFT) frame2 = Frame(rc,bd=5,cursor="hand2") frame2.pack(side=RIGHT) frame2.config(width=480,height=320) redbutton2 = Button(frame2, text="Red", fg="red") redbutton2.pack( side = LEFT) nt= ttk.Notebook(rc) redbutton3 = Button(nt, text="Red", fg="red") redbutton3.pack( side = LEFT) rc.mainloop() <file_sep>/pruebas/prueba v1/menu.py import socket import string import sys import datetime import pickle import _compat_pickle import threading from tkinter import * import os sys.path.append("C:/Users/ricar/PycharmProjects/v-version/venv/prueba v1/buscaip.py") from buscaip import * class trasmisor(): def __init__(self,ip): self.ip=ip self.archivo=None self.ruta=NONE self.vent=Tk() self.vent.geometry("300x100") self.text= Entry(self.vent) self.text.place(relx=0.05,rely=0.05,relwidth=0.9,relheight=0.45) self.boton= Button(self.vent,command=lambda :self.transferir()) self.boton.place(relx=0.05,rely=0.6,relheight=0.3,relwidth=0.4) self.buffer=1024 self.vent.mainloop() def transferir(self): self.s =socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.dir=((self.ip,8000)) self.s.connect(self.dir) self.s.sendto(str(self.ip).encode(),(self.dir)) if (self.s.recv(self.buffer).decode()=="listo"): self.vent.destroy() self.s.close() class menu(): def __init__(self): self.limites_conecciones=10 self.vent= Tk() self.vent.geometry("500x500") self.list=Listbox(self.vent) self.list.place(relx=0.1,rely=0.15,relwidth=0.5,relheight=0.5) self.list.bind('<<ListboxSelect>>', lambda event :self.imprimir(event,2)) self.list.config(state=DISABLED) self.actualizar_boton= Button(self.vent,text="actualizar",command=lambda:self.actualizar_comando()) self.actualizar_boton.place(relx=0.15,rely=0.75,relwidth=0.1,relheight=0.05) self.b=Button(self.vent,text="empezar",command=lambda :self.empezar()) self.b.place(relx=0.5,rely=0.75,relwidth=0.1,relheight=0.05) self.hilo_servidor=threading.Thread(name="servidor",target=self.servidor) self.hilo_servidor.start() self.hilo_mainloop=threading.Thread(name="mainloop",target=self.vent.mainloop()) self.hilo_mainloop.start() def servidor(self): print("empezo a funcionar") self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.s.bind(('', 8000)) self.s.listen(self.limites_conecciones) self.buffer = 1024 while True: self.conexion, self.direccion = self.s.accept() self.ip = self.conexion.recv(self.buffer).decode() self.conexion.sendto("listo".encode(), self.direccion) self.conexion.close() break print("termino hilo servidor") self.vent.destroy() def empezar(self): self.empezar=trasmisor(socket.gethostbyname(socket.gethostname())) 'print (socket.gethostbyname(socket.gethostname()))' def imprimir(self,event,im): trasf=trasmisor(self.list.get(self.list.curselection()[0])) 'print(self.list.get(self.list.curselection()[0]))' def actualizar_comando(self): gestor_ip=gestor(5,0,100) if gestor_ip.estado: i=0 'self.list.config(state=e)' self.list.config(state=NORMAL) for ip in gestor_ip.obtener_ips(): self.list.insert(i,ip) i+=1 else: print("no se pudo cargar ips") menu= menu() <file_sep>/pruebas/prueba servidor-cliente/servidor-pong.py import socket import sys sys.path.append("C:/Users/ricar/PycharmProjects/v-version/venv/prueba servidor-cliente/j1.py") sys.path.append("C:/Users/ricar/PycharmProjects/v-version/venv/prueba servidor-cliente/prueba.py") from prueba import * print("empieza") s= socket.socket() s.bind(('localhost',8000)) s.listen(1) i=0 while True: conexion, direccion= s.accept() peticion=conexion.recv(1024).decode() print(peticion) if peticion=="jugador 1 esperando": i=i+1 print(i) if i==3: print("se envio ") conexion.send("se puede".encode()) elif peticion=="arriba": '' conexion.close() <file_sep>/pruebas/pruebas aisladas/pestañas y su ejecucion.py from tkinter import * import tkinter as tk from tkinter import ttk from tkinter import messagebox from pynput.mouse import Button as Mouse_button, Controller import xml.etree.ElementTree as ET def archivoxml(): bd = ET.Element("base") ventana = ET.SubElement(bd, "ventana", name="ventana-consultas") ventana_hide = ET.SubElement(ventana, "ventana-hide", ) ventana_hide.set("option-hide", "0") ET.dump(bd) tree = ET.ElementTree(bd) tree.write("C:/Users/ricar/Desktop/pruebas v1/pruebasv1.xml") def modificar_leer_xml(): estructura_xml = ET.parse("C:/Users/ricar/Desktop/pruebas v1/pruebasv1.xml") # Obtiene el elemento raíz: raiz = estructura_xml.getroot() print("primer for") for elemento_hijo in raiz: print(elemento_hijo) print("segundo for") for ventana in raiz.findall("ventana"): print(ventana.find("ventana-consultas")) for ventana in raiz.iter('ventana'): ventana.text = "nuevotexto" ventana.set("option-hide", "1") print(ventana.get("option-hide")) estructura_xml.write("C:/Users/ricar/Desktop/pruebas v1/pruebasv1.xml") def opciones(event): mouse= Controller() mouse.click(Mouse_button.left,1) Varialbe_ubicacion = "{0}x{0}+" + str(vent.winfo_pointerx()) + "+" + str(vent.winfo_pointery()) '''root.geometry("{0}x{0}+0+0".format(root.winfo_screenwidth(), root.winfo_screenheight()))''' opciones_vent.geometry(Varialbe_ubicacion.format(175, 40)) opciones_vent.deiconify() '''se a abierto una ventana modificar el xml''' def crear(): frame.append(Frame(note)) frame[len(frame)-1].bind("<<FocusIn>>", f) note.add(frame[len(frame) - 1], text="Consulta") consulta.append(Entry(frame[len(frame)-1])) consulta[len(consulta)-1].place(x=0,y=0,relheight=1,relwidth=1) opciones_vent.withdraw() ''' print("framme") print(frame) print("text") print(consulta) ''' def hola(): try: indice_notebook_general=note.index(tk.CURRENT) except: indice_notebook_general=0 print(indice_notebook_general) def cerrar(): note.select(note.index(tk.CURRENT)) note.forget(note.index(tk.CURRENT)) frame.pop(note.index(tk.CURRENT)) consulta.pop(note.index(tk.CURRENT)) print(len(consulta)) print(len(frame)) opciones_vent.withdraw() ''' mause.click(vent.winfo_pointerx(),vent.winfo_pointery())''' def opciones_withdraw(): '''se a abierto una ventana modificar el xml''' estructura_xml = ET.parse("C:/Users/ricar/Desktop/pruebas v1/pruebasv1.xml") # Obtiene el elemento raíz: raiz = estructura_xml.getroot() for ventana in raiz.iter('ventana'): if int(ventana.get("option-hide"))==1: ventana.set("option-hide","0") opciones_vent.withdraw() else: ventana.set("option-hide","1") estructura_xml.write("C:/Users/ricar/Desktop/pruebas v1/pruebasv1.xml") def esconder_opciones(event): opciones_withdraw() def f(event): print("focus") print(note.index(tk.CURRENT)) ''' print(str(note.index(ttk.CURRENT())))''' def notebook_cambio(event): print(note.index(tk.CURRENT)) print("cambio") '''ButtonRelease-1''' '''ubicacion[0]--> eje x , [1]-->y''' def ver(): print(note.tabs()) for i in range(len(note.tabs())): print(note.tab(i)) ''' print(note.identify(x,y))''' ''' print(note.tab(0, option=identify(x,y))) ''' frame=[] consulta=[] opciones_vent= Tk() butons= Button(opciones_vent) boton_crear = Button(opciones_vent, text="Crear", command=crear,cursor="hand2",relief=FLAT) boton_crear.place(x=0,rely=0,relheight=0.2,relwidth=1) boton_cerrar = Button(opciones_vent, text="Cerrar", command=cerrar,cursor="hand2",relief=FLAT) boton_cerrar.place(x=0,rely=0.2,relheight=0.2,relwidth=1) opciones_vent.overrideredirect(1) opciones_vent.geometry("200x100") opciones_vent.withdraw() opciones_vent.bind("<FocusOut>",esconder_opciones) vent= Tk() vent.geometry("500x250") note = ttk.Notebook(vent) note.pack(fill="both",expand="yes") note.bind("<3>",opciones) vent.bind("<1>",esconder_opciones) note.bind("<<NotebookTabChanged>>",notebook_cambio) boton=Button(vent,command=ver,text="ver").pack() vent.mainloop() <file_sep>/pruebas/pruebas aisladas/tiempos de ejecucion.py from timeit import timeit from time import time import xml.etree.ElementTree as ET '''for i in range(0,100): print(timeit("'Hello, world!'.replace('Hello', 'Goodbye')"))''' # Start counting. start_time = time() # Take the original function's return value. # Calculate the elapsed time. bd=ET.Element("base") ventana=ET.SubElement(bd,"ventana", name="ventana-consultas") ventana_hide=ET.SubElement(ventana,"ventana-hide",) ventana_hide.set("option-hide","false") ET.dump(bd) tree = ET.ElementTree(bd) tree.write("C:/Users/ricar/Desktop/pruebas v1/pruebasv1.xml") estructura_xml = ET.parse("C:/Users/ricar/Desktop/pruebas v1/pruebasv1.xml") # Obtiene el elemento raíz: raiz = estructura_xml.getroot() '''for ventana in raiz.findall('ventana'): print(ventana) print("espacio1") print(ventana.get("option-hide")) print("nada") ''' for ventana in raiz.iter('ventana'): print("get: "+str(ventana.get("option-hide"))) ventana.set("option-hide","0") print(ventana.get("option-hide")) estructura_xml.write("C:/Users/ricar/Desktop/pruebas v1/pruebasv1.xml") '''v=[] for i in range(100): v.append("gkaseqwoeqwpwkq"*10000) v[i]="gkaseqwoeqwpwkq"''' elapsed_time = time() - start_time print(time()) print(start_time) print("Elapsed time: %0.10f seconds." % elapsed_time) <file_sep>/pruebas/prueba servidor-cliente/pong v-fall/gui-clientre.py from tkinter import * # Carga módulo tk (widgets estándar) from tkinter import ttk # Carga ttk (para widgets nuevos 8.5+) import socket import sys import datetime from tkinter import messagebox import time import threading import random 'sys.path.append("C:/Users/ricar/PycharmProjects/v-version/venv/prueba servidor-cliente/prueba.py")' import keyboard class gui_pong(): def __init__(self): self.ventana=Tk() self.ventana.geometry("250x250") self.inicio_jugadores_y=[] self.pelota_x=0 self.pelota_y=0 self.conexion=None self.boton=Button(self.ventana,command=self.imprimir_conexion(),text="imprimir conexion").pack(side="top") self.ventana.mainloop() def imprimir_conexion(self): print(self.conexion) d=gui_pong() <file_sep>/pruebas/prueba v1/servidor.py import socket import pickle import threading import time import random class servidor(): def __init__(self,ip1,ip2): print("inicio servidor") self.ip=[] self.ip.append(ip1) self.ip.append(ip2) self.bandera=0 'self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)' 'self.ip=socket.gethostbyname(socket.gethostname())' 'velocidad de los objetos' self.jugador_velocidad=0 self.vel_x=0 self.vel_y=0 self.puerto_recive_j1=8000 self.puerto_enviar_j1=8001 self.puerto_recive_j2=8002 self.puerto_enviar_j2=8003 self.velocidad_jugador() 'variables usadas en el envio / recive' '''self.socket_envia=[] self.socket_recive=[]''' '''x = self.ventana.winfo_screenwidth() y = self.ventana.winfo_screenheight()''' self.jugador_posicion=[] self.jugador_posicion.append((800*0.8)*0.25) self.jugador_posicion.append((800 * 0.8) * 0.25) self.tope_izquierda=(1500*0.8)*0.1 self.tope_derecha=(1500*0.8)*0.9 self.tope_arriba=(800*0.8)*0.1 self.tope_abajo=800*0.8*0.9 'el tope de abajo tiene q considerar el tamaño de la barra ' self.tamaño_barra=800*0.8*0.5 self.tope_abajo_jugador=((800*0.8)*0.9)-self.tamaño_barra x=(1500*0.8)//2 y=(800*0.8)//2 t=x*0.01 self.pelota_posicion=[] self.pelota_posicion.append(x-t) self.pelota_posicion.append(y-t) 'self.conexion(0,8001,8000)' self.establecer_conexion() while True: if self.bandera==2: print("se an iniciado las 2") break self.hilo_pelota_movimiento=threading.Thread(name="movimiento",target=self.movimiento) self.hilo_pelota_movimiento.start() def establecer_conexion(self): '''self.puerto_recive_j1=8000 self.puerto_enviar_j1=8001 self.puerto_recive_j2=8002 self.puerto_enviar_j2=8003''' self.hilo_conexion1=threading.Thread(name=self.ip[0],target=self.conexion_j1) self.hilo_conexion2 = threading.Thread(name=self.ip[1], target=self.conexion_j2) self.hilo_conexion1.start() self.hilo_conexion2.start() def conexion_j1(self): 'para j1' 'envia' while True: try: self.socket_envia_j1=socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket_envia_j1.connect((self.ip[0], self.puerto_enviar_j1)) break except: '' 'se establece el recive' self.socket_recive_j1=socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket_recive_j1.bind((self.ip[0], self.puerto_recive_j1)) self.socket_recive_j1.listen(1) self.conexion_recive_j1, self.direccion_recive_j1 = self.socket_recive_j1.accept() self.bandera+=1 'inicia el revice . envia del j1' self.hilo_recive=threading.Thread(name="recive",target=self.recive_j1) self.hilo_recive.start() self.hilo_envia=threading.Thread(name="envia",target=self.envia_j1) self.hilo_envia.start() def conexion_j2(self): 'para j2' 'envia' while True: try: self.socket_envia_j2=socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket_envia_j2.connect((self.ip[1], self.puerto_enviar_j2)) break except: '' 'se establece el recive' self.socket_recive_j2=socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket_recive_j2.bind((self.ip[1], self.puerto_recive_j2)) self.socket_recive_j2.listen(1) self.conexion_recive_j2, self.direccion_recive_j2 = self.socket_recive_j2.accept() self.bandera+=1 'inicia el recive-envia j2' self.hilo_recive=threading.Thread(name="recive",target=self.recive_j2) self.hilo_recive.start() self.hilo_envia=threading.Thread(name="envia",target=self.envia_j2) self.hilo_envia.start() def velocidad_jugador(self): self.jugador_velocidad+=10 def movimiento(self): print("inicia movimiento") while True: self.velocidad(random.randint(0, 4)) break while True: 'posicion actual' self.pelota_posicion[0] += self.vel_x self.pelota_posicion[1] += self.vel_y print(self.pelota_posicion) if self.pelota_posicion[1]>=self.tope_abajo: if self.direccion==2: self.velocidad(0) elif self.direccion==3: self.velocidad(1) if self.pelota_posicion[1]<=self.tope_arriba: if self.direccion==0: self.velocidad(2) elif self.direccion==1: self.velocidad(3) if self.pelota_posicion[0]>=self.tope_derecha: if self.direccion==1: self.velocidad(0) elif self.direccion==3: self.velocidad(2) if self.pelota_posicion[0]<= self.tope_izquierda: if self.direccion==0: self.velocidad(1) elif self.direccion==2: self.velocidad(3) time.sleep(1) def velocidad(self,dir): 'cambia la direccion accionando por la velocidad' self.direccion=dir if self.direccion==0: self.vel_x=random.randint(20,51)*-1 self.vel_y=random.randint(20,51)*-1 elif self.direccion==1: self.vel_x = random.randint(20, 51) self.vel_y = random.randint(20, 51) *-1 elif self.direccion==2: self.vel_x = random.randint(20, 51) *-1 self.vel_y = random.randint(20, 51) elif self.direccion==3: self.vel_x = random.randint(20, 51) self.vel_y = random.randint(20, 51) def envia_j1(self): 'para j1' print("inicia envio j1") while True: 'envia posicion de jugador 1 y polota posicion' self.socket_envia_j1.sendto(pickle.dumps(self.jugador_posicion+self.pelota_posicion), (self.ip[0], self.puerto_enviar_j1)) time.sleep(0.1) '''if (self.socket.recv(1024).decode()!="si"): break''' self.socket_envia[0].close() def recive_j1(self): 'para _j1' print("inicia recive j1") while True: self.peticion = self.conexion_recive_j1.recv(1024).decode() print(self.peticion) if self.peticion == "arriba" and self.jugador_posicion[0]>=self.tope_arriba : self.jugador_posicion[0]+=-self.jugador_velocidad if self.peticion == "abajo" and self.jugador_posicion[0]<=self.tope_abajo_jugador: self.jugador_posicion[0]+=self.jugador_velocidad self.coneccion_recive.close() def envia_j2(self): 'para _j2' print("inicia envio j1") while True: 'envia posicion de jugador 1 y polota posicion' self.socket_envia_j2.sendto(pickle.dumps(self.jugador_posicion+self.pelota_posicion), (self.ip[0], self.puerto_enviar_j2)) time.sleep(0.1) '''if (self.socket.recv(1024).decode()!="si"): break''' self.socket_envia_j2.close() def recive_j2(self): 'para j2' print("inicia recive j1") while True: self.peticion = self.conexion_recive_j2.recv(1024).decode() print(self.peticion) if self.peticion == "arriba" and self.jugador_posicion[1]>=self.tope_arriba : self.jugador_posicion[1]+=-self.jugador_velocidad if self.peticion == "abajo" and self.jugador_posicion[1]<=self.tope_abajo_jugador: self.jugador_posicion[1]+=self.jugador_velocidad self.coneccion_recive.close() servidor = servidor(socket.gethostbyname(socket.gethostname()),socket.gethostbyname(socket.gethostname())) <file_sep>/pruebas/pruebas aisladas/cliente-servidor/pruebas de envio binario/pong_server_2.py import binascii import socket import struct import sys class prueba(): def __init__(self): self.t=0 # Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = ('localhost', 10000) sock.bind(server_address) sock.listen(1) '''unpacker = struct.Struct('I 2s f ')''' unpacker=None while True: print('\nwaiting for a connection') connection, client_address = sock.accept() try: print("unpacker",unpacker) if unpacker==None: estructura = connection.recv(1024) print("estructura",estructura.decode()) unpacker=struct.Struct(estructura.decode()) else: data = connection.recv(unpacker.size) print('received {!r}'.format(binascii.hexlify(data))) unpacked_data = unpacker.unpack(data) print('unpacked:', unpacked_data) finally: 'connection.close()'<file_sep>/pruebas/pruebas aisladas/servidor constantes/servidor.py ''' import os import sys import platform from datetime import datetime import socket ip = socket.gethostbyname(socket.gethostname()) ipDividida = ip.split('.') try: red = ipDividida[0] + '.' + ipDividida[1] + '.' + ipDividida[2] + '.' print(red) comienzo = 0 fin = 100 except: print("[!] Error") sys.exit(1) if (platform.system() == "Windows"): ping = "ping -n 1" else: ping = "ping -c 1" tiempoInicio = datetime.now() print("[*] El escaneo se está realizando desde", red + str(comienzo), "hasta", red + str(fin)) asa=1 for subred in range(comienzo, fin + 1): direccion = red + str(subred) response = os.popen(ping + " " + direccion) for line in response.readlines(): if ("ttl" in line.lower()): print(subred) print(direccion, "está activo") break tiempoFinal = datetime.now() tiempo = tiempoFinal - tiempoInicio print("[*] El escaneo ha durado %s" % tiempo)''' import os import sys import platform import threading, subprocess from datetime import datetime import socket IPXHILOS = 1 ip = socket.gethostbyname(socket.gethostname()) ipDividida = ip.split('.') try: red = ipDividida[0] + '.' + ipDividida[1] + '.' + ipDividida[2] + '.' comienzo = 0 fin = 100 except: print("[!] Error") sys.exit(1) if (platform.system() == "Windows"): ping = "ping -n 1" else: ping = "ping -c 1" class Hilo(threading.Thread): def __init__(self, inicio, fin): self.ip=[] threading.Thread.__init__(self) self.inicio = inicio self.fin = fin def run(self): for subred in range(self.inicio, self.fin): direccion = red + str(subred) response = os.popen(ping + " " + direccion) for line in response.readlines(): if ("ttl" in line.lower()): self.ip.append(direccion) '''print(direccion, "está activo")''' break class gestor(): def __init__(self,cantidadhilos,redip,comienzog,fing,ipxhilosg): self.cantidadhilo=cantidadhilos self.comienzo=comienzog self.fin=fing self.iphilo=ipxhilosg self.hilo = [] self.ips=[] try: for i in range(self.cantidadhilo): self.finAux = self.comienzo + self.iphilo if (self.finAux >self.fin): self.finAux = self.fin h =Hilo(self.comienzo, self.finAux) h.start() self.hilo.append(h) self.comienzo =self.finAux except Exception as e: print("[!] Error creando hilos:", e) sys.exit(2) for hilo in self.hilo: hilo.join() def esperar(self): for h in self.hilo: if h.is_alive(): print("nada") else: print("hola") def obtener_ips(self): self.ips=[] for h in self.hilo: self.ips=self.ips + h.ip return self.ips tiempoInicio = datetime.now() print("[*] El escaneo se está realizando desde", red + str(comienzo), "hasta", red + str(fin)) NumeroIPs = fin - comienzo numeroHilos = int((NumeroIPs / IPXHILOS)) print("numeros de hilos: ",numeroHilos) g=gestor(numeroHilos,red,comienzo,fin,IPXHILOS) g.obtener_ips() g.obtener_ips() g.obtener_ips() print(len(g.ips)) print(g.ips) 'print(socket.gethostbyaddr(socket.gethostname()))' '''for ip in g.ips: try : print(socket.gethostbyaddr(ip)) print(ip) except: print("la ip:",ip,"da problemass") ''' 'print(socket.gethostbyaddr("192.168.2.15"))' tiempoFinal = datetime.now() tiempo = tiempoFinal - tiempoInicio print("[*] El escaneo ha durado %s" % tiempo)<file_sep>/pruebas/clase bd/usuario_gestor.py import socket import pickle import datetime import io import sys import os from usuario_data import datos_usuarios from usuario_secion import usuario_secion class gestor_usuarios(): def __init__(self): if os.path.exists("C:/Users/ricar/Desktop/pruebas v1/base/usuarios/usuarios.gu"): self.usuario = self.actualizar().usuario else: self.usuario = [] self.crear_usuario("rc","123456789","1111") print("no existe") def iniciar_secion(self,usuario,password): i= self.encontrar_usuario(usuario,password) print(i) if i>=0: if self.usuario[i].connectiosn_actuales<self.usuario[i].max_connections: self.usuario[i].connectiosn_actuales=+1 self.guardar() return "aceptado" else: return "el usuario a exedido el numero de conecciones" elif i==-1: return "contraseña no coinciden" elif i==-2: return "no existe el usuario" def cerrar_secion(self,usuario,password): i=self.encontrar_usuario(usuario,password) if i>=0: self.usuario[i].connectiosn_actuales=self.usuario[i].connectiosn_actuales+1 self.guardar() return "aceptado" elif i==-1: return "contraseña no coinciden" elif i==-2: return "no existe el usuario" self.usuario[i].connectiosn_actuales=self.usuario[i].connectiosn_actuales-1 self.guardar() del secion def encontrar_usuario(self,usuario,password): exist=False i=0 while not exist and i<len(self.usuario): if self.usuario[i].usuario == usuario: exist = True else: i = i + 1 if exist: if self.usuario[i].password == password: return i else: return -1 else: return -2 def crear_usuario(self,usuario,password,privilegios): exist=False i=0 while not exist and i<len(self.usuario): if self.usuario[i].usuario==usuario: exist=True i=i+1 if not exist: if len(password)>8: usuario_data=datos_usuarios(usuario,password,privilegios) self.usuario.append(usuario_data) print(self.usuario[0]) print("usuario creado") self.guardar() else: print("contraseña corta") else: print("usuario existente") def eliminar_usuario(self,usuario,password): i=self.encontrar_usuario(usuario,password) if i>=0: self.usuario.pop(i) self.actualizar() return i elif i==-1: return -1 elif i==-2: return -2 def guardar(self): with open("C:/Users/ricar/Desktop/pruebas v1/base/usuarios/usuarios.gu", "wb") as f: pickle.dump(self, f) def actualizar(self): with open("C:/Users/ricar/Desktop/pruebas v1/base/usuarios/usuarios.gu", "rb") as f: b = pickle.load(f) return b 'restablece las conecciones a 0' def restablece(self): for i in range(len(self.usuario)): self.usuario[i].connectiosn_actuales=0 self.guardar() ''' C:/Users/ricar/Desktop/pruebas v1/base/usuarios es la carpeta donde se guardaran los datos de los usuarios para el servidor C:/Users/ricar/Desktop/pruebas v1/base/secion usuario es la carpeta donde se guardaran las seciones de cada usuario (esta carpeta debera estar en cada terminal remota no en el servidor) ''' gu= gestor_usuarios() gu.restablece() ''' gu= gestor_usuarios() gu.restablece() '''''''gu= gestor_usuarios() for i in range (0,len(gu.usuario)): print(gu.usuario[i].usuario) print(gu.usuario[i].password) secion=gu.iniciar_secion("rc","123456789") print(sys.getsizeof(secion)) print(sys.getsizeof(gu))''' ''' gu= gestor_usuarios() gu.crear_usuario("rc","123456789","1111") secion = gu.iniciar_secion("rc","123456789") if type(secion)!=int: print(secion) gu.cerrar_secion(secion) else: print("no se pudo iniciar secion") for i in range (0,len(gu.usuario)): print(gu.usuario[i].usuario) print(gu.usuario[i].password) print(gu.usuario[i].last_connection) ''' '''print(gu.eliminar_usuario("rc2","12345678910"))''' <file_sep>/pruebas/pruebas aisladas/cliente-servidor/pruebas de envio binario/prueba de envio binario.py import binascii import socket import struct import sys class prueba(): def __init__(self): self.t=1 self.s=10 def armonizar(p): v=[] s="" v.append(p.t) 's+=str(type(v[0]))' v.append(p.s) 's+=str(type(v[1]))' s='I I' return s,v # Create a TCP/IP socket values = (1, b'ab', 2.7) values=prueba() armonizador , values=armonizar(values) packer = struct.Struct(armonizador) packed_data = packer.pack(*values) print('values =', values) i=0 for i in range (2): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = ('localhost', 10000) sock.connect(server_address) try: # Send data if i==0: print("1") print(armonizador.encode()) sock.send(armonizador.encode()) i+=1 else: print("2") print('sending {!r}'.format(binascii.hexlify(packed_data))) sock.sendall(packed_data) finally: print('closing socket') sock.close() <file_sep>/v-2/pruebas/administrador de archivos online/server.py import socket import pickle import threading import time import random import sys sys.path.append("v-2/pruebas/administrador de archivos online/gestor_file.py") from gestor_file import * class cliente: def __init__(self): self.ruta=[] def conectar(self,ip_servidor): self.ip_servidor=ip_servidor self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.connect((self.ip_servidor, 8000)) self.id=pickle.dumps(self.socket.recv(1024)) return pickle.dumps(self.socket.recv(1024)) def accion(self,peticion): self.socket.send(pickle.loads(peticion)) return pickle.dumps(self.socket.recv(1024)) class server: def __init__(self,conexiones_maximas,puerto,archivos): self.ip_server=socket.gethostbyname(socket.gethostname()) 'self.puertos=[]' self.puerto_libre=puerto self.max_conecciones=conexiones_maximas self.hilos=[] self.socket=socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.bind(('', 8000)) self.socket.listen(self.max_conecciones) self.conexiones=[] self.gestor_archivos=archivos self.contenidos_archivos=archivo_contenido() 'clientes' self.ruta_actual={} def iniciar_server(self): self.conexion_id=0 while True: self.conexiones.append(0) 'self.conexiones[self.conexion_id], direccion = self.conexiones.accept()' conexion , direccion = self.conexiones.accept() self.hilos.append(threading.Thread(name=str(self.conexion_id), target=self.gestor_conexiones,args={conexion,self.conexion_id})) self.hilos[self.conexion_id].start() self.conexion_id+=1 def gestor_conexiones(self,conexion,id_hilo): self.ruta_actual[id_hilo]=[] self.ruta_actual[id_hilo].append(0) 'enviarle el sistema de archivos actual desde el master' conexion.send(pickle.dumps(id_hilo)) conexion.send(pickle.dumps(self.gestor_archivos.busqueda_carpeta(self.ruta_actual[id_hilo]))) while True: peticion= pickle.loads(conexion.recv(1024)) 'todas las peticiones tiene el primer dato como lo que necesitan hacer y el segundo la ruta en string, exepcion de creacion de archivo que viene el archivo' 'peticion[0]= accion , pet[1]=situacion actual(nuevo elemento para la ruta), pet[2]=id del cliente, el resto es un caso especial' if peticion[0]=="abrir": self.ruta_actual[peticion[2]].append(peticion[1]) conexion.send(pickle.dumps(self.abrir(self.ruta_actual[peticion[2]]))) elif peticion[0]=="borrar": self.borrar(self.ruta_actual[peticion[2]]+peticion[1]) conexion.send(pickle.dumps(self.abrir(self.ruta_actual[peticion[2]]))) elif peticion[0] == "crear_carpeta": self.crear_carpeta(self.ruta_actual[peticion[2]]) conexion.send(pickle.dumps(self.abrir(self.ruta_actual[peticion[2]]))) elif peticion[0] == "crear_archivo": 'caso especial peticion => 0 es accion , 1 es archivo,2 es id, 3 es contenido' self.crear_archivo(self.ruta_actual[peticion[2]],peticion[1],peticion[3]) conexion.send(pickle.dumps(self.abrir(self.ruta_actual[peticion[2]]))) def abrir(self,ruta): 'abre un archivo o carpeta, o vuelve a la carpeta anterior (caso especial) ' 'falta tratar archivos' try: return self.gestor_archivos.busqueda_carpeta(ruta) except: print("recarge todo porque esta mal") return "error" def borrar(self,ruta): 'borra una carpeta o archivo' try: self.gestor_archivos.busqueda_carpeta(ruta).borrar() except: print("no hay tal elemento o ya se borro") def crear_carpeta(self,ruta): 'crea una carpeta' i=0 while True: if self.gestor_archivos.busqueda_carpeta(ruta).agregar_contenido(carpeta("nueva carpeta"+str(i)))!=-1: break else: i+=1 def crear_archivo(self,ruta,archivo,contenido): 'crea un archivo' if self.gestor_archivos.busqueda_carpeta(ruta).agregar_contenido(archivo)!=-1: ruta.append(archivo.nombre+"."+archivo.extencion) self.gestor_archivos.busqueda_carpeta(ruta).asigna_contenido(self.contenidos_archivos.agregar(contenido)) else: i=0 nombre=archivo.nombre while True: archivo.nombre=nombre+"copia " + str(i) if self.gestor_archivos.busqueda_carpeta(ruta).agregar_contenido(archivo) != -1: ruta.append(archivo.nombre + "." + archivo.extencion) self.gestor_archivos.busqueda_carpeta(ruta).asigna_contenido(self.contenidos_archivos.agregar(contenido)) break ax=archivo_contenido() sistema_de_archivos=carpeta("master") for i in range(10): sistema_de_archivos.agregar_contenido(archivo(str(i) + ".exe",ax.cantidad_archivos())) sistema_de_archivos.agregar_contenido(carpeta("carpeta 2")) sistema_de_archivos.agregar_contenido(carpeta("carpeta 1")) for i in sistema_de_archivos.contenido: if type(i) == carpeta: for l in range(5): i.agregar_contenido(archivo(str(l) + ".jpg",ax.cantidad_archivos())) 'recorrer(self.sistema_de_archivos)' server(2,8000,sistema_de_archivos)<file_sep>/pruebas/prueba servidor-cliente/pong v-fall/pong sin server.py from tkinter import * # Carga módulo tk (widgets estándar) from tkinter import ttk # Carga ttk (para widgets nuevos 8.5+) import socket import sys import datetime from tkinter import messagebox import time import threading import random 'sys.path.append("C:/Users/ricar/PycharmProjects/v-version/venv/prueba servidor-cliente/prueba.py")' from prueba import * import keyboard class pong(): def __init__(self): self.ventana=Tk() self.x = int(self.ventana.winfo_screenwidth()) self.y = int(self.ventana.winfo_screenheight()) xy = "{0}x{0}+" +"0" + "+" + "0" self.ventana.geometry((xy.format(self.x, self.y))) 'dimenciones x,y de los jugadores' self.tamaño_barra=self.y*0.2 'int(self.ventana.winfo_screenheight())' xy = "{0}x{0}+" +"0" + "+" + "0" ' self.ventana.geometry((xy.format(500, 500)))' self.velocidad_jugador=1 self.direccion=random.randint(0,3) 'donde inicia la barra' self.inicio_j1_y=int((self.y//3)*2) self.inicio_j2_y = int((self.y // 3) * 2) self.velocidad_pelota_x=15 self.velocidad_pelota_y=20 self.puntuacion_j1=0 self.puntuacion_j2=0 'se define todo en el inicio de secion' ''' self.pelota_x=[self.dimenciones[0]//2],[self.dimenciones[2]//2] self.pelota_y=[self.dimenciones[1]//2],[self.dimenciones[3]//2] ''' self.pelota_posicion_x=int((self.x//2)) self.pelota_posicion_y=int((self.y//2)) 'margenes' self.margen_y_arriba=(self.y*0.02) self.margen_y_abajo=(self.y*0.9) self.margen_x_izquierdo=30 self.margen_x_derecho=self.x-30 self.timer=time ''' self.servidor.hilo= threading.Timer(0.01,self.servidor_ejecucion()) self.servidor.hilo.start() ''' '''self.hilo_tiempo = threading.Timer(1, lambda: self.tiempo_ejecucion()) self.hilo_tiempo.start() self.hilo_mainloop=threading.Thread(self.ventana.mainloop()) self.hilo_mainloop.start() ''' self.canvas= Canvas(self.ventana,bg="black") self.canvas.place(relx=0,rely=0,relheight=1,relwidth=1) self.canvas.focus_set() self.canvas.create_line(self.margen_x_izquierdo, self.inicio_j1_y ,self.margen_x_izquierdo, self.inicio_j1_y+self.tamaño_barra ,fill="white",width=15,tags="jugador1") self.canvas.create_line(self.margen_x_derecho,self.inicio_j2_y ,self.margen_x_derecho, self.inicio_j2_y+self.tamaño_barra ,fill="white",width=15,tags="jugador2") self.canvas.create_rectangle(self.pelota_posicion_x,self.pelota_posicion_y,self.pelota_posicion_x+25,self.pelota_posicion_y+25,fill="white",tags="pelota") self.canvas.create_line(self.margen_x_izquierdo,self.margen_y_arriba,self.margen_x_derecho,self.margen_y_arriba,fill="white",width=5) self.canvas.create_line(self.margen_x_izquierdo, self.margen_y_abajo, self.margen_x_derecho, self.margen_y_abajo,fill="white",width=5) '''self.hilo_j1= threading.Thread(self.canvas.bind("<Key>",lambda event:self.mover_j1(event))) self.hilo_j2 = threading.Thread(self.canvas.bind("<Key>", lambda event: self.mover_j2(event))) self.hilo_j1.start() self.hilo_j2.start() ''' self.canvas.bind("<Key>", lambda event: self.mover(event)) ''' self.hilo_escuchaj2=threading.Thread(target=self.mover_jugador2()) self.hilo_escuchaj2.start() ''' self.hilo_actualizar= threading.Thread(target=self.tiempo_ejecucion) self.hilo_actualizar.start() ''' self.hilo_movimiento_jugadores=threading.Thread(target=self.mover) self.hilo_movimiento_jugadores.start()''' self.hilo_mainloop= threading.Thread(target= self.ventana.mainloop()) self.hilo_mainloop.start() def tiempo_ejecucion(self): print("inicio hilo t_eje") while self.puntuacion_j1 < 10 and self.puntuacion_j2 < 10: self.choque_margen() self.timer.sleep(0.05) def mover_j1(self,event): if event.char=="w": self.mover_jugador1_arriba() if event.char=="s": self.mover_jugador1_abajo() def mover_j2(self, event): if event.char == "i": self.mover_jugador2_arriba() if event.char == "k": self.mover_jugador2_abajo() def mover(self,event): ''' cambiar a lo de arriba de vuelta self.hilo_jugador1=threading.Thread(self.mover_jugador1(event.char)) self.hilo_jugador2=threading.Thread(self.mover_jugador2(event.char)) self.mover_jugador1(event.char) self.mover_jugador2(event.char) ''' ''' while TRUE: if keyboard.is_pressed("w"): print("uppp") sys.exit(0)''' if event.char=="w": self.mover_jugador1_arriba() if event.char=="s": self.mover_jugador1_abajo() ''' if event.char == "u": self.mover_jugador2_arriba() if event.char == "j": self.mover_jugador2_abajo()''' def mover_jugador2(self): while self.puntuacion_j2<10 and self.puntuacion_j1<10: if keyboard.is_pressed("u"): self.mover_jugador2_arriba() if keyboard.is_pressed("j"): self.mover_jugador2_abajo() def mover_jugador1_abajo(self): if self.inicio_j1_y<self.margen_y_abajo-self.tamaño_barra: self.inicio_j1_y=self.inicio_j1_y+(10*self.velocidad_jugador) 'self.canvas.move(self.canvas.find_withtag("jugador1"),0, 10*self.velocidad_jugador)' self.canvas.delete(self.canvas.find_withtag("jugador1")) self.canvas.create_line(self.margen_x_izquierdo, self.inicio_j1_y , self.margen_x_izquierdo, self.inicio_j1_y +self.tamaño_barra, fill="white", width=15, tags="jugador1") else: print("muy abajo") def mover_jugador1_arriba(self): if self.inicio_j1_y>self.margen_y_arriba: self.inicio_j1_y= self.inicio_j1_y - (10 * self.velocidad_jugador) 'self.canvas.move(self.canvas.find_withtag("jugador1"),0,- (10 * self.velocidad_jugador))' self.canvas.delete(self.canvas.find_withtag("jugador1")) self.canvas.create_line(self.margen_x_izquierdo, self.inicio_j1_y, self.margen_x_izquierdo, self.inicio_j1_y + self.tamaño_barra, fill="white", width=15, tags="jugador1") else: print("muy arriba") def mover_jugador2_abajo(self): if self.inicio_j2_y<self.margen_y_abajo-self.tamaño_barra: self.inicio_j2_y=self.inicio_j2_y+(10*self.velocidad_jugador) 'self.canvas.move(self.canvas.find_withtag("jugador1"),0, 10*self.velocidad_jugador)' self.canvas.delete(self.canvas.find_withtag("jugador2")) self.canvas.create_line(self.margen_x_derecho, self.inicio_j2_y , self.margen_x_derecho, self.inicio_j2_y +self.tamaño_barra, fill="white", width=15, tags="jugador2") else: print("muy abajo") def mover_jugador2_arriba(self): if self.inicio_j2_y>self.margen_y_arriba: self.inicio_j2_y= self.inicio_j2_y - (10 * self.velocidad_jugador) 'self.canvas.move(self.canvas.find_withtag("jugador1"),0,- (10 * self.velocidad_jugador))' self.canvas.delete(self.canvas.find_withtag("jugador2")) self.canvas.create_line(self.margen_x_derecho, self.inicio_j2_y, self.margen_x_derecho, self.inicio_j2_y + self.tamaño_barra, fill="white", width=15, tags="jugador2") else: print("muy arriba") 'print(self.inicio_j1_y,self.y*0.2,self.y*0.8)' def cambio_direccion(self,direccion): self.direccion=direccion self.velocidad_pelota_y=random.randint(10,25) self.velocidad_pelota_y=random.randint(10,25) def choque_margen(self): 'print(self.pelota_posicion_x,self.pelota_posicion_y,self.margen_y_abajo,self.margen_y_arriba)' self.mover_pelota() if self.margen_y_abajo<=self.pelota_posicion_y: if self.direccion==3: self.cambio_direccion(1) elif self.direccion==2: self.cambio_direccion(0) elif self.pelota_posicion_y<self.margen_y_arriba: if self.direccion==1: self.cambio_direccion(3) elif self.direccion==0: self.cambio_direccion(2) if self.margen_x_derecho<self.pelota_posicion_x: if self.direccion==1: self.cambio_direccion(0) elif self.direccion==3: self.cambio_direccion(2) if self.pelota_posicion_y>=self.inicio_j1_y and self.pelota_posicion_y<=self.inicio_j1_y*self.tamaño_barra and self.pelota_posicion_x<=self.margen_x_izquierdo+2: print("paso por aqui xd") if self.direccion==0: self.cambio_direccion(1) self.mover_pelota() elif self.direccion==2: self.cambio_direccion(3) self.mover_pelota() if self.pelota_posicion_x<15 : print("punto para el j1") sys.exit(0) ' if self.margen_y_abajo>=self.pelota_posicion_y and self.pelota_posicion_y>self.margen_y_arriba and self.margen_x_derecho>self.pelota_posicion_x and self.pelota_posicion_x>=self.margen_x_izquierdo:' 'self.canvas.create_line(50, self.inicio_j1_y, 50, self.inicio_j1_y + 200, fill="white", width=15, tags="jugador1")' print(self.inicio_j1_y,self.inicio_j1_y*1.2,self.pelota_posicion_x,self.pelota_posicion_y) def mover_pelota(self): if self.direccion==0: self.pelota_posicion_y = self.pelota_posicion_y - self.velocidad_pelota_y self.pelota_posicion_x = self.pelota_posicion_x - self.velocidad_pelota_x 'self.canvas.move(self.canvas.find_withtag("pelota"), -self.velocidad_pelota_x, -self.velocidad_pelota_y)' self.canvas.delete(self.canvas.find_withtag("pelota")) self.canvas.create_rectangle(self.pelota_posicion_x, self.pelota_posicion_y, self.pelota_posicion_x + 25, self.pelota_posicion_y + 25, fill="white", tags="pelota") elif self.direccion==1: self.pelota_posicion_y = self.pelota_posicion_y - self.velocidad_pelota_y self.pelota_posicion_x = self.pelota_posicion_x + self.velocidad_pelota_x 'self.canvas.move(self.canvas.find_withtag("pelota"), self.velocidad_pelota_x, -self.velocidad_pelota_y)' self.canvas.delete(self.canvas.find_withtag("pelota")) self.canvas.create_rectangle(self.pelota_posicion_x, self.pelota_posicion_y, self.pelota_posicion_x + 25, self.pelota_posicion_y + 25, fill="white", tags="pelota") elif self.direccion==2: self.pelota_posicion_y = self.pelota_posicion_y+ self.velocidad_pelota_y self.pelota_posicion_x = self.pelota_posicion_x- self.velocidad_pelota_x 'self.canvas.move(self.canvas.find_withtag("pelota"), -self.velocidad_pelota_x, self.velocidad_pelota_y)' self.canvas.delete(self.canvas.find_withtag("pelota")) self.canvas.create_rectangle(self.pelota_posicion_x, self.pelota_posicion_y, self.pelota_posicion_x + 25, self.pelota_posicion_y + 25, fill="white", tags="pelota") elif self.direccion==3: self.pelota_posicion_y = self.pelota_posicion_y + self.velocidad_pelota_y self.pelota_posicion_x = self.pelota_posicion_x + self.velocidad_pelota_x 'self.canvas.move(self.canvas.find_withtag("pelota"), self.velocidad_pelota_x, self.velocidad_pelota_y)' self.canvas.delete(self.canvas.find_withtag("pelota")) self.canvas.create_rectangle(self.pelota_posicion_x, self.pelota_posicion_y, self.pelota_posicion_x + 25, self.pelota_posicion_y + 25, fill="white", tags="pelota") ''' self.canvas.create_rectangle(self.pelota_x - 15, self.pelota_y - 15, self.pelota_x + 15, self.pelota_y + 15, fill="white", tags="pelota")''' pong = pong() ''' root = Tk() def key(event,ro): print ("pressed", repr(event.char)) print(ro) def callback(event): print ("clicked at", event.x, event.y) print(root) canvas= Canvas(root) canvas.place(x=0,y=0,height=100,width=100) canvas.focus_set() canvas.bind("<Key>",lambda event: key(event,root)) canvas.bind("<Button-1>", callback) canvas.pack() root.mainloop() '''<file_sep>/pruebas/prueba v1/pong_game.py 'este es ek q funca' import socket import string import sys '''sys.path.append("C:/Users/ricar/PycharmProjects/v-version/venv/prueba v1/servidor.py") from servidor import *''' import datetime import pickle import threading from tkinter import * class pong_game(): def __init__(self,ip,jugador): self.bandera=0 self.ip=ip self.jugador=jugador print(ip,jugador) while TRUE: if self.jugador==1: self.puerto_enviar=8000 self.puerto_recive=8001 break elif self.jugador==2: self.puerto_enviar=8002 self.puerto_recive=8003 break self.ventana= Tk() self.x=self.ventana.winfo_screenwidth() self.y=self.ventana.winfo_screenheight() self.ventana.geometry("{0}x{1}+0+0".format(self.x,self.y)) 'self.ventana.overrideredirect(TRUE)' self.ventana.config(bg="RED") self.canvas= Canvas(self.ventana,bg="Black") self.x=1500 self.y=800 'pociciones de los objetos' self.jugador_posicion = [] self.jugador_posicion.append((800 * 0.8) * 0.25) self.jugador_posicion.append((800 * 0.8) * 0.25) self.tope_izquierda = (1500 * 0.8) * 0.1 self.tope_derecha = (1500 * 0.8) * 0.9 self.tope_arriba = (800 * 0.8) * 0.1 'el tope de abajo tiene q considerar el tamaño de la barra ' self.tamaño_barra = 800 * 0.8 * 0.5 self.tope_abajo = ((800 * 0.8) * 0.9) - self.tamaño_barra x=(1500*0.8)//2 y=(800*0.8)//2 t=(1500*0.8)*0.01 self.pelota_posicion=[] self.pelota_posicion.append(x-t) self.pelota_posicion.append(y-t) 'inicio de los objetos' self.canvas.place(x=self.x*0.1,y=self.y*0.1,width=self.x*0.8,height=self.y*0.8) self.jugador1= self.canvas.create_line((1500*0.8)*0.075,self.jugador_posicion[0] ,(1500*0.8)*0.075,self.jugador_posicion[0]+self.tamaño_barra ,fill="blue",width=(1500*0.8)*0.01,tags="j1") self.pelota= self.canvas.create_rectangle(self.pelota_posicion[0] ,self.pelota_posicion[1], self.pelota_posicion[0]+(2*t),self.pelota_posicion[1]+(2*t), fill="white", tags="pelota") self.jugador2= self.canvas.create_line((1500*0.8) * 0.925,self.jugador_posicion[0] , (1500*0.8) * 0.925, self.jugador_posicion[0]+self.tamaño_barra , fill="blue",width=(1500*0.8) * 0.01, tags="j2") self.canvas.focus_set() 'self.establecer_conexion()' self.conexionhilo1=threading.Thread(name="hilosconexion1",target=self.establecer_conexion) self.conexionhilo1.start() '''self.conexionhilo2=threading.Thread(name="hilosconexion2",target=self.conexion_j2) self.conexionhilo2.start()''' self.canvas.bind("<1>",lambda event: self.click(event)) self.canvas.bind("<Key>",lambda event: self.mover(event)) self.hilo_actualizador=threading.Thread(name="actualizar",target=self.actualizar) self.hilo_actualizador.start() self.hilo_mainloop=threading.Thread(name="mainloop",target=self.ventana.mainloop()) self.hilo_mainloop.start() def establecer_conexion(self): 'se establece el recive' self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.bind((self.ip, self.puerto_recive)) self.socket.listen(1) self.conexion, self.direccion = self.socket.accept() 'se establece el envia' self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.connect((self.ip, self.puerto_enviar)) self.bandera+=1 def click(self,event): print(event.x,event.y) def mover(self,event): if event.char=="w": self.enviar_movimiento("arriba") if event.char=="s": self.enviar_movimiento("abajo") if event.char=="i": '' self.enviar_movimiento_j2("arriba") if event.char == "k": '' self.enviar_movimiento_j2("abajo") '''j2 def conexion_j2(self): 'se establece el recive' self.socket_j2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket_j2.bind((self.ip, 8003)) self.socket_j2.listen(1) self.conexion_j2, self.direccion_j2 = self.socket_j2.accept() 'se establece el envia' self.socket_j2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket_j2.connect((self.ip, 8002)) self.bandera+=1 def enviar_movimiento_j2(self,movimiento): 'movimiento = pickle.dumps(movimiento)' self.socket_j2.sendto(movimiento.encode(), (self.ip, self.puerto_enviar)) def actualizar(self): 'conexion de recive' while self.bandera<2: '' while True: self.valores = self.conexion_j2.recv(1024) self.valores=pickle.loads(self.valores) print(self.valores) self.canvas.move(self.jugador1 ,0,self.valores[0]-self.jugador_posicion[0]) self.canvas.move(self.jugador2, 0, self.valores[1] - self.jugador_posicion[1]) self.jugador_posicion[0]=self.valores[0] self.jugador_posicion[1]=self.valores[1] self.canvas.move(self.pelota,self.valores[2]- self.pelota_posicion[0] ,self.valores[3] - self.pelota_posicion[1]) self.pelota_posicion[0]=self.valores[2] self.pelota_posicion[1]=self.valores[3] 'self.conexion.send("si".encode())' self.conexion.close()''' def enviar_movimiento(self,movimiento): 'movimiento = pickle.dumps(movimiento)' self.socket.sendto(movimiento.encode(), (self.ip, self.puerto_enviar)) 'respuesta = self.socket.recv(1024).decode()' 'print(respuesta)' def actualizar(self): 'conexion de recive' while self.bandera<1: '' while True: self.valores = self.conexion.recv(1024) self.valores=pickle.loads(self.valores) print(self.valores) self.canvas.move(self.jugador1 ,0,self.valores[0]-self.jugador_posicion[0]) self.canvas.move(self.jugador2, 0, self.valores[1] - self.jugador_posicion[1]) self.jugador_posicion[0]=self.valores[0] self.jugador_posicion[1]=self.valores[1] self.canvas.move(self.pelota,self.valores[2]- self.pelota_posicion[0] ,self.valores[3] - self.pelota_posicion[1]) self.pelota_posicion[0]=self.valores[2] self.pelota_posicion[1]=self.valores[3] 'self.conexion.send("si".encode())' self.conexion.close() 'pong_game(socket.gethostbyname(socket.gethostname()), 1)' a=threading.Thread(name="j1",target=pong_game,args={socket.gethostbyname(socket.gethostname()),1}) b=threading.Thread(name="j2",target=pong_game,args={socket.gethostbyname(socket.gethostname()),2}) a.start() b.start() <file_sep>/pruebas/pruebas aisladas/objetos pruebas/ob1.py class arbol(): def __init__(self): self.años=1 self.vec=[] self.vec.append("fsaf") print("se a creado") def asignar(self,año): self.años=año def crece(self): self.años=self.años+1 def muere(self): self.años=-1 print("murio" + str(self.años)) def mostrar(self): print(self.años) def obtener(self): return self.años def obtener_vec(self): print(self.vec) '''a=arbol() a.asignar(4) a.crece() print("años") a.mostrar() a.muere() a.mostrar()'''<file_sep>/pruebas/pruebas aisladas/menu2.py #!/usr/bin/env python #-*- coding: utf-8 -*- from tkinter import * contador = 0 def actualizar(): '''Actualiza la entrada de menu.''' global contador contador += 1 menu.entryconfig(0, label=str(contador)) raiz = Tk() # Crear el menu principal menubarra = Menu(raiz) # Crear el menu desplegable Prueba menu = Menu(menubarra, tearoff=0, postcommand=actualizar) menu.add_command(label=str(contador)) menu.add_command(label="Salir", command=raiz.quit) menubarra.add_cascade(label="Prueba", menu=menu) # Mostrar el menu raiz.config(menu=menubarra) # Mostrar la ventana raiz.mainloop() # Enlazar el menu popup al marco marco.bind("<Button-3>", popup) # Mostrar la ventana raiz.mainloop()<file_sep>/v-2/pruebas/administrador de archivos online/interfaz.py from tkinter import * import tkinter as tk from PIL import Image, ImageTk import sys import pickle sys.path.append("v-2/pruebas/administrador de archivos online/gestor_file.py") from gestor_file import * from tkinter import filedialog as FileDialog from tkinter import messagebox as MessageBox class gui(): def __init__(self): 'imagenes' self.vent = Tk() self.sistema_de_archivos=carpeta("master") self.sistema_de_archivos.asignar_id(0) self.archivos_contenidos_io=archivo_contenido() self.ruta=[] self.id_actual=-1 'fase de pruebas off' 'self.cargar_pruebas()' self.iconos_botones=[] self.maximo_ventana_x=1000 self.maximo_ventana_y=800 'margen izquierdo' self.vent.geometry(str(self.maximo_ventana_x)+"x"+str(self.maximo_ventana_y)) self.menu = Menu(self.vent) self.opciones = Menu(self.menu, tearoff=0) self.opciones.add_command(label="iniciar como servidor", command=self.iniciar_servidor) self.opciones.add_command(label="unirse", command=self.unirse) self.menu.add_cascade(label="opciones", menu=self.opciones) self.vent.config(menu=self.menu) self.iconos = Canvas(self.vent,bg="red") self.iconos.place(relx=0, rely=0, relheight=1, relwidth=1) self.iconos.bind('<1>',lambda event:self.select(event)) self.vent.mainloop() def abrir(self): 'falta tratar archivos' print(self.id_actual) if self.id_actual != -1: bus_complet=self.busqueda_carpeta(self.sistema_de_archivos,self.ruta+[self.id_actual]) print(type(bus_complet)) if type(bus_complet)==carpeta: self.iconos.delete("all") self.ruta.append(self.id_actual) self.cargar_canvas(bus_complet) else: print(self.archivos_contenidos_io.obtener_contenido(bus_complet.contenido)) else: print("no se selecciono ningun archivo") def borrar(self): 'self.ruta + self.icono_actual es el archivo a tocar' if self.id_actual!=-1: self.busqueda_carpeta(self.sistema_de_archivos,self.ruta).contenido[self.id_actual].visible=0 self.iconos.delete("all") self.cargar_canvas(self.busqueda_carpeta(self.sistema_de_archivos, self.ruta)) self.id_actual=-1 else: print("no hay archivo seleccionado") def volver(self): if len(self.ruta)!=0: self.ruta.pop(len(self.ruta)-1) self.iconos.delete("all") self.cargar_canvas(self.busqueda_carpeta(self.sistema_de_archivos,self.ruta)) else: print("no se puede volver atras") def select(self,event): try: 'print("----------------------------")' x=(self.iconos.find_withtag(tk.CURRENT)) 'self.iconos.itemconfig(x,args)' 'self.iconos.move(x,0,75)' '''print(self.iconos.gettags(x)[0],"tags elemento") print(self.obtener_geometry())''' self.id_actual=int(self.iconos.gettags(x)[0]) except: print("ocurrio un error") self.id_actual=-1 def agregar_carpeta(self): self.iconos.delete("all") s=0 while True: if not self.busqueda_carpeta(self.sistema_de_archivos, self.ruta).agregar_contenido(carpeta("nueva carpeta"+str(s)))!=-1: s+=1 else: break self.cargar_canvas(self.busqueda_carpeta(self.sistema_de_archivos, self.ruta)) def agregar_archivo(self): exist=False file_s= FileDialog.askopenfilename(title="Abrir un fichero") if file_s!="": name=self.sacar_nombre_direccion(file_s) for i in self.busqueda_carpeta(self.sistema_de_archivos, self.ruta).contenido: if type(i)==archivo: if name==i.nombre +"."+ i.extencion: exist = True if MessageBox.askquestion("advertencia","¿existe un archvio igual en esta carpeta desea reemplazarlo?"): print("se reemplazo") if exist==False: c = open(file_s, "rb") 'crea una instancia de un archivo y la guarda en la carpeta actual' print(self.archivos_contenidos_io.cantidad_archivos()) self.busqueda_carpeta(self.sistema_de_archivos, self.ruta).\ agregar_contenido(archivo(name,self.archivos_contenidos_io.cantidad_archivos())) 'print(self.busqueda_carpeta(self.sistema_de_archivos, self.ruta+[self.id_actual]).contenido)' self.archivos_contenidos_io.agregar(c.read()) print(self.archivos_contenidos_io.cantidad_archivos()) self.iconos.delete("all") self.cargar_canvas(self.busqueda_carpeta(self.sistema_de_archivos, self.ruta)) else: print("no se selecciono ningun archiivo") 'fin de los eventos de movimiento' def iniciar_servidor(self): self.menu.add_command(label="abrir",command=lambda : self.abrir()) self.menu.add_command(label="agreagar archivo",command=lambda : self.agregar_archivo()) self.menu.add_command(label="nueva carpeta",command=lambda : self.agregar_carpeta()) self.menu.add_command(label="borrar",command=lambda : self.borrar()) self.menu.add_command(label="volver",command=lambda : self.volver()) self.carpeta_jpg = "C:/Users/ricar/PycharmProjects/v-version/v-2/pruebas/iconos/carpeta.jpg" self.img_carpeta = ImageTk.PhotoImage(Image.open(self.carpeta_jpg).resize((50, 50))) self.archivo_jpg = "C:/Users/ricar/PycharmProjects/v-version/v-2/pruebas/iconos/archivo.jpg" self.img_archivo = ImageTk.PhotoImage(Image.open(self.archivo_jpg).resize((50, 50))) self.cargar_canvas(self.sistema_de_archivos) def obtener_geometry(self): v=[] v.append("") j=0 print(self.vent.geometry()) for i in range(len(self.vent.geometry())): if self.vent.geometry()[i:i+1]!="+" and self.vent.geometry()[i:i+1]!="x": v[j]+=self.vent.geometry()[i:i+1] else: v.append("") j+=1 return v def unirse(self): print('unirse') def cargar_pruebas(self): '' for i in range(10): self.sistema_de_archivos.agregar_contenido(archivo(str(i) + ".exe")) self.sistema_de_archivos.agregar_contenido(carpeta("carpeta 1")) self.sistema_de_archivos.agregar_contenido(carpeta("carpeta 2")) for i in self.sistema_de_archivos.contenido: if type(i) == carpeta: for l in range(5): i.agregar_contenido(archivo(str(l) + ".jpg")) 'recorrer(self.sistema_de_archivos)' def busqueda_carpeta(self,dir_actual, ruta): try: for i in ruta: 'si falla es porque se modifico la direccion o ruta actual para que no sea integro' dir_actual = dir_actual.contenido[i] return dir_actual except: 'print("no se encontro o ruta desconocida")' return None def busqueda_archivo(self,dir_actual, ruta): try: for i in ruta: if type(dir_actual) == carpeta: dir_actual = dir_actual.contenido[i] if type(dir_actual) == archivo: return dir_actual 'print("encontrado:", dir_actual.nombre, dir_actual.extencion)' except: 'print("no se encontro o ruta desconocida")' return None def cargar_canvas(self,sistema_archivos): x=50 y=50 p=0 self.iconos_botones=[] for i in sistema_archivos.contenido: if (i.visible==1): if (type(i)==carpeta): self.iconos_botones.append(self.iconos.create_image(x,y, anchor="nw", image=self.img_carpeta, tags=str(i.id))) nom = i.nombre else: self.iconos_botones.append(self.iconos.create_image(x, y, anchor="nw", image=self.img_archivo, tags=str(i.id))) nom = i.nombre + "." + i.extencion if len(nom)>10: nom=nom[0:10]+"..." self.iconos.create_text(x+25,y+60,fill="darkblue",font="arial 8 ",text=nom) if x+100<self.maximo_ventana_x : x+=75 else: x=50 y+=75 p+=1 self.vent.mainloop() def sacar_nombre_direccion(self,direccion): i=len(direccion)-1 while direccion[i:i+1]!="/": i-=1 return direccion[i+1:len(direccion)] gui() <file_sep>/pruebas/pruebas aisladas/administrador de archivos.py from tkinter import * # Carga módulo tk (widgets estándar) from tkinter import ttk # Carga ttk (para widgets nuevos 8.5+) import os from os import listdir '''armar listado de rutas''' def carga(vector,ruta,vector2,pos): for elemento in listdir(ruta): tab= "\t"*pos print( tab, elemento , pos) vector.append(elemento) vector2.append(pos) if(os.path.isdir(ruta+"/"+elemento)): carga(vector,ruta+"/"+elemento,vector2,pos+1) '''simplificacion: falta validar el archivo .prop que tengo q crear para usar, configurar otra pestaña de prop y darle esas prop los archivos tambien verificar las extenciones y la ruta ingresada''' def simplificacion (evento): '''si es un directorio abre todo si no configurar extenciones''' print(rutas[list.curselection()[0]]) if(archivos_tipo[list.curselection()[0]]=="carpeta"): if(estado[list.curselection()[0]]==0): '''0 --> cerrado , 1 --> abierto''' estado[list.curselection()[0]]=1 '''si la seleccion actual es un directorio se guarda asi > sino asi " " ''' for elemento in listdir(rutas[list.curselection()[0]]+"/"+ list.get(list.curselection()[0])[3*posicion[list.curselection()[0]]+1:]): posicion.insert(list.curselection()[0] + 1, posicion[list.curselection()[0]] + 1) if os.path.isdir(rutas[list.curselection()[0]]+"/"+ list.get(list.curselection()[0])[3*posicion[list.curselection()[0]]+1:]+"/"+elemento): archivos_nombre.insert(list.curselection()[0]+1," "*posicion[list.curselection()[0]+1]+">"+elemento) archivos_tipo.insert(list.curselection()[0]+1,"carpeta") rutas.insert(list.curselection()[0]+1,rutas[list.curselection()[0]]+"/"+ list.get(list.curselection()[0])[3*posicion[list.curselection()[0]]+1:]) else: archivos_nombre.insert(list.curselection()[0] + 1," " * posicion[list.curselection()[0] + 1] + " " + elemento) archivos_tipo.insert(list.curselection()[0]+1,"archivo") rutas.insert(list.curselection()[0]+1,rutas[list.curselection()[0]]+"/"+ list.get(list.curselection()[0])[3*posicion[list.curselection()[0]]+1:]) estado.insert(list.curselection()[0]+1,0) list.delete("0","end") for i in range(0,len(archivos_nombre)): list.insert(i,str(archivos_nombre[i])) else: '''si ya esta abierto el directorio''' estado[list.curselection()[0]]=0 while posicion[list.curselection()[0]]<posicion[list.curselection()[0]+1]: posicion.pop(list.curselection()[0]+1) archivos_nombre.pop(list.curselection()[0]+1) rutas.pop(list.curselection()[0]+1) estado.pop(list.curselection()[0]+1) list.delete("0","end") for i in range(0,len(archivos_nombre)): list.insert(i,str(archivos_nombre[i])) else: print("es un archivo") def iniciar(): for elemento in listdir("C:/Users/ricar/Desktop/pruebas v1"): rutas.append("C:/Users/ricar/Desktop/pruebas v1") posicion.append(0) estado.append(0) if os.path.isdir("C:/Users/ricar/Desktop/pruebas v1/"+elemento): archivos_tipo.append("carpeta") archivos_nombre.append(">"+elemento) else: archivos_nombre.append(" "+elemento) archivos_tipo.append("archivo") '''cambiar por cuando solo tenga una extencion''' for i in range (0,len(archivos_nombre)): list.insert(i,archivos_nombre[i]) print(rutas) def hola(evento): if len(list.curselection()) != 0: c=list.get(list.curselection()[0]) prueba2 = Entry(rc, text=c,bd=5,bg="blue").pack(side=RIGHT) '''define el elemento y el indice''' print(c,list.curselection()[0]) ''' carga todo como si estubiera abierto r="C:/Users/ricar/Desktop/pruebas v1" carga(vec,r,posicion,0) for i in range(0,len(vec)): list.insert(i," "*posicion[i]+str(vec[i])) ''' '''def simplificacion (evento): if(os.path.isdir(rutas[list.curselection()[0]]+"/"+ list.get(list.curselection()[0])[4*posicion[list.curselection()[0]]:])): if(estado[list.curselection()[0]]==0): estado[list.curselection()[0]]=1 for elemento in listdir(rutas[list.curselection()[0]]+"/"+ list.get(list.curselection()[0])[4*posicion[list.curselection()[0]]:]): if os.path.isdir(rutas[list.curselection()[0]]+"/"+ list.get(list.curselection()[0])[4*posicion[list.curselection()[0]]:]): posicion.insert(list.curselection()[0] + 1, posicion[list.curselection()[0]] + 1) archivos_nombre.insert(list.curselection()[0]+1," "*posicion[list.curselection()[0]+1]+">"+elemento) rutas.insert(list.curselection()[0]+1,rutas[list.curselection()[0]]+"/"+ list.get(list.curselection()[0])[4*posicion[list.curselection()[0]]:]) estado.insert(list.curselection()[0]+1,0) list.delete("0","end") for i in range(0,len(archivos_nombre)): list.insert(i,str(archivos_nombre[i])) else: estado[list.curselection()[0]]=0 while posicion[list.curselection()[0]]<posicion[list.curselection()[0]+1]: posicion.pop(list.curselection()[0]+1) archivos_nombre.pop(list.curselection()[0]+1) rutas.pop(list.curselection()[0]+1) estado.pop(list.curselection()[0]+1) list.delete("0","end") for i in range(0,len(archivos_nombre)): list.insert(i,str(archivos_nombre[i])) else: print("es un archivo") def iniciar(): for elemento in listdir("C:/Users/ricar/Desktop/pruebas v1"): archivos_nombre.append(elemento) rutas.append("C:/Users/ricar/Desktop/pruebas v1") posicion.append(0) estado.append(0) if os.path.isdir("C:/Users/ricar/Desktop/pruebas v1/"+elemento): archivos_tipo.append("carpeta") for i in range (0,len(archivos_nombre)): list.insert(i,archivos_nombre[i])''' def prueba(): print("archivos _ nombre") print(archivos_nombre) print("posicion") print(posicion) print("estado") print(estado) print("ruta") print(rutas) print("tipos de archivos") print(archivos_tipo) archivos_nombre=[] posicion=[] estado=[] rutas=[] archivos_tipo=[] rc= Tk() '''rc.geometry("{0}x{0}+0+0".format(rc.winfo_screenwidth(), rc.winfo_screenheight()))''' rc.geometry("500x500") list = Listbox(rc,exportselection=0) '''LISTBOX.SIZE() -->OBTIENE todos los elementos, exportseleccion permite q no se pierda la seleccion al perder el foco ,selectmode=SINGLE''' iniciar() list.bind('<<ListboxSelect>>', simplificacion) list.place(x=0,y=0,relwidth=0.5,relheight=0.5) but=Button(rc,command=prueba,text="hola").pack() rc.mainloop()<file_sep>/pruebas/pruebas aisladas/NOOTBOOCK.py from tkinter import * from tkinter import ttk def obtener(): print(text1.get(),text2.get()) vent= Tk() vent.geometry("250x250") note = ttk.Notebook(vent) note.pack(fill="both",expand="yes") note1 = ttk.Notebook(note) note1.pack(fill="both",expand="yes") note.add(note1,text="frame1") note2 = ttk.Notebook(note) note2.pack(fill="both",expand="yes") note.add(note2,text="frame2") frame4=Frame(note1) note1.add(frame4,text="hola") frame5=Frame(note2) note2.add(frame5,text="hola") vent.mainloop() <file_sep>/pruebas/pruebas aisladas/menubutton y full scrin.py from tkinter import * # Carga módulo tk (widgets estándar) from tkinter import ttk # Carga ttk (para widgets nuevos 8.5+) def posicionarmenu(menu,relx): menu.place(relx=relx, rely=0.005, relheight=0.025, relwidth=0.1) menu.menu = Menu(menu, tearoff=1) menu["menu"] = menu.menu def asignarmenu(menu,nombre,variable): menu.menu.add_button ( text= nombre, variable = variable ) '''button = Button(vent, text="prueba", command=radioprueba).place(x=10, y=100)''' v1= Tk() v1.geometry("{0}x{1}+0+0".format(v1.winfo_screenwidth(), v1.winfo_screenheight())) '''v1.overrideredirect(True) pantalla completa ''' cinta= Frame(v1,bg="gray").place(relx=0,rely=0,relwidth = 1 , relheight = 0.035 ) '''definicion de menu''' archivos= Menubutton(cinta,text="Archivos",relief=RAISED) posicionarmenu(archivos,0.005) '''define los items del menu y la variable q ocupa (no importa)''' itemsmenu=["mayo","otro","nose","hola"] mayoVar = StringVar() for i in range (0, len(itemsmenu)): asignarmenu(archivos,itemsmenu[i],mayoVar) '''archivos.menu.add_checkbutton ( label = "mayo", variable = mayoVar )''' opciones= Menubutton(cinta,text="Opciones",relief=GROOVE) posicionarmenu(opciones,0.115) itemsmenu=["mayo","otro"] for i in range (0, len(itemsmenu)): asignarmenu(opciones,itemsmenu[i],mayoVar) text= Entry(v1,textvariable=mayoVar).pack() v1.mainloop() <file_sep>/pruebas/prueba servidor-cliente/pong v-fall/server.py import socket import pickle class pruebas(): def __init__(self): self.prueba=["hola"],["adios"] self.numero=10 self.letra="a" self.palabra="holaadios" s= socket.socket() s.bind(('localhost',8000)) s.listen(1) print("empezo") while True: conexion, direccion= s.accept() print("coneccion nueva\n") print( conexion) print(direccion) peticion = conexion.recv(1024) print(peticion) peticion=pickle.loads(peticion) print(peticion) print("imprima una palabra") peticion.palabra=input() conexion.send(pickle.dumps(peticion)) conexion.close()<file_sep>/pruebas/pruebas aisladas/rutas absolutas.py from tkinter import * # Carga módulo tk (widgets estándar) from tkinter import ttk # Carga ttk (para widgets nuevos 8.5+) from os import listdir def ls(ruta = '.'): return listdir(ruta) path = "C:/Users/ricar/Desktop/pruebas v1" directorios = [] for dir in listdir(path): element= {} element['directorio'] = dir path_nuevo = path +'/'+str(dir)+'/' for file in listdir(path): element['archivo'] = file directorios.append(element) print (directorios) '''verificar cual tarda mas un for direccionies in list direcciones o var= list direcciones for i in range(1.len(direcciones) considerar por tiempo de memoria)''' ruta=StringVar() ruta=ls("C:/Users/ricar/Desktop/pruebas v1") print (ruta ) <file_sep>/pruebas/pruebas aisladas/hilos/hilos_simultaneos.py import threading import time def crear_hilo(hilo_numero,timer): hilos=threading.Thread(name=str(hilo_numero),target=tarea,args=(hilo_numero,timer,0)) return hilos def tarea(numero,timers,indice): while True: indice+=1 print("este hilo es el: " + str(threading.current_thread()),indice) 'timers.sleep(0.5)' if indice ==10: break; class prueba(): def __init__(self): print("inicio") self.hilos=[] self.timer=[] ''' self.hilo1=threading.Thread(name="hilo%s" %2,target=tarea,args=(10,)) self.hilo1.start()''' 'multiples hilos simultaneos (+5)' for i in range(2): self.timer.append(time) self.hilos.append(crear_hilo(i,self.timer[i])) self.hilos[i].start() print("asdidossdhnjoikdsaffbhnkjlkasdj bnkskadmj") p=prueba() <file_sep>/pruebas/pruebas aisladas/cliente-servidor/picke-socket/cliente.py import socket import pickle class pruebas(): def __init__(self): self.prueba=["hola"],["adios"] self.numero=10 self.letra="a" self.palabra="holaadios" prueba=pruebas() mensaje=pickle.dumps(prueba) host = 'localhost' port = 8000 obj = socket.socket() obj.connect((host, port)) obj.send(mensaje) respuesta= obj.recv(1024) print(respuesta) respuesta=pickle.loads(respuesta) print(respuesta.palabra) obj.close() print("Conexión cerrada")<file_sep>/pruebas/clase bd/prueba.py import pickle import io def codificar_mensaje(mensaje): mensaje_codificado="" for i in range (len(mensaje)): mensaje_codificado=mensaje_codificado + str(mensaje[i])+"\n" return mensaje_codificado def decoficar_mensaje(mensaje): i=0 lasti=0 vec=[] mensaje=str(mensaje).replace("'","").replace("[","").replace("]","").replace('"',"") while i<len(str(mensaje)): if str(mensaje)[i:i+1]=="\n": vec.append(str(mensaje)[lasti:i]) lasti=i+1 i=i+1 return vec ''' print("empieza") vec=[] vec.append("hola1") vec.append("hola2") vec.append("hola3") s=gestor_mensaje() s.codificar_mensaje(vec) a=s.decoficar_mensaje(s.mensaje_codificado) for i in range (len(a)): print(a[i]==vec[i]) '''<file_sep>/v-2/algoritmoloyd/prueba1.py from tkinter import * import tkinter as tk from tkinter import ttk from tkinter.filedialog import askopenfilename from tkinter import filedialog from tkinter.messagebox import showerror from tkinter import simpledialog import pickle from tkinter import messagebox class interfaz: def __init__(self): self.floyd_clase = floyd() self.vent=Tk() self.x_max=self.vent.winfo_screenwidth() self.y_max=self.vent.winfo_screenheight() self.vent.geometry(str(self.x_max)+"x"+ str(self.y_max)+"+0+0") self.label_nodos=Label(self.vent,text="ingrese la cantidad de nodos") self.label_nodos.place(x=15,y=5,width=150,height=15) self.cant_nodo= Entry(self.vent) self.cant_nodo.place(x=15,y=30,width=100,height=15) self.boton_nodo = Button(self.vent,text="continuar",command=self.continuar_nodos) self.boton_nodo.place(x=15, y=45, width=75, height=30) self.menu = Menu(self.vent) self.opciones = Menu(self.menu, tearoff=0) self.opciones.add_command(label="guardar datos", command=self.guardar) self.opciones.add_command(label="cargar datos", command=self.cargar) self.menu.add_cascade(label="opciones", menu=self.opciones) self.vent.config(menu=self.menu) self.vent.mainloop() def guardar(self): filename = filedialog.askdirectory() if filename!="": answer = simpledialog.askstring("como desea llamarlo", "",parent=self.vent) if filename!="" and (answer!=None): try: x= str(filename)+"/"+str(answer)+".matriz" file= open(x, "wb") w = [] for i in range(int(self.cant_nodo.get())): w.append([]) for j in range(int(self.cant_nodo.get())): if i != j: try: if int(self.matriz[i][j].get()) >= 0: w[i].append(int(self.matriz[i][j].get())) else: w[i].append("-") except: w[i].append("-") else: w[i].append("-") file.write(pickle.dumps(w)) file.close() except: messagebox.showinfo(message="no hay datos que guardar", title="--") else: self.cant_nodo.insert(0,"sadiosdj") def cargar(self): fname = askopenfilename(filetypes=(("matriz_dts", "*.matriz"), ("All files", "*.*"))) if fname!="": c = open(fname, "rb") matriz= pickle.loads(c.read()) c.close() self.cant_nodo.delete(0,END) self.cant_nodo.insert(0,len (matriz[0])) try: for i in range(len(self.matriz[0])): for j in range(len(self.matriz[0])): self.matriz[i][j].destroy() self.vent.update() except: '' tam = (int(self.vent.winfo_screenheight()) * 0.8) // int(len(matriz[0])) if tam > 50: tam = 50 self.matriz = [] y = 100 x_l = 100 y_l = 100 for i in range(len(matriz[0])): Label(self.vent, text="nodo" + str(i + 1)).place(x=x_l, y=25, width=tam, height=tam) Label(self.vent, text="nodo" + str(i + 1)).place(x=25, y=y_l, width=tam, height=tam) x_l += tam y_l += tam x = 100 self.matriz.append([]) for j in range(len(matriz[0])): if i == j: self.matriz[i].append(Entry(self.vent)) self.matriz[i][j].place(x=x, y=y, width=tam, height=tam) self.matriz[i][j].insert(0, "-") self.matriz[i][j].configure(justify=CENTER, state=DISABLED) x += tam else: self.matriz[i].append(Entry(self.vent)) self.matriz[i][j].place(x=x, y=y, width=tam, height=tam) self.matriz[i][j].configure(justify=CENTER) self.matriz[i][j].insert(0,matriz[i][j] ) x += tam y += tam self.inicio_B = Button(self.vent, text="metodo de floyd", command=self.metood_floyd) self.inicio_B.place(x=400, y=15, width=150, height=15) def continuar_nodos(self): if self.cant_nodo.get()!="": try: for i in range(len(self.matriz[0])): for j in range(len(self.matriz[0])): self.matriz[i][j].destroy() self.vent.update() except: '' tam= (int(self.vent.winfo_screenheight())*0.8)//int(self.cant_nodo.get()) if tam>50: tam=50 self.matriz=[] y = 100 x_l=100 y_l=100 for i in range(int(self.cant_nodo.get())): Label(self.vent,text="nodo"+str(i+1)).place(x=x_l,y=25,width=tam,height=tam) Label(self.vent, text="nodo" + str(i + 1)).place(x=25, y=y_l, width=tam, height=tam) x_l+=tam y_l+=tam x=100 self.matriz.append([]) for j in range(int(self.cant_nodo.get())): if i==j: self.matriz[i].append(Entry(self.vent)) self.matriz[i][j].place(x=x, y=y, width=tam, height=tam) self.matriz[i][j].insert(0,"-") self.matriz[i][j].configure(justify=CENTER,state=DISABLED) x += tam else: self.matriz[i].append(Entry(self.vent)) self.matriz[i][j].place(x=x, y=y, width=tam, height=tam) self.matriz[i][j].configure(justify=CENTER) self.matriz[i][j].insert(0,"-") x += tam y += tam self.inicio_B= Button (self.vent,text="metodo de floyd",command=self.metood_floyd) self.inicio_B.place(x=400,y=15,width=150,height=15) def metood_floyd(self): 'floyd' w=[] for i in range(int(self.cant_nodo.get())): w.append([]) for j in range(int(self.cant_nodo.get())): if i!=j: try: if int(self.matriz[i][j].get())>=0: w[i].append(int(self.matriz[i][j].get())) except: w[i].append(-1) else: w[i].append(-1) try: self.floyd_clase.vent_floyd.deiconify() self.floyd_clase.iniciar(w) except: self.floyd_clase = floyd() self.floyd_clase.vent_floyd.deiconify() self.floyd_clase.iniciar(w) class floyd: def __init__(self): self.matriz_adjunta=[] self.estado_1=[] self.estado_2=[] self.vent_floyd = Tk() self.tam = int(int(self.vent_floyd.winfo_screenheight()) * 0.8) self.vent_floyd.geometry(str(self.tam) + "x" + str(self.tam)) self.intento=1 self.note_historial = ttk.Notebook(self.vent_floyd) self.note_historial.pack(fill="both", expand="yes") self.vent_floyd.withdraw() def iniciar(self,matriz): self.historial = Frame(self.note_historial) self.note_historial.add(self.historial,text=("prueba: "+str(self.intento))) self.intento+=1 self.matriz = matriz self.tamaño = len(self.matriz[0]) for i in range(self.tamaño): self.matriz_adjunta.append([]) for j in range(self.tamaño): if j!=i: self.matriz_adjunta[i].append(j+1) else: self.matriz_adjunta[i].append("-") for w in range(self.tamaño): for i in range(self.tamaño): for j in range(self.tamaño): if (j!=w or j!=i ) and (self.matriz[i][w]>=0 and self.matriz[w][j]>=0) and (j!=i): if self.matriz[i][j]==-1: self.matriz[i][j] = (self.matriz[i][w] + self.matriz[w][j]) self.matriz_adjunta[i][j] = w+1 elif self.matriz[i][w] + self.matriz[w][j] < self.matriz[i][j]: self.matriz[i][j] = (self.matriz[i][w]+self.matriz[w][j]) self.matriz_adjunta[i][j]=w+1 self.estado_1.append(self.matriz) self.estado_2.append(self.matriz_adjunta) self.note_iteraciones = ttk.Notebook(self.historial) self.note_iteraciones.pack(fill="both", expand="yes") for w in range(self.tamaño): self.contenedor= Frame(self.note_iteraciones,bg="blue") self.contenedor.place(relx=0,rely=0,relwidth=0.5,relheight=0.5) self.note_iteraciones.add(self.contenedor, text="iteracion: "+str(w+1)) tam=50 Label(self.contenedor, width=10, text="Matriz: D").grid(row=0, column=0) Label(self.contenedor, width=10, text="Matriz: S").grid(row=self.tamaño+2, column=0) Label(self.contenedor, width=10, text="---").grid(row=1 + self.tamaño, column=0) for i in range(self.tamaño): '''Label(self.contenedor, text="nodo" + str(i + 1)).place(x=x_l, y=25, width=tam, height=tam) Label(self.contenedor, text="nodo" + str(i + 1)).place(x=25, y=y_l, width=tam, height=tam)''' 'matriz D' Label(self.contenedor, width=10, text="Nodo: " + str(i + 1)).grid(row=0, column=i + 1) Label(self.contenedor, width=10, text="Nodo: " + str(i + 1)).grid(row=i+1, column=0) Label(self.contenedor, width=10, text="---").grid(row=1 + self.tamaño, column=i +1,pady=4) 'matriz S' Label(self.contenedor, width=10, text="Nodo: " + str(i + 1)).grid(row=2+self.tamaño, column=i+1) Label(self.contenedor, width=10, text="Nodo: " + str(i + 1)).grid(row=i + 3+self.tamaño, column=0) for j in range(self.tamaño): if i != j: 'matriz d' if self.estado_1[w][i][j]>0: Label(self.contenedor, width=10, text=str(self.estado_1[w][i][j])).grid(row=i + 1, column=j + 1) else: Label(self.contenedor, width=10, text="-").grid(row=i + 1,column=j + 1) 'matriz adjunta' if self.estado_2[w][i][j]>0: Label(self.contenedor, width=10, text=str(self.estado_2[w][i][j])).grid(row=i + 3+self.tamaño, column=j + 1 ) else: Label(self.contenedor, width=10, text="-").grid(row=i + 3 + self.tamaño, column=j + 1) 'Label(self.contenedor,text=str(self.estado_1[w][i][j])).place(x=x, y=y, width=tam, height=tam)' else: 'matriz d' 'Label(self.contenedor, text="-").place(x=x, y=y, width=tam, height=tam)' Label(self.contenedor, width=10, text="-").grid(row=i + 1, column=j + 1) 'matriz adjunta' Label(self.contenedor, width=10, text="-").grid(row=i +3 +self.tamaño, column=j + 1) self.vent_floyd.mainloop() interfaz()<file_sep>/pruebas/pruebas aisladas/loggin/loggin test.py import logging import socket import sys 'basicamente sirve para dar registros de error para un mejor mantenimiento y mejor manejo de errores' logging.basicConfig( format='%(asctime)s - %(message)s', level=logging.DEBUG ,filename='app.log', filemode='w') logging.debug("esto es una prueba de namae: %s IP: %s",socket.gethostname(),socket.gethostbyname(socket.gethostname())) try: print(0/0) except Exception as e: logging.error("division sobre '0' de %s",socket.gethostname(), exc_info=True) print("Error OS: {0}".format(e)) for i in range(len(sys.exc_info())): print(sys.exc_info()[i]) print(i) print(e) print(e.args) <file_sep>/v-2/pruebas/envio de archivos por socket/envio por partes/servidor.py import socket from io import open import pickle import sys 'r="C:/Users/ricar/Desktop/Nuevo documento de texto.txt"' r="archivo_recivido.txt" s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('localhost',8000)) s.listen(1) i=0 iteraciones=0 'while True:' c = open(r, "wb") conexion, direccion= s.accept() w=True while w: peticion =conexion.recv(1024) if peticion == "termino".encode(): w = False print("termino") else: iteraciones += 1 print("iteraciones: ", iteraciones,"peticion: ",peticion) c.write(peticion) i+=1 c.close() conexion.close() <file_sep>/pruebas/clase bd/usuario_secion.py import socket import pickle import datetime import io import sys class usuario_secion: def __init__(self,usuario,password): self.usuario=usuario self.password=<PASSWORD> self.pc_name=socket.gethostname() self.pc_ip=socket.gethostbyname(socket.gethostname()) self.expiracion_secion=datetime.date.today()+datetime.timedelta(days=1) self.ruta_archivo="C:/Users/ricar/Desktop/pruebas v1/base/seciones_particulares" '''self.usuario_privilegios--> 1°-->privilegios de crear usuarios,bd,etc 2°-->privilegios de insert 3°-->privilegios de update 4°-->privilegios de delete°''' self.usuario_privilegios="" def asignar_usuario(self,usuario): self.usuario=usuario def asignar_password(self,password): self.password =<PASSWORD> def asignar_pc_name(self): self.pc_name =socket.gethostname() def asignar_pc_ip(self): self.pc_ip =socket.gethostbyname(socket.gethostname()) def asignar_privilegios(self,priv): self.usuario_privilegios =priv def serializar(ruta,objeto): with open(ruta,"wb") as f: pickle.dump(objeto, f) def deserializar(ruta): with open(ruta, "rb") as f: b = pickle.load(f) return b ''' secion = usuario_secion() secion.asignar_usuario("rc") secion.asignar_password("<PASSWORD>") secion.asignar_pc_name() secion.asignar_pc_ip() secion.asignar_last_connection() secion.asignar_ruta_bd("C:/Users/ricar/Desktop/pruebas v1/base/secion") secion.asignar_privilegios("1111") serializar(secion.ruta_archivo,secion) print(secion) '''<file_sep>/pruebas/prueba v1/hilos.py import threading import time def prueba(id,id1,id3): while True: print(id,id1,id3) time.sleep(1) s1=threading.Thread(name="s",target=prueba,args={1,2,3}) s2=threading.Thread(name="s",target=prueba,args={4,5,6}) s1.start() s2.start()<file_sep>/pruebas/pruebas aisladas/s.py from tkinter import * def func1(): print("in func1") def func2(): print("in func2") def selection(): try: dictionary[listbox.selection_get()]() except: pass root = Tk() frame = Frame(root) frame.pack() dictionary = {"1":func1, "2":func2} items = StringVar(value=tuple(sorted(dictionary.keys()))) listbox = Listbox(frame, listvariable=items, width=15, height=5) listbox.grid(column=0, row=2, rowspan=6, sticky=("n", "w", "e", "s")) listbox.focus() selectButton = Button(frame, text='Select', underline = 0, command=selection) selectButton.grid(column=2, row=4, sticky="e", padx=50, pady=50) root.bind('<Double-1>', lambda x: selectButton.invoke()) root.mainloop()<file_sep>/pruebas/v-versiones/v1.py from tkinter import * # Carga módulo tk (widgets estándar) from tkinter import ttk # Carga ttk (para widgets nuevos 8.5+) from os import listdir def donothing(): filewin = Toplevel(root) button = Button(filewin, text="Do nothing button") button.pack() def asignaritemsmenu(menu_items,list): for i in range (1,len(list)): menu_items.add_command(label=list[i], command = donothing) def prints(): if len(direcciones.curselection()) != 0: t=direcciones.get(direcciones.curselection()[0]) print(t) x = Label(root, text=t).pack(side=LEFT) root= Tk() root.geometry("{0}x{0}+0+0".format(root.winfo_screenwidth(), root.winfo_screenheight())) '''menu''' menu_bar= Menu(root) archivos=Menu(menu_bar,tearoff =0) '''lista y carga''' itemsmenu=["1","2","3","4","5"] '''asignaritemsmenu(archivos,itemsmenu)''' asignaritemsmenu(archivos,itemsmenu) archivos.add_separator() archivos.add_command(label = "Exit", command = root.quit) menu_bar.add_cascade(label="Archivos", menu=archivos) root.config(menu=menu_bar) '''administrador de archivos''' visualizadorbd = Frame(root,bd=5,cursor="hand1",bg="blue").place(x=0,y=0,relwidth=0.15,relheight=0.8) ruta=StringVar() direcciones= Listbox(visualizadorbd) lista_direcciones=StringVar() lista_direcciones=listdir("C:/Users/ricar/Desktop/Pruebas Bd") direcciones.place(x=0,y=0,relwidth=0.15,relheight=0.4) direcciones.insert(0,"das") t=StringVar() y=Button(root,text=t,command=prints).pack() root.mainloop() <file_sep>/v-2/pruebas/yacc - lex/lexema.py import ply.lex as lex # Declaración de palabras reservadas reserved = { 'public': 'public', 'private': 'private', 'static': 'static', 'final': 'final', 'void': 'void', 'main': 'main', 'class': 'class', 'while': 'while', 'if': 'if', 'else': 'else', } # Declaración de tokens tokens = ['TIPODATO', 'ABREPARENT', 'CIERRAPARENT', 'PUNTOCOMA', 'ABRELLAVE', 'CIERRALLAVE', 'ID', 'IGUAL', 'PUNTO', 'COMA', 'ABRECORCHETE', 'CIERRACORCHETE', 'PLUS', 'MINUS', 'TIMES', 'DIVIDE', 'MOD', 'LT', 'GT', 'LE', 'GE', 'EQ', 'NE','COMILLA'] + list(reserved.values()) # Definición de tokens # Comments def t_commentario(t): r'/[\*][a-zA-Z0-9\n]*[\*]/' t.lexer.lineno += t.value.count('\n') pass def t_ID(t): r'[a-zA-Z]+[a-zA-Z0-9_]*' t.type = reserved.get(t.value, 'ID') return t def t_TIPODATO(t): r'char|byte|double' return t t_COMILLA = r'\'' t_ABREPARENT = r'\(' t_CIERRAPARENT = r'\)' t_PUNTOCOMA = r'\;' t_ABRELLAVE = r'\{' t_CIERRALLAVE = r'\}' t_IGUAL = r'=' t_COMA = r',' t_PUNTO = r'\.' t_ABRECORCHETE = r'\[' t_CIERRACORCHETE = r'\]' # Operators t_PLUS = r'\+' t_MINUS = r'-' t_TIMES = r'\*' t_MOD = r'%' t_LT = r'<' t_GT = r'>' t_LE = r'<=' t_GE = r'>=' t_EQ = r'==' t_NE = r'!=' # Tokens a ignorar t_ignore = " \t" # Función error def t_error(t): print("Error Lexico: %s" % repr(t.value[0])) lex.lexer.skip(1) # Contador de línea def t_newline(t): r';\n' t.lexer.lineno += 1 # Construcción del lexer lexer = lex.lex() while True: text= input() lexer.input(text) while True: tok = lexer.token() if not tok: break print(tok) <file_sep>/pruebas/prueba servidor-cliente/ajedrez/juego-agedrez.py from tkinter import * # Carga módulo tk (widgets estándar) from tkinter import ttk # Carga ttk (para widgets nuevos 8.5+) from PIL import Image, ImageTk import tkinter as tk import socket import sys import datetime from tkinter import messagebox import time from threading import Lock import random 'sys.path.append("C:/Users/ricar/PycharmProjects/v-version/venv/prueba servidor-cliente/prueba.py")' 'from prueba import *' class ajedres(): def __init__(self): 'pieza actual seleccionada' self.pieza_i=0 self.pieza_j=0 'ver si hay vista de posibles movimientos activa' self.vista=FALSE 'lista de movimientos' self.mov_posibles=[] self.tablero = [] for i in range (8): self.tablero.append([]) for j in range (8): self.tablero[i].append(None ) self.tablero[0][0]=pieza(0,0,1,"torre") self.tablero[1][0]=pieza(0,1,1,"caballo") self.tablero[2][0]=pieza(0,2,1,"alfil") self.tablero[3][0]=pieza(0,3,1,"reina") self.tablero[4][0] = pieza(0,4,1,"rey") self.tablero[5][0]=pieza(0,5,1,"alfil") self.tablero[6][0] = pieza(0,6,1,"caballo") self.tablero[7][0] = pieza(0,7,1,"torre") self.tablero[0][7] = pieza(7,0,-1,"torre") self.tablero[1][7] = pieza(7,1,-1,"caballo") self.tablero[2][7] = pieza(7,2,-1,"alfil") self.tablero[3][7] = pieza(7,3,-1,"rey") self.tablero[4][7] = pieza(7,4,-1,"reina") self.tablero[5][7] = pieza(7,5,-1,"alfil") self.tablero[6][7] = pieza(7,6,-1,"caballo") self.tablero[7][7] = pieza(7,7,-1,"torre") for i in range(8): self.tablero[i][1]=pieza(1,i,1,"peon") self.tablero[i][6]=pieza(6,i,-1,"peon") self.turno=1 self.jugador1=1 self.jugador2=-1 self.ventana=Tk() self.ventana.geometry("900x800+200+10") self.canvas=Canvas(self.ventana) self.canvas.place(x=0,y=0,width=480,height=480) self.tam=50 self.inicio_x=30 ver=TRUE self.canvas.create_rectangle(80,80,480,480, fill="white", width=1) for i in range(8): self.inicio_x += self.tam self.inicio_y = 80 if ver: ver=FALSE else: ver=TRUE for i in range(8): if ver: self.canvas.create_rectangle(self.inicio_x,self.inicio_y,self.inicio_x+self.tam,self.inicio_y+self.tam,fill="black",width=1) ver=FALSE else: self.canvas.create_rectangle(self.inicio_x,self.inicio_y,self.inicio_x+self.tam,self.inicio_y+self.tam, fill="white",width=1) ver=TRUE self.inicio_y+=self.tam ruta="C:/Users/ricar/Desktop/pruebas/piezas/" imagenes=[] indice=0 inicio_x = 30 for i in range (8): inicio_x+=self.tam inicio_y=80 for j in range(2): jugador=self.tablero[i][j].jugador tipo=self.tablero[i][j].tipo_pieza ruta_imagen=ruta+str(tipo)+str(jugador)+".png" img=Image.open(ruta_imagen) img=img.resize((self.tam,self.tam)) self.tablero[i][j].imagen_pieza(ImageTk.PhotoImage(img)) imagenes.append(ImageTk.PhotoImage(img)) self.canvas.create_image( inicio_x ,inicio_y , anchor="nw", image=imagenes[indice],tags=str(i)+str(j)) indice+=1 self.tablero[i][j].x=inicio_x self.tablero[i][j].y=inicio_y inicio_y+=self.tam inicio_x = 30 for i in range(8): inicio_x+=self.tam inicio_y=380 for j in range(6, 8): jugador=self.tablero[i][j].jugador+3 tipo=self.tablero[i][j].tipo_pieza ruta_imagen=ruta+str(tipo)+str(jugador)+".png" img=Image.open(ruta_imagen) img=img.resize((self.tam,self.tam)) self.tablero[i][j].imagen_pieza(ImageTk.PhotoImage(img)) imagenes.append(ImageTk.PhotoImage(img)) self.canvas.create_image( inicio_x ,inicio_y , anchor="nw", image=imagenes[indice],tags=str(i)+str(j)) indice+=1 self.tablero[i][j].x=inicio_x self.tablero[i][j].y=inicio_y inicio_y+=self.tam self.canvas.bind('<1>',lambda event:self.hola(event)) print("enpezo") self.ventana.mainloop() def hola(self,event): ''' print("coords") print(event.x,event.y) print(self.canvas.canvasx(event.x),self.canvas.canvasy(event.y)) print(tk.CURRENT) print(self.canvas.find_withtag(tk.CURRENT)) print(self.canvas.find_closest(event.x,event.y)) ''' self.detectar_pieza(event.x,event.y,self.canvas.find_withtag(tk.CURRENT)) 'self.canvas.move(self.canvas.find_closest(event.x,event.y),10,10)' 'self.canvas.delete(self.canvas.find_withtag(tk.CURRENT))' '''for i in range (8): for j in range(8): if(self.canvas.find_withtag(tk.CURRENT)==self.canvas.find_withtag("{},{}".format(i,j))): print("1") if(self.canvas.find_closest(event.x,event.y)==self.canvas.find_withtag("{},{}".format(i,j))): print("2") if(self.canvas.find_withtag("{},{}".format(i,j))==self.canvas.find_closest(event.x,event.y)): print("3")''' def vista_movimiento(self): '' print(self.tablero[self.pieza_i][self.pieza_j].tipo_pieza) if self.tablero[self.pieza_i][self.pieza_j].tipo_pieza=="peon": if not self.vista: self.movimiento_peon() self.vista=TRUE ''' self.tablero[self.pieza_i+jugador][self.pieza_j-jugador]=pieza(x,y,self.tablero[self.pieza_i][self.pieza_j].jugador,"posible") self.tablero[self.pieza_i+jugador][self.pieza_j + jugador] = pieza(x,y, self.tablero[self.pieza_i][self.pieza_j].jugador, "posible") self.tablero[self.pieza_i+jugador][self.pieza_j ] = pieza(x, y, self.tablero[self.pieza_i][self.pieza_j].jugador, "posible") ''' else: self.mov_posibles = [] self.vista=FALSE self.canvas.delete("mov_pos") def movimiento_peon(self): jugador = self.tablero[self.pieza_i][self.pieza_j].jugador y = ((self.pieza_i + self.tablero[self.pieza_i][self.pieza_j].jugador) * self.tam) + 80 x = ((self.pieza_j + 1) * self.tam) + 30 self.canvas.create_rectangle(x, y, x + self.tam, y + self.tam, fill="yellow", width=0.1, tags="mov_pos") self.mov_posibles=[] if jugador == 1: ''' self.tablero[self.pieza_i + jugador][self.pieza_j - jugador]=pieza(0,0,0,"hola") self.tablero[self.pieza_i + jugador][self.pieza_j + jugador]=pieza(0,0,0,"hola") ''' self.mov_posibles.append(self.obtener_i(x)) self.mov_posibles.append(self.obtener_j(y)) if type(self.tablero[self.pieza_i + jugador][self.pieza_j + jugador]) == pieza: if self.tablero[self.pieza_i + jugador][self.pieza_j + jugador].tipo_pieza != "error": self.canvas.create_rectangle(x + self.tam, y, x + (2 * self.tam), y + self.tam, fill="yellow", width=0.1, tags="mov_pos") self.mov_posibles.append(self.obtener_i(x+self.tam)) self.mov_posibles.append(self.obtener_j(y)) if type(self.tablero[self.pieza_i + jugador][self.pieza_j - jugador]) == pieza: if self.tablero[self.pieza_i + jugador][self.pieza_j - jugador].tipo_pieza != "error": self.canvas.create_rectangle(x - self.tam, y, x, y + self.tam, fill="yellow", width=0.1, tags="mov_pos") self.mov_posibles.append(self.obtener_i(x-self.tam)) self.mov_posibles.append(self.obtener_j(y)) print("matrz mov",self.mov_posibles) else: 'self.tablero[self.pieza_i + jugador][self.pieza_j - jugador] = pieza(0, 0, 0, "hola")' 'self.tablero[self.pieza_i + jugador][self.pieza_j + jugador] = pieza(0, 0, 0, "hola")' if type(self.tablero[self.pieza_i + jugador][self.pieza_j - jugador]) == pieza: if self.tablero[self.pieza_i + jugador][self.pieza_j - jugador].tipo_pieza != "error": self.canvas.create_rectangle(x + self.tam, y, x + (2 * self.tam), y + self.tam, fill="yellow", width=0.1, tags="mov_pos") if type(self.tablero[self.pieza_i + jugador][self.pieza_j + jugador]) == pieza: if self.tablero[self.pieza_i + jugador][self.pieza_j + jugador].tipo_pieza != "error": self.canvas.create_rectangle(x - self.tam, y, x, y + self.tam, fill="yellow", width=0.1, tags="mov_pos") def movimiento_torre(self): jugador = self.tablero[self.pieza_i][self.pieza_j].jugador def detectar_pieza(self,x,y,pieza_canvas): self.pieza_j=(y-30)//self.tam -1 self.pieza_i=(x-30)//self.tam -1 if type(self.tablero[self.pieza_i][self.pieza_j])==pieza: self.vista_movimiento() else: 'mover la pieza' print("mover pieza") if len(self.mov_posibles)!=0: nuevo_i=self.obtener_i(x) nuevo_j=self.obtener_j(y) print(self.obtener_x_y(nuevo_i) ,self.obtener_x_y(nuevo_j) ) self.canvas.create_image(self.obtener_x_y(nuevo_i) ,self.obtener_x_y(nuevo_j) , anchor="nw", image=self.tablero[self.pieza_i][self.pieza_j] ,tags=str(self.pieza_i)+str(self.pieza_j)) self.canvas.delete(str(self.pieza_i)+str(self.pieza_j)) s=self.tablero[nuevo_i][nuevo_j] print(s) print(self.tablero[self.pieza_i][self.pieza_j].tipo_pieza) self.tablero[nuevo_i][nuevo_j]=self.tablero[self.pieza_i][self.pieza_j] self.tablero[self.pieza_i][self.pieza_j]=s del s self.mov_posibles=[] def obtener_i(self,x): return int((x - 30) // self.tam - 1) def obtener_j(self,y): return int((y - 30) // self.tam - 1) def obtener_x_y(self,i): return int(((i+1)*self.tam)+30) class pieza(): def __init__(self,x,y,jugador,tipo_pieza): self.x=int(x) self.y=int(y) self.jugador=int(jugador) self.tipo_pieza=tipo_pieza def imagen_pieza(self,imagen): self.imagen_pieza=imagen ajedres() <file_sep>/pruebas/prueba v1/subpruebav1 servers/servidor.py import socket import threading import time class server(): def __init__(self): self.ip=socket.gethostbyname(socket.gethostname()) self.fin=0 'establece conexion' while True: try: puerto=8000 self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.s.connect((self.ip ,puerto)) print("se conexto envia") break except: print("sigue") puerto=8001 self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server.bind((self.ip,puerto)) self.server.listen(1) self.conexion, self.direccion = self.server.accept() 'se establecio recive' 'fin de establece conexion' self.comprobacion=0 self.hilo1=threading.Thread(name="1",target=self.envia) self.hilo1.start() self.hilo2=threading.Thread(name="1",target=self.recive) self.hilo2.start() print("inicio") def recive(self): while True: peticion = self.conexion.recv(1024).decode() print(peticion) if (self.fin==1): break self.conexion.close() def envia(self): while True: self.s.send("mensaje ".encode('utf-8')) print("se a enviado el mensaje") time.sleep(1) if self.comprobacion==1: break self.s.close() h=server()<file_sep>/v-2/pruebas/envio de archivos por socket/envio por partes/cliente.py import socket import pickle import sys paso=8 r="archivo.txt" c=open(r,"rb") fin= (sys.getsizeof(c.read())) iteraciones=fin//paso c.seek(0) w=0 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('localhost',8000)) tamaños=0 validador=True while validador: s.send(c.read(paso)) w+=paso c.seek(w) print("fin",fin,"w",w) if w>fin: validador=False s.send("termino".encode()) print("tamaños: ",tamaños,"cantidad de iteraciones: ",iteraciones) s.send(("termino").encode()) s.close() <file_sep>/pruebas/pruebas aisladas/textbox.py from tkinter import * from tkinter import ttk def obt(): print(textbox.get()) v= Tk() v.geometry("500x500") textbox= Entry(v) textbox.pack() b= Button(v,command=obt).place(x=50,y=50,width=30,height=20) v.mainloop()<file_sep>/pruebas/pruebas aisladas/cliente-servidor/otra forma/servidor.py import socket import time import threading s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('',8000)) s.listen(1) a=[] i=0 while True: a.append(0) a[i], direccion= s.accept() print("se a conectado") print(a[i]) print(direccion) peticion = a[i].recv(1024) print(peticion) mensaje="hola cliente" a[i].send(mensaje.encode('utf-8')) 'a[i].close()' i += 1 if len(a)>4: break print(len(a)) print(a) ''' def imprime(io): while True: print(io) time.sleep(1) b=[] for i in range(10): b.append(threading.Thread(name="movimiento",target=imprime,args={i})) b[i].start() '''
d29baf1efe018a9f30280cdfb6fabb553ea27b86
[ "Python" ]
54
Python
ColqueRicardo/v-version
45fd067443e084f510f69053a70507956edae0a2
7c3bd074a5ce9e3b774d1cbd95a4059683d7b46e
refs/heads/master
<file_sep># Описание проекта NeuroStartUp: **NeuroStartUp - динамически развивающийся стартап, специализирующийся на поиске с использованием новейших технологий искусственного интеллекта.** ## Базовые установки проекта *В данном разделе указаны необходимые шаги пользователя, для установки NeuroStartUp на персональный компьютер* ### Установка проекта Откройте консоль проекта и выполните следующие шаги: 1. Нажмите клавишу "Старт" 1. Следуйте инструкциям мастера установки ### Настройки проекта 1. Выберите язык установки 1. В открывшемся меню укажите 1. Адрес своего местонахождения 1. Контактный телефон для связи ### Запуск проекта * Нажмите кнопку Новый проект * После заставки выполните следующие действия * Введите логин * Введите пароль ~~[Сайт проекта]~~(http://www.123456789.ru)
f4764a8c0b372a4eb7ea75584755b69c7f5345b6
[ "Markdown" ]
1
Markdown
Casa-Bonita/GIT-leson1-work1
7f968054bca5749327e1abce68c1bd2aeb410a92
734edbf036689b5df6a755a11abcfdd9e601d1e0
refs/heads/master
<file_sep># twitter School project.
0085827fe66ad29cf8a7be16e951c42286d01294
[ "Markdown" ]
1
Markdown
louiced/twitter
3067b9029643de4dd335da26330f7ae087bb2f8c
8ebe083f21cf93c0ec6bc22d854f0328800320ae
refs/heads/master
<repo_name>digitalscientists/css<file_sep>/screen.sass body :font-family :font-size :color table thead tbody tr th td form .text_field .text_area .select_box .check_box .radio_button .file_field .submit_button .button_field label fieldset legend ul .inline :list-style-type none li :display inline ol li a :outline none img :border none &:hover h1 h2 h3 h4 h5 h6 .container :width Xpx :margin 0 auto :clear both .content :clear both .padded .notice .error .fieldWithErrors
dd76d509618ceca0668442671c2ebe9afb0f8e2c
[ "Sass" ]
1
Sass
digitalscientists/css
5f766fd4cea077f2d7e7215188a71d7367d54845
9b8a6520c6a77132c21d3abb455372f2ddd9f57f
refs/heads/master
<repo_name>SamKuper/project-lvl1-s454<file_sep>/src/games/even.js import { startGame } from '..'; import generateNumber from '../utils'; import { cons } from 'hexlet-pairs' const isEven = num => num % 2 === 0; const trueAnswer = (num) => isEven(num) ? 'yes' : 'no'; const gameMessage = 'Answer "yes" if number even otherwise answer "no".'; const gameConfig = () => { const question = generateNumber(1, 13543); const correctAnswer = trueAnswer(question) return cons(question, correctAnswer); }; export default () => startGame(gameConfig, gameMessage); <file_sep>/README.md # project-lvl1-s454 [![Maintainability](https://api.codeclimate.com/v1/badges/a99a88d28ad37a79dbf6/maintainability)](https://codeclimate.com/github/SamKuper/project-lvl1-s454) [![Build Status](https://travis-ci.org/SamKuper/project-lvl1-s454.svg?branch=master)](https://travis-ci.org/SamKuper/project-lvl1-s454) [![asciicast](https://asciinema.org/a/Udf4mVM3Av0buXHiwNEnuG9tm.svg)](https://asciinema.org/a/Udf4mVM3Av0buXHiwNEnuG9tm) [![asciicast](https://asciinema.org/a/TEpv0bCIPYk7kXL4Igq8EjLbj.svg)](https://asciinema.org/a/TEpv0bCIPYk7kXL4Igq8EjLbj) [![asciicast](https://asciinema.org/a/wAiSE7pNncoFh7LwKJGacxJ80.svg)](https://asciinema.org/a/wAiSE7pNncoFh7LwKJGacxJ80) [![asciicast](https://asciinema.org/a/KHSgyon7cVfL0gftY06U88n2s.svg)](https://asciinema.org/a/KHSgyon7cVfL0gftY06U88n2s) [![asciicast](https://asciinema.org/a/re7kYqYDCU4M8XwvjCNgjY6Px.svg)](https://asciinema.org/a/re7kYqYDCU4M8XwvjCNgjY6Px) <file_sep>/src/utils.js const generateNumber = (a, b) => Math.floor(Math.random() * (b - a + 1)) + a; export default generateNumber; <file_sep>/src/games/prime.js import { startGame } from '..'; import generateNumber from '../utils'; import { cons } from 'hexlet-pairs'; const gameMessage = 'Answer "yes" if given number is prime. Otherwise answer "no"'; const isEven = num => num % 2 === 0; const isPrime = (num) => { if (isEven(num) && num > 3 || num < 2) { return false; } if (num === 2) { return true; } const minDivisor = 3; const iter = (i) => { if (num % i !== 0 && i > num / i || num < 4) { return true; } if (num % i === 0) { return false; } return iter(i + 2); }; return iter(minDivisor) }; const gameConfig = () => { const question = generateNumber(1, 150); const trueAnswer = isPrime(question) ? 'yes' : 'no'; return cons(question, trueAnswer); }; export default () => startGame(gameConfig, gameMessage); <file_sep>/Makefile install: npm install start: npx babel-node -- src/bin/brain-games.js publish: npm publish lint: npx eslint src . <file_sep>/src/games/progression.js import { startGame } from '..'; import generateNumber from '../utils'; import { cons } from 'hexlet-pairs'; const gameMessage = 'What number is missing in the progression?'; const progressionMembers = 10; const gameConfig = () => { const zeroMember = generateNumber(1, 20); const diff = generateNumber(1, 7); const emptyPosition = generateNumber(0, progressionMembers - 1); const findValue = (position) => position === emptyPosition ? '..' : zeroMember + (diff * position); const createQuestion = () => { const iter = (i, acc) => { if (i === 0) { return `${findValue(i)}` + acc; } return iter(i - 1, ` ${findValue(i)}` + acc); }; return iter(progressionMembers - 1, ''); }; const question = createQuestion(); const trueAnswer = String(zeroMember + (diff * emptyPosition)); return cons(question, trueAnswer); }; export default () => startGame(gameConfig, gameMessage); <file_sep>/src/games/calc.js import { startGame } from '..'; import generateNumber from '../utils'; import { cons } from 'hexlet-pairs' const gameMessage = 'What is the result of the expression?'; const gameConfig = () => { const value_a = generateNumber(1, 25); const value_b = generateNumber(1, 25); const operatorNumber = generateNumber(1, 3); const operationChoose = (operatorNumber) => { switch(operatorNumber) { case 1: return cons(`${value_a} + ${value_b}`, value_a + value_b); case 2: return cons(`${value_a} - ${value_b}`,value_a - value_b ); case 3: return cons(`${value_a} * ${value_b}`, value_a * value_b); } }; const gameData = operationChoose(operatorNumber); return gameData; }; export default () => startGame(gameConfig, gameMessage);
f1086a320fee83f70c57ec1ac9db0f9bbbc6b7bb
[ "Makefile", "Markdown", "JavaScript" ]
7
Makefile
SamKuper/project-lvl1-s454
dbf7ae5e4aa14e7190151144d8a91b618eda8fd7
aaab3a31853c59ded198160c4c179592c52be305
refs/heads/master
<file_sep>const { spaceLess } = require('../common/spacecape.js'); const transitions = { template: { '{=': ['push', 'variable'], '{#': ['push', 'variable'], '{?': ['push', 'variable'], '{!': ['push', 'variable'], '{|': ['push', 'template'], '{:': ['push', 'helpers'], '|}': ['pop', 'template'], '|:': ['', 'helpers'], }, variable: { '.': ['', 'variable'], ':': ['', 'helpers'], '|': ['def', 'template'], '}': ['pop', 'template'], }, helpers: { '|': ['flip', 'template'], ':': ['', 'helpers'], '}': ['pop', 'template'], } } module.exports = function parse(string) { const stack = []; let context = 'template'; let startIx = 0, i = 0; let current = { tag: '|', template: [], helpers: [] }; const ops = { push, pop, flip, def }; while (i < string.length) { for (const token in transitions[context]) { if (!test(token)) continue; add(string.substring(startIx, i), token); startIx = i + token.length; i += (token.length - 1); break; } i++; } if (startIx < string.length) add(string.substr(startIx)); if (stack.length) throw Error('strtl.render.missing }'); return current.template; function push(token) { const node = { tag: token[1], variable: [], template: [], helpers: [] }; current.template.push(node); stack.push(current); current = node; } function pop() { if (!stack.length) throw Error('strtl.render.unexpected }'); current = stack.pop(); } function flip() { current = { tag: '!', variable: current.variable, template: [], helpers: [], }; stack[stack.length - 1].template.push(current); } function def() { if (current.tag === '=') flip(); } function add(value, token) { if (context === 'template') value = spaceLess(value); if (value) current[context].push(value); if (!token) return; const [op, nextState] = transitions[context][token]; if (ops[op]) ops[op](token); if (nextState) context = nextState; } function test(token) { for (let j = 0; j < token.length; j++) { if (token[j] !== string[i + j]) return false; } return true; } } <file_sep>const assert = require('assert'); const tests = []; const only = []; global.makeTest = fn => { const test = (...args) => tests.push([fn, ...args]); test.skip = (...args) => console.log('SKIP', args.pop()); test.only = (...args) => only.push([fn, ...args]); return test; }; function runTest([fn, ...args]) { const expected = args.pop(); let result; try { result = fn(...args); assert.deepEqual(result, expected); console.log('PASS', fn.name, expected); } catch (e) { console.log('FAIL', fn.name, expected); console.error('Error:', e); } } require('./common/spacecape.test.js'); require('./build/build.test.js'); require('./render/toString.test.js'); require('./render/toObject.test.js'); if (only.length) { only.forEach(runTest); } else { tests.forEach(runTest); } <file_sep>const render = require('./index.js'); const test = makeTest(render.toObject); test( '{"ex":"This is { =} too.","why":"{\\"foo\\":{=foo:json},\\"bar\\":{ =bar:json}}"}', { foo: 33 }, {}, {"ex":"This is {=} too.","why":'{"foo":33,"bar":{=bar:json}}'}, ); test( '{"foo":33,"bar":{=bar:json}}', { bar: {"pot": "ato" } }, { foo:33, bar: { pot: 'ato' } } ) <file_sep>const root = require('./proxy.js'); const { strOuter } = require('./affixes.js'); let lastId = 0; function getId() { if (lastId > 9999) lastId = 0; return '' + lastId++; } module.exports = function build(buildFn) { const buildId = getId(); const built = buildFn(root(buildId)); return strOuter(built, buildId); } <file_sep>const build = require('./index.js'); const test = makeTest(build); test( ({ name }) => ({ N: name }), '{"N":{=name:json}}' ) test( ({ name }) => ({ N: name.upper() }), '{"N":{=name:upper:json}}' ) test( ({ emails }) => ({ E: emails.map(e => e), }), '{"E":[{#emails|{:json}|:join}]}' ) test( ({ emails }) => ({ E: emails.map(e => e.upper()).filter('4'), }), '{"E":[{#emails|{:upper:json}|:filter 4:join}]}' ) test( ({ error }) => ({ code: error.then(400).else(200) }), '{"code":{?error|400|:|200|}}' ) test( ({ error }) => ({ code: error.then(400).toFixed().else(200).toFixed() }), '{"code":{?error|400|:toFixed|200|:toFixed}}' ) test( ({ name }) => ({ N: name.else('Hi') }), '{"N":{=name:json|"Hi"|}}' ) test( ({ name, number }) => ({ N: name.else({ foo: number }) }), '{"N":{=name:json|{"foo":{=number:json}}|}}' ) test( ({ rand }) => ({ roll: rand(1, 2) }), '{"roll":{:rand 1 2:json}}' ) test( ( {foo} ) => ({ ex: 'This is {=} too.', foo}), '{"ex":"This is { =} too.","foo":{=foo:json}}' ) test( ({foo}) => ({ ex: 'This is {=} too.', why: build(({ bar}) => ({ foo, bar }))}), '{"ex":"This is { =} too.","why":"{\\"foo\\":{=foo:json},\\"bar\\":{ =bar:json}}"}' ) <file_sep>const render = require('./render'); const build = require('./build'); exports.render = render; exports.build = build; <file_sep># 😮 Strtl [![NPM](https://img.shields.io/npm/v/strtl?style=flat-square)](https://www.npmjs.com/package/strtl) A shockingly minimal templating language for strings and JSON. The syntax is as small and intuitive as possible, while retaining powerful features like custom helpers. There are zero dependencies, and the renderer (used on the client), is under 200 lines of code. - **[Syntax and rendering](#syntax-and-rendering)** - [Scope](#scope) - [Helpers](#helpers) - [Default](#default) - [Loops](#loops) - [Conditionals](#conditionals) - [Escaping](#escaping) - [Truthiness](#truthiness) - **[Building JSON templates](#building-json-templates)** - [Concept](#concept) - [Simpe example](#simple-example) - [Helpers](#helpers-1) - [Loops](#loops-1) - [Conditionals](#conditionals-1) - [Default](#default-1) - [Combining helpers](#combining-helpers) - **[Why JSON templates?](#why-json-templates)** ## Syntax and rendering ```js import render from 'strtl/render'; ``` There are two render methods: - `render.toString()`: Renders a template to a string and returns it. - `render.toObject()`: Does the same thing but does `JSON.parse()` on the result before returning it. ```js render.toString( 'Hello, {=name}!', { name: 'World' } ); // Returns 'Hello, World!' ``` ### Scope A template string is processed in the context of a *scope* to return a rendered string. Placeholders in the template may be dot-separated expressions that are resolved in the scope. The scope might be a single object or a list of objects. If it's a list, strtl uses the first one in which a placeholder appears. ```js render.toString( 'Hi {=user.name}, you have {=user.count} notifications.', [ { user: { name: 'Emily' } }, { user: { count: 3 } } ] ) // Returns 'Hi Emily, you have 3 notifications.' ``` ### Helpers Helpers are transformation functions that can be applied to values before printing. Helper names are prefixed with `:` and accept arguments separated by spaces. ```js render.toString( 'Total: {=total:toFixed 2}', { total: 3.1416 }, { toFixed: (num, digits) => num.toFixed(digits) } ) // Returns 'Total: 3.14' ``` The first argument to the helper function will be the value before the `:`. This will be of the same type as in the scope: in the example above, this will be a number. The remaining arguments are from the template, and passed as strings ('2' above). It's also possible to chain multiple helpers, and to pass a rendered template through helpers: ```js render.toString( '{|Hello {=name}|:toUpperCase :urlEncode}', { name: 'World' } { toUpperCase: str => str.toUpperCase(), urlEncode: str => encodeURIComponent(str) } ) // Returns 'HELLO%20WORLD' ``` Helper functions may return any JavaScript value, but the value returned by the last helper in a chain is converted to a string before inserting into the template. Finally, you could also have helper-only tags: ```js render.toString( 'Die roll: {:roll}', {}, { roll: () => 1 + Math.floor(6 * Math.random()) } ) // Returns 'Die roll: 4' ``` ### Default A default value may be provided, which is used when the placeholder's value is [falsy](#truthiness): ```js render.toString( 'Hi {=name|You|}', {} ) // Returns 'Hi You' ``` This works as expected with helpers too. ```js '{=placeholder:helper|Default value|:defaultHelper}' ``` ### Loops Loops use the syntax `{#variable|Repeating template|}`, where `variable` points to an array in the scope. For each value in that array, the template between the `|` and `|}` is rendered, and the item itself is added to the scope. ```js render.toString( '{#books| ${title} by ${author}; |}', { books: [ { title: '1984', '<NAME>' }, { title: '2001', '<NAME>' } ] } ) // Returns '1984 by George Orwell; 2001 by <NAME>;' ``` When looping over strings or numbers, `{=}` is the placeholder for the current element. Loops also support helpers, which are called with an array of rendered strings as the first argument. ```js render.toString( 'Hi {#names|Dr. {=}|:listFormat}', { names: ['Alice', 'Bob', 'Carol'] }, { listFormat: items => new Intl.ListFormat('en').format(items) } ) // Returns 'Hi Dr. Alice, Dr. Bob and Dr. Carol' ``` ### Conditionals The tag `{?variable|True template|}` renders the sub-template if the variable is [truthy](#truthiness), while `{!variable|False template|}` renders it if it is falsy. There is also a couple of shortcuts for common patterns: - `{?variable|True template|:|False template|}`. If-else without repeating the variable. This is syntactic sugar for `{?variable|True template|}{!variable|False template|}`. - `{#variable|Repeating Template|:|Empty template|}`. A default value for empty loops. Syntactic sugar for `{#variable|Repeating Template|}{!variable|Empty template|}`. ### Escaping There are no reserved characters that need to be escaped. However the following 2-character tokens, if they appear in the text, need to be escaped: - Start of an embedded tag: `{=`, `{#`, `{?`, `{!`, `{:` `{|` - End of a nested template: `|:`, `|}` Escaping is performed by inserting a space character between the two characters of the token. If a string is escaped twice, it will have two spaces, and so on. Each call to render un-escapes once by removing a single space. ### Truthiness If a placeholder is considdered falsy if it does not exist in the scope or resolves to `undefined`, `null`, `false`, `0`, an empty string or an empty array. In all other cases, it's considered truthy. ## Building JSON templates ```js import build from 'strtl/build'; ``` `build()` is a somewhat magical function to intuitively build templates that can `render.toObject()` into JS objects. There is no equivalent function for building string templates, as those are easy to write by hand. ### Concept `build()` accepts a JavaScript function as argument, and returns a template string representing the data transformation operations in that function. You can pretend that the function can time travel into the future when the template is rendered, and the render time data is passed to it as an argument. That might sound like we're calling `.toString()` on the function and sending it to the client to be `eval`uated - we are not. We use ES Proxies to make this syntax work. ### Simple example ```js build(({ name }) => ({ N: name })) // Returns '{"N":{=name:json}}' ``` Note the `:json` helper. `toObject()` adds this helper transparently; this allows `name` to be any valid JSON object, not just a string. This template can be used with `.toObject()`: ```js render.toObject('{"N":{=name:json}}', { name: 'Alice' }) // Returns { N: 'Alice' } render.toObject('{"N":{=name:json}}', { name: ['First', 'Last'] }) // Returns { N: ['First', 'Last'] } ``` ### Helpers Method calls become helpers. ```js build(({ name }) => ({ N: name.upper() })) // Returns '{"N":{=name:upper:json}}' ``` ### Loops Not **all** method calls become helpers; `.map()` is a special method to produce loops. They work like `Array.prototype.map()`. ```js build(({ emails }) => ({ E: emails.map(e => e), })) // Returns '{"E":[{#emails|{=:json},|}]}' ``` ### Conditionals The if-else construct is supported, but unfortunately this requires using the special `.then()` and `.else()` methods in a chain rather than `if` statements or ternary operators. ```js build(({ error }) => ({ code: error.then(400).else(200) })) // Returns '{"code":{?error|400|:|200|}}' ``` Note that it is possible to write a `.then()` call without an `.else()`, but the opposite is not. ### Default `.else()` does double-duty as the method for providing a default value for a placeholder. ```js build(({ name }) => ({ N: name.else('Hi') })) // Returns '{"N":{=name:json|"Hi"|}}' ``` ### Combining helpers Helpers can be combined with loops, conditionals and default. ```js build(({ emails }) => ({ E: emails.map(e => e.upper()).filter('example.com'), })) // Returns '{"E":[{#emails|{=:upper:json},|:filter example.com}]}' ``` ```js build(({ error }) => ({ code: error.then(400).toFixed().else(200).toFixed() })) // Returns '{"code":{?error|400|:toFixed|200|:toFixed}}' ``` ```js build(({ name, number }) => ({ N: name.else({ foo: number }) })) // Returns '{"N":{=name:json|{"foo":{=number:json}}|}}' ``` ## Why JSON templates While there are undoubtedly other use cases for a templating language for JSON objects, this is ours: We have a mobile app that can display custom, user-configured forms, described using JSON. We require client-side interactivity where some fields should be reconfigured (enabled or disabled, shown or hidden, options modified) when the value in another field changes. Users can now build JSON templates for their forms to express these requirements. <file_sep>const parse = require('./parse.js'); const render = require('./render.js'); function toString (template, scopes, helperFns) { if (!Array.isArray(scopes)) scopes = [scopes]; const tree = parse(template); return render(tree, scopes, helperFns); } function toObject (template, scopes, helperFns = {}) { return JSON.parse(toString(template, scopes, { ...helperFns, json: JSON.stringify, join: (arr, delim=',') => arr.join(delim) })); } module.exports = { toString, toObject } <file_sep>const { prefix, suffix, spacer, tplPrefix, tplSuffix } = require('./affixes.js'); const wrapped = Symbol(); const wrap = value => ({ [wrapped]: value }); function proxy(node, id) { const func = () => {}; func.node = node; func.id = id; return new Proxy(func, traps); } const traps = { get({ node, id }, key) { if (key === 'toString') return JSON.stringify(node); if (key === 'toJSON') return toJSON(node, id); if (typeof key === 'symbol') return; return proxy({ ...node, expr: node.expr.concat([key]) }, id); }, ownKeys() { return []; }, apply({ node, id }, self, args) { const name = node.expr[node.expr.length - 1]; const expr = node.expr.slice(0, -1); switch(name) { case 'map': const child = wrap(args[0](root(id))); return proxy({ ...node, expr, tag: '#', nodes: [child] }, id); case 'then': return proxy({ ...node, expr, tag: '?', nodes: [wrap(args[0])] }, id) case 'else': const numNodes = node.nodes.length; const lastNode = node.nodes[numNodes - 1]; const delim = numNodes > 0 && typeof lastNode !== 'string' ? ':' : ''; const nodes = node.nodes.concat([delim, wrap(args[0])]); return proxy({ ...node, expr, nodes }, id); default: // const tag = expr.length ? node.tag : ''; return proxy({ ...node, expr, tag: node.tag, nodes: node.nodes.concat([ ':' + name, ...args].join(' ')) }, id) } } }; const root = id => proxy({ tag: '=', expr: [], nodes: [] }, id); const toJSON = ({ tag, expr, nodes }, id) => () => { const result = []; let tagStart = '{', tagEnd = '}', exprTrail = ''; if (tag === '#') { tagStart = '[{'; tagEnd = ':join}]'; } else if (tag === '=' || tag === '') { if (!expr || !expr.length && nodes) tag = ''; exprTrail = ':json' } let string = prefix + tagStart + spacer(id) + tag + expr.join('.'); for (const node of nodes) { if (typeof node === 'string') { string += node; } else { result.push(string + exprTrail + tplPrefix, node[wrapped]); string = tplSuffix + spacer(id); exprTrail = ''; } } string += exprTrail + tagEnd + suffix; result.push(string); return result; }; module.exports = root; <file_sep>const render = require('./index.js'); const test = makeTest(render.toString); const helpers = { upr: (s) => s.toUpperCase(), lwr: (s) => s.toLowerCase() }; test( 'Hi {=name:lwr|You|:upr}', {}, helpers, 'Hi YOU' ); test( 'Hi {=name:lwr|You|:upr}', { name: 'Alice' }, helpers, 'Hi alice' ); test( 'mailto:{#foo.recipients|{=email}{=delim}|}?...', { delim: ';', foo: { recipients: [ { email: '<EMAIL>' }, { email: '<EMAIL>' } ]}}, 'mailto:<EMAIL>;<EMAIL>;?...' ); test( 'foo{|Hello, {=name:up}|:url}', { name: 'World' }, { url: encodeURIComponent, up: str => str.toUpperCase() }, 'fooHello%2C%20WORLD' ); test( '{#tags|Tag {=} |:|No tags|}', { tags: ['1', '2'] }, 'Tag 1 Tag 2 ' ); test( '{#tags|Tag {=} |:|No tags|}', { tags: [] }, 'No tags' ); test( '{?tags|Has tags|:upr|No tags|:lwr}', { tags: 1 }, { upr: (s) => s.toUpperCase(), lwr: (s) => s.toLowerCase() }, 'HAS TAGS' ); test( '{?tags|Has Tags|:upr|No Tags|:lwr}', { tags: 0 }, { upr: (s) => s.toUpperCase(), lwr: (s) => s.toLowerCase() }, 'no tags' ); test( 'mailto:{#recipientEmails|{=};|:url}?subject={=subject:url}', { recipientEmails: ['<EMAIL>', '<EMAIL>'], subject: 'Hi there ^_^' }, { url: encodeURIComponent }, 'mailto:rizkisunaryo%40gmail.com%3B%2Crizki%40nektar.ai%3B?' + 'subject=Hi%20there%20%5E_%5E' ); test( '{:now}', {}, { now: () => 123 }, '123' );
24d5af2f74a9731cee825ea207872fb4a6bc6276
[ "Markdown", "JavaScript" ]
10
Markdown
nektarai/strtl
98a7536eb3cb1b97b479a4765aad6c9f7990396e
9c316fd9092992cfdecf763e1f2dee93b140c40c
refs/heads/master
<repo_name>shaunpat/Javascript-ben<file_sep>/script.js $('span').click(function() { console.log("You clicked it LOL"); $('body').css('background-color', 'yellow'); }); $('body').css ({ 'margin-top':'5%', 'margin-bottom':'5%', 'margin-left':'10%', 'margin-right':'10%' }); $('body').css('background-color', '#FFFFFF');<file_sep>/README.md # Javascript-ben The HTML file imports the JavaScript file. So you can essentially pretend like all of the JavaScript we write in script.js is inside of the HTML file itself. jQuery is imported in the same way in the <head> element, so we can use jQuery in script.js.
c91f452ccc4e0e3707709beda5a03a3fbc7e7161
[ "Markdown", "JavaScript" ]
2
Markdown
shaunpat/Javascript-ben
3b6766ba034745d0da0e814dcb65b4700ccff94e
db0b75a30967e30b494b9bc9275b13231852ea68
refs/heads/master
<repo_name>anamariasosam/best_quotes_native_app<file_sep>/android/settings.gradle rootProject.name = 'best_quotes' include ':app'
5b412c575944b379467834659b5357c98991a7a5
[ "Gradle" ]
1
Gradle
anamariasosam/best_quotes_native_app
e50a9f8d0693b9a408f8ebb4f655b81110d5b67d
82afe01f6f192deff9a44b72bf7cfd1e9185e470
refs/heads/master
<repo_name>janlueders/FacebookCrypter-C-<file_sep>/FirstFacebookApplication/classes/Database.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SQLite; using System.Collections; namespace FirstFacebookApplication { class Database { private string dataSource = "fbCrypter.db"; private SQLiteConnection connection; public Database() { connection = new SQLiteConnection(); connection.ConnectionString = "Data Source=" + dataSource; connection.Open(); createBaseTable(); } private void createBaseTable() { SQLiteCommand command = new SQLiteCommand(connection); command.CommandText = "CREATE TABLE IF NOT EXISTS friends ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name VARCHAR(255) NOT NULL, sharedKey VARCHAR(255) NOT NULL);"; command.ExecuteNonQuery(); command.CommandText = "INSERT INTO friends (id, name,sharedKey) VALUES(NULL, '100001591876114','100001591876114')"; command.ExecuteNonQuery(); command.Dispose(); } public Hashtable getFriends() { Hashtable myHT = new Hashtable(); SQLiteCommand command = new SQLiteCommand(connection); command.CommandText = "SELECT name,sharedKey FROM friends DESC"; SQLiteDataReader reader = command.ExecuteReader(); while (reader.Read()) { if (!myHT.ContainsKey(reader[0].ToString()) && !myHT.ContainsValue(reader[1].ToString())) { myHT.Add(reader[0].ToString(), reader[1].ToString()); } } reader.Close(); reader.Dispose(); command.Dispose(); return myHT; } public string getSpecifiedSharedKey(string userId) { string sharedKey = ""; SQLiteCommand command = new SQLiteCommand(connection); command.CommandText = "SELECT sharedKey FROM friends WHERE name = "+userId+" DESC"; SQLiteDataReader reader = command.ExecuteReader(); while (reader.Read()) { sharedKey = reader[0].ToString(); } reader.Close(); reader.Dispose(); command.Dispose(); return sharedKey; } } } <file_sep>/FirstFacebookApplication/forms/Stream.cs  namespace FirstFacebookApplication { using System; using Facebook; using System.Windows.Forms; using System.Collections.Generic; public partial class Stream : Form { private const string AppId = "271893929589092"; private const string ExtendedPermissions = "user_about_me,publish_actions,read_stream,publish_stream,status_update,offline_access"; private string _accessToken; public Stream() { InitializeComponent(); } private void DisplayAppropriateMessage(FacebookOAuthResult facebookOAuthResult) { if (facebookOAuthResult != null) { if (facebookOAuthResult.IsSuccess) { _accessToken = facebookOAuthResult.AccessToken; this.loadFacebook(); var timer = new Timer(); timer.Tick += new EventHandler(timer_Tick); timer.Interval = 60000; timer.Start(); } else { MessageBox.Show(facebookOAuthResult.ErrorDescription); } } } private void loginToolStripMenuItem1_Click(object sender, EventArgs e) { var fbLoginDialog = new FacebookLoginDialog(AppId, ExtendedPermissions); fbLoginDialog.ShowDialog(); DisplayAppropriateMessage(fbLoginDialog.FacebookOAuthResult); loginToolStripMenuItem1.Visible = false; } private void logoutToolStripMenuItem1_Click(object sender, EventArgs e) { var webBrowser = new WebBrowser(); var fb = new FacebookClient(); var logouUrl = fb.GetLogoutUrl(new { access_token = _accessToken, next = "https://www.facebook.com/connect/login_success.html" }); webBrowser.Navigate(logouUrl); loginToolStripMenuItem1.Visible = true; } private void timer_Tick(object sender, EventArgs e) { this.loadFacebook(); } private void loadFacebook() { FacebookWorker fbWorker = new FacebookWorker(_accessToken); Panel panels = fbWorker.getDataSetForDataGrid(); panels.Name = "FacebookMainBoard"; this.groupBox1.Controls.Clear(); this.groupBox1.Controls.Add(panels); } private void button1_Click(object sender, EventArgs e) { FacebookWorker fbWorker = new FacebookWorker(_accessToken); fbWorker.postToWall(this.textBox1.Text); Panel panels = fbWorker.getDataSetForDataGrid(); panels.Name = "FacebookMainBoard"; this.groupBox1.Controls.Clear(); this.groupBox1.Controls.Add(panels); } } } <file_sep>/FirstFacebookApplication/classes/VideoLoader.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.IO; using System.Web; namespace FacebookCrypter.classes { class VideoLoader { public string GetDownloadLink(string inputurl, ref string title_video) { string outputurl = ""; string type = ""; int size = 0; string source; var request = (HttpWebRequest)WebRequest.Create(inputurl.ToString()); var response = (HttpWebResponse)request.GetResponse(); source = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8).ReadToEnd(); //get title title_video = source.Substring(source.IndexOf("<title>") + 7, source.IndexOf("</title>") - (source.IndexOf("<title>") + 7)).Replace("\n", "").Replace("youtube", ""); if (source.IndexOf("video_id") > -1) { if (source.Contains("&fmt_url_map=")) { source = System.Text.RegularExpressions.Regex.Split(source, "&fmt_url_map=")[1]; } if (source.Contains("\"fmt_url_map\": \"")) { source = System.Text.RegularExpressions.Regex.Split(source, "\"fmt_url_map\": \"")[1]; } } source = WebUtility.HtmlDecode(source).Replace("%2C", ",").Split(new string[] { "http:\\/\\/" }, StringSplitOptions.RemoveEmptyEntries).ElementAt(1); source = source.Insert(0, "http://").Replace("|", ""); source = source.Remove(source.LastIndexOf(","), source.Length - source.LastIndexOf(",")); if (Convert.ToString(source[source.Length - 1]) == "C") { source = source.Remove(source.Length - 1, 1); } if (source.Contains("rv.2.rating")) { int index = source.IndexOf("\","); source = source.Remove(index, source.Length - index); } source = source.Replace(@"\/", "/"); source = source.Replace("\\u0026", "&"); var request2 = (HttpWebRequest)WebRequest.Create(source); var response2 = (HttpWebResponse)request2.GetResponse(); if (response2.ContentType == "video/x-flv") { type = ".flv"; outputurl = source; size = (int)response2.ContentLength; } else if (response2.ContentType == "video/mp4") { type = ".mp4"; outputurl = source; size = (int)response2.ContentLength; } else { type = ""; outputurl = ""; } return outputurl; } } } <file_sep>/FirstFacebookApplication/classes/FacebookWorker.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using Facebook; using System.Windows.Forms; using System.Dynamic; using System.Collections; using System.Drawing; namespace FirstFacebookApplication { class FacebookWorker { private dynamic fb; private dynamic me; private string accessToken; private Security sec; private Panel facebookMainBoard; private Panel facebookGroundPanel; private Label facebookCommentsLabel; private PictureBox facebookBorderLine; private PictureBox facebookPictureBox; private Label facebookPostTime; private Label facebookUserName; private Label facebookLikesLabel; private Label countOfComments; private TextBox facebookMessageBox; private Label countOfLikes; private LinkLabel linkLabel1; private TextBox textBox2; public FacebookWorker(String _accessToken) { this.accessToken = _accessToken; this.fb = new FacebookClient(_accessToken); this.me = this.fb.Get("/me"); this.sec = new Security(this.me.id); } /// <summary> /// /// </summary> /// <returns></returns> public Panel getDataSetForDataGrid() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Stream)); Database db = new Database(); Hashtable friends = db.getFriends(); this.facebookMainBoard = new System.Windows.Forms.Panel(); this.facebookBorderLine = new System.Windows.Forms.PictureBox(); dynamic feedResult = fb.Get("/me/home"); var messages = feedResult.data; List<Panel> addPanel = new List<Panel>(); int drawingPointX = 3; int drawingPointY = 3; int addToPointY = 119; int i = 0; foreach (var message in messages) { dynamic whoIs = message.from; this.facebookGroundPanel = new Panel(); this.facebookLikesLabel = new Label(); this.countOfComments = new Label(); this.facebookCommentsLabel = new Label(); this.facebookPostTime = new Label(); this.facebookUserName = new Label(); this.countOfLikes = new Label(); this.facebookMessageBox = new TextBox(); this.linkLabel1 = new LinkLabel(); this.textBox2 = new TextBox(); // // facebookMainBoard // this.facebookMainBoard.AutoScroll = true; this.facebookMainBoard.Dock = DockStyle.Fill; this.facebookMainBoard.Location = new Point(3, 16); this.facebookMainBoard.Name = "facebookMainBoard"; this.facebookMainBoard.Size = new System.Drawing.Size(630, 392); this.facebookMainBoard.TabIndex = 0; // // facebookGroundPanel // this.facebookGroundPanel.Controls.Add(this.countOfLikes); this.facebookGroundPanel.Controls.Add(this.facebookLikesLabel); this.facebookGroundPanel.Controls.Add(this.countOfComments); this.facebookGroundPanel.Controls.Add(this.facebookCommentsLabel); this.facebookGroundPanel.Controls.Add(this.facebookBorderLine); this.facebookGroundPanel.Controls.Add(this.facebookPostTime); this.facebookGroundPanel.Controls.Add(this.facebookUserName); this.facebookGroundPanel.Location = new Point(drawingPointX, drawingPointY); this.facebookGroundPanel.Name = "facebookGroundPanel"+i; this.facebookGroundPanel.Size = new Size(624, 112); drawingPointY = addToPointY + drawingPointY; // // facebookLikesLabel // this.facebookLikesLabel.AutoSize = true; this.facebookLikesLabel.Location = new Point(161, 94); this.facebookLikesLabel.Name = "facebookLikesLabel" + i; this.facebookLikesLabel.Size = new Size(73, 13); this.facebookLikesLabel.TabIndex = 5; this.facebookLikesLabel.Text = "Anzahl Likes: "; // // countOfComments // this.countOfComments.AutoSize = true; this.countOfComments.Location = new Point(104, 94); this.countOfComments.Name = "countOfComments" + i; this.countOfComments.Size = new Size(35, 13); this.countOfComments.TabIndex = 4; this.countOfComments.Text = "0"; // // facebookCommentsLabel // this.facebookCommentsLabel.AutoSize = true; this.facebookCommentsLabel.Location = new Point(9, 94); this.facebookCommentsLabel.Name = "facebookCommentsLabel" + i; this.facebookCommentsLabel.Size = new Size(97, 13); this.facebookCommentsLabel.TabIndex = 3; this.facebookCommentsLabel.Text = "Anzahl Comments: "; // // facebookBorderLine // this.facebookBorderLine.Image = ((Image)(resources.GetObject("facebookBorderLine.Image"))); this.facebookBorderLine.Location = new Point(10, 85); this.facebookBorderLine.Name = "facebookBorderLine" + i; this.facebookBorderLine.Size = new Size(600, 4); this.facebookBorderLine.SizeMode = PictureBoxSizeMode.AutoSize; this.facebookBorderLine.TabIndex = 2; this.facebookBorderLine.TabStop = false; // // facebookPostTime // this.facebookPostTime.AutoSize = true; this.facebookPostTime.Location = new Point(7, 24); this.facebookPostTime.Name = "facebookPostTime" + i; this.facebookPostTime.Size = new Size(35, 13); this.facebookPostTime.TabIndex = 1; this.facebookPostTime.Text = ""; // // facebookUserName // this.facebookUserName.AutoSize = true; this.facebookUserName.Location = new Point(7, 7); this.facebookUserName.Name = "facebookUserName" + i; this.facebookUserName.Size = new Size(35, 13); this.facebookUserName.TabIndex = 0; this.facebookUserName.Text = whoIs.name; this.facebookUserName.UseWaitCursor = true; // // countOfLikes // this.countOfLikes.AutoSize = true; this.countOfLikes.Location = new Point(231, 94); this.countOfLikes.Name = "countOfLikes" + i; this.countOfLikes.Size = new Size(35, 13); this.countOfLikes.TabIndex = 6; this.countOfLikes.Text = "0"; // // facebookMessageBox // this.facebookMessageBox.BorderStyle = BorderStyle.None; this.facebookMessageBox.Enabled = false; this.facebookMessageBox.Location = new Point(136, 7); this.facebookMessageBox.Multiline = true; this.facebookMessageBox.Name = "facebookMessageBox" + i; this.facebookMessageBox.ReadOnly = true; this.facebookMessageBox.Size = new Size(474, 72); this.facebookMessageBox.TabIndex = 7; if(message.type.Equals("photo")) { this.facebookPictureBox = new PictureBox(); this.facebookPictureBox.Location = new Point(255, 7); this.facebookMessageBox.BorderStyle = BorderStyle.None; this.facebookPictureBox.ImageLocation = message.picture; this.facebookGroundPanel.Controls.Add(this.facebookPictureBox); this.linkLabel1.AutoSize = true; this.linkLabel1.Location = new Point(360, 84); this.linkLabel1.Name = "linkLabel1"+i; this.linkLabel1.Size = new Size(55, 13); this.linkLabel1.Text = message.link; //this.linkLabel1.Location = message.link; this.facebookGroundPanel.Controls.Add(this.linkLabel1); this.textBox2.Location = new Point(360, 3); this.textBox2.Multiline = true; this.textBox2.Name = "textBox2"; this.textBox2.Size = new Size(248, 78); this.textBox2.Text = message.message; this.textBox2.ReadOnly = true; this.facebookGroundPanel.Controls.Add(this.textBox2); } else if(message.type.Equals("video")) { this.facebookPictureBox = new PictureBox(); this.facebookPictureBox.Location = new Point(255, 7); this.facebookMessageBox.BorderStyle = BorderStyle.None; this.facebookPictureBox.ImageLocation = message.picture; this.facebookGroundPanel.Controls.Add(this.facebookPictureBox); this.linkLabel1.AutoSize = true; this.linkLabel1.Location = new Point(360, 84); this.linkLabel1.Name = "linkLabel1"+i; this.linkLabel1.Size = new Size(55, 13); this.linkLabel1.TabIndex = 2; this.linkLabel1.TabStop = true; this.linkLabel1.Text = message.link; //this.linkLabel1.Location = message.link; this.facebookGroundPanel.Controls.Add(this.linkLabel1); this.textBox2.Location = new Point(360, 3); this.textBox2.Multiline = true; this.textBox2.Name = "textBox2"+i; this.textBox2.Size = new Size(248, 78); this.textBox2.Text = message.message; this.textBox2.ReadOnly = true; this.facebookGroundPanel.Controls.Add(this.textBox2); } else if (message.type.Equals("link")) { this.facebookPictureBox = new PictureBox(); this.facebookPictureBox.Location = new Point(255, 7); this.facebookMessageBox.BorderStyle = BorderStyle.None; this.facebookPictureBox.ImageLocation = message.picture; this.facebookGroundPanel.Controls.Add(this.facebookPictureBox); this.linkLabel1.AutoSize = true; this.linkLabel1.Location = new Point(360, 84); this.linkLabel1.Name = "linkLabel1"+i; this.linkLabel1.Size = new Size(55, 13); this.linkLabel1.TabStop = true; this.linkLabel1.Text = message.link; //this.linkLabel1.Location = message.link; this.facebookGroundPanel.Controls.Add(this.linkLabel1); this.textBox2.Location = new Point(360, 3); this.textBox2.Multiline = true; this.textBox2.Name = "textBox2"+i; this.textBox2.Size = new Size(248, 78); this.textBox2.ReadOnly = true; this.textBox2.Text = message.message; this.facebookGroundPanel.Controls.Add(this.textBox2); } else { this.facebookGroundPanel.Controls.Add(this.facebookMessageBox); if (whoIs.id == this.me.id) { this.facebookMessageBox.Text += sec.decryptMessage(message.message, this.me.id); } else { if (friends.ContainsKey(whoIs.id) && !friends.ContainsKey(this.me.id)) { this.facebookMessageBox.Text += sec.decryptMessage(message.message, friends[whoIs.id]); } else { this.facebookMessageBox.Text += message.message; } } } var likes = message.likes; var comments = message.comments; bool hasLikeCount = (message as IDictionary<string, object>).ContainsKey("likes"); bool hasCommentCount = (message as IDictionary<string, object>).ContainsKey("comments"); if (hasLikeCount) { this.countOfLikes.Text = likes.count.ToString(); } if (hasCommentCount) { this.countOfComments.Text = comments.count.ToString(); } this.facebookMainBoard.Controls.Add(this.facebookGroundPanel); i++; } return this.facebookMainBoard; } public bool postToWall(string message) { var argList = new Dictionary<string,object>(); var privacy = new Dictionary<string,object>(); try { argList["application"] = "CSharp FacebookCrypter"; argList["message"] = this.sec.encryptMessage(message); fb.Post("me/feed", argList); } catch (FacebookOAuthException ex) { MessageBox.Show(ex.Message); } catch (FacebookApiException ex) { MessageBox.Show(ex.Message); } return true; } /// <summary> /// return the Full Facebookname /// </summary> /// <returns>String</returns> public String getFullName() { return this.me.name; } } }
3b3af4bd8ac3023e68387a7673e757be6de2e2b6
[ "C#" ]
4
C#
janlueders/FacebookCrypter-C-
4cb7ea047e697a614c0bea3edcd6b1b8e284bcc6
f7778efe6e23268e1ee5ef41e5780a83c3e31167
refs/heads/master
<repo_name>SMathenge/hello-world<file_sep>/README.md # hello-world third copy of the same thing
9ba73974497093040f8860f86db3729d3bd1078d
[ "Markdown" ]
1
Markdown
SMathenge/hello-world
8b4ac4d37fce18dfa3d3a4d6f979cc515703c2c3
3fedef6c0b39579a654758ae3e5064e2b339bf38
refs/heads/master
<repo_name>maximewetz/rails-mister-cocktail<file_sep>/app/views/doses/new.html.erb <h3>What's the doses for your <%= @cocktail.name %>?</h3> <%= simple_form_for [@cocktail, @dose] do |f| %> <%= f.input :description %> <%= f.association :ingredient, collection: @ingredients %> <%= f.submit "Add the doses", class: "btn btn-success" %> <% end %> <file_sep>/app/views/cocktails/show.html.erb <h1>Your cocktail: </h1> <h3><%= @cocktail.name %></h4> <h5> Your dose of ingredients: </h5> <ul> <% @cocktail.doses.each do |d| %> <li><%= d.ingredient.name %>: <%= d.description %></li> <% end %> </ul> <%= link_to "Cocktaiiils", cocktails_path, class: "btn btn-primary" %> <file_sep>/app/views/cocktails/new.html.erb <h1>Create your cocktail: </h1> <%= simple_form_for @cocktail do |f| %> <%= f.input :name %> <%= f.submit "Add your cocktail", class: "btn btn-success" %> <% end %> <%= link_to "Back", cocktails_path, class: "btn btn-primary" %>
29a0961e2ced066db7411912b8384d5baac994ef
[ "HTML+ERB" ]
3
HTML+ERB
maximewetz/rails-mister-cocktail
e43c6b64f1785e1cc450cc584c34dd708758238b
c2ab13cec6c28446d11d2221cff956c356061a03
refs/heads/master
<repo_name>graemechapman/inf-jqtest-calc<file_sep>/js/app.js // self executing main function (function($) { console.log('Welcome to the calculator app'); //--------------- put your code below this line ------------- })(jQuery);
66465d7472a3f83c2d849575ee495e1baf460cbd
[ "JavaScript" ]
1
JavaScript
graemechapman/inf-jqtest-calc
4ccaf56a5a988c6b49a60cd908d970a1508dd1ad
603ff9f1f3ad8f1825f799add136b1664c7de51e
refs/heads/master
<repo_name>slaven100/Program_MobilePLatform<file_sep>/MobileBase/main.c #include "stm32f4xx.h" #include <stdio.h> USART_InitTypeDef USART_InitStructure; GPIO_InitTypeDef GPIO_InitStructure; void USART_Configuration(unsigned int BaudRate); void SendUSART(USART_TypeDef* USARTx,uint16_t ch); int GetUSART(USART_TypeDef* USARTx); static void Delay(__IO uint32_t nTime); static __IO uint32_t TimingDelay; /* Private function prototypes -----------------------------------------------*/ #ifdef __GNUC__ /* With GCC/RAISONANCE, small printf (option LD Linker->Libraries->Small printf set to 'Yes') calls __io_putchar() */ #define PUTCHAR_PROTOTYPE int __io_putchar(int ch) #else #define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f) #define GETCHAR_PROTOTYPE int fgetc(FILE *f) #endif /* __GNUC__ */ void Delay(__IO uint32_t nTime){ TimingDelay = nTime; while(TimingDelay != 0); } void TimingDelay_Decrement(void){ if (TimingDelay != 0){ TimingDelay--; } } int main(void){ SysTick_Config(SystemCoreClock / 1000); USART_Configuration(115200); printf(" Test hello world\r"); while(1){ printf(" abc\r"); Delay(2000); } } void USART_Configuration(unsigned int BaudRate){ RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE); RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE); /* Configure USART Tx as alternate function */ GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_Init(GPIOB, &GPIO_InitStructure); /* Configure USART Rx as alternate function */ GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7; GPIO_Init(GPIOB, &GPIO_InitStructure); USART_InitStructure.USART_BaudRate = BaudRate; USART_InitStructure.USART_WordLength = USART_WordLength_8b; USART_InitStructure.USART_StopBits = USART_StopBits_1; USART_InitStructure.USART_Parity = USART_Parity_No; USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None; USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; USART_Init(USART1, &USART_InitStructure); GPIO_PinAFConfig(GPIOB,GPIO_PinSource6,GPIO_AF_USART1); GPIO_PinAFConfig(GPIOB,GPIO_PinSource7,GPIO_AF_USART1); USART_Cmd(USART1, ENABLE); } void SendUSART(USART_TypeDef* USARTx,uint16_t ch){ USART_SendData(USARTx, (uint8_t) ch); /* Loop until the end of transmission */ while (USART_GetFlagStatus(USARTx, USART_IT_TXE) == RESET) {} } int GetUSART(USART_TypeDef* USARTx){ while (USART_GetFlagStatus(USARTx, USART_IT_RXNE) == RESET) {} return USART_ReceiveData(USARTx); } /** * @brief Retargets the C library printf function to the USART. * @param None * @retval None */ GETCHAR_PROTOTYPE{ return GetUSART(USART1); } PUTCHAR_PROTOTYPE{ /* Place your implementation of fputc here */ /* e.g. write a character to the USART */ USART_SendData(USART1, (uint8_t) ch); /* Loop until the end of transmission */ while (USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET) {} return ch; } #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(uint8_t* file, uint32_t line) { /* User can add his own implementation to report the file name and line number, ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ /* Infinite loop */ while (1) { } } #endif
2ecd3ac5d67d708673606386e97f4c7960f19280
[ "C" ]
1
C
slaven100/Program_MobilePLatform
18565741dbb9c8b39b6513d2e684166796c38e32
4c3c10a7bf803c7edffff82ee11bda81cb3f1f8f
refs/heads/master
<repo_name>cconsidine/big-hack-website<file_sep>/README.md # Big Hack Website Big Hack website, live [here](http://bighack.org/). For a social good hackathon between Cal and Stanford, co-hosted by [Cal Hacks](http://www.calhacks.io/), [Tree Hacks](https://www.treehacks.com/), [CS + Social Good](http://www.cs4good.org/), and [Cal Blueprint](https://www.calblueprint.org/). Written in vanilla HTML, CSS, and JavaScript. # Credits **Developers:** * [<NAME>] (https://github.com/cconsidine) (Cal Hacks) * [<NAME>] (https://github.com/mikeyu152) (Tree Hacks) * [<NAME>](https://github.com/shashankredemption) (Cal Hacks) * [<NAME>] (vivekraghuram) (Blueprint) * <NAME> * <NAME> * <NAME> **Designers:** * [<NAME>] (https://github.com/kevintxwu) (Blueprint) * Zhi Pan * <NAME>
b42c95c7385667f4d98b03195c67f691ffa2a75c
[ "Markdown" ]
1
Markdown
cconsidine/big-hack-website
d95ac3c470e1fdcde25e78dc5fe748b090350f9c
4e74136146f24a7d9815fab9c0165d8be7bfe979
refs/heads/master
<file_sep># logicapython Repositório para alunos do curso de Algoritmo e Lógica de Programação.
99cfa587614efb0af20b4615506ac5b62a85411c
[ "Markdown" ]
1
Markdown
BrutalitTech/logicapython
756342a53f7e7ccfd05cee2a7ff4f355799a6957
9072f3457c6f69671bdf02597160c797cdc7184a
refs/heads/master
<file_sep>## 为什么需要权限管理 - 安全性:误操作、人为破坏、数据泄露等 - 数据隔离:不同的权限能看到及操作不同的数据 - 明确职责:运营、客服等不同角色,leader和dev等不同级别 ## 权限管理核心 - 用户-权限:人员少,功能固定,或者特别简单的系统 - RBAC(Role-Based Access Control):用户-角色-权限,都适用 ![](https://img2018.cnblogs.com/blog/1231979/201906/1231979-20190610090216179-1810988515.png) ## 理想中的权限管理 - 能实现角色级权限:RBAC - 能实现功能级、数据级权限 - 简单、易操作,能够应对各种需求 ## 相关操作界面 - 权限管理界面、角色管理界面、用户管理界面 - 角色和权限关系维护界面、用户和角色关系维护界面 ## Spring Security权限管理框架介绍 ![](https://img2018.cnblogs.com/blog/1231979/201906/1231979-20190610091232234-524751612.png) ## Spring Security常用权限拦截器 ![](https://img2018.cnblogs.com/blog/1231979/201906/1231979-20190610091849257-1031469268.png) ![](https://img2018.cnblogs.com/blog/1231979/201906/1231979-20190610092744533-346463947.png) ## Spring Security数据库管理 ![](https://img2018.cnblogs.com/blog/1231979/201906/1231979-20190610092815757-2028596813.png) ```java public interface UserDetailsService { UserDetails loadUserByUsername(String usegname) throws UsernameNotFoundException; } ``` ![](https://img2018.cnblogs.com/blog/1231979/201906/1231979-20190610092956959-645360581.png) ![](https://img2018.cnblogs.com/blog/1231979/201906/1231979-20190610093107810-1782649402.png) ## Spring Security权限缓存 - CachingUserDetailsService ## Spring Security优点 ``` 提供一套安全框架,而且这个框架是可用的 提供了很多用户认证的功能,实现相关接口即可,节约大量开发工作 基于spring,易于继承到spring项目中,且封装了很多方法 ``` ## Spring Security缺点 ``` 配置文件多,角色被“编码”到配置文件和源文件中,RBAC不明显 对于系统中用户、角色、权限之间的关系,没有可操作的界面 大数据量不可用 ``` ## Apache Shiro ### Shiro介绍 ![](https://img2018.cnblogs.com/blog/1231979/201906/1231979-20190610100614456-541894022.png) ### Shiro架构图 ![](https://img2018.cnblogs.com/blog/1231979/201906/1231979-20190610100755422-422685195.png) ## 环境搭建及使用 ![](https://img2018.cnblogs.com/blog/1231979/201906/1231979-20190610151630439-2026177505.png) ![](https://img2018.cnblogs.com/blog/1231979/201906/1231979-20190610160357116-1375100253.png) ![](https://img2018.cnblogs.com/blog/1231979/201906/1231979-20190610160910880-309566708.png) <file_sep>package com.legend.permission.service; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import com.legend.permission.dao.SysDeptMapper; import com.legend.permission.dto.DeptLevelDto; import com.legend.permission.model.SysDept; import com.legend.permission.util.LevelUtil; import org.apache.commons.collections.CollectionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * 计算树的结构 * * * 涉及递归算法的实现 */ @Service public class SysTreeService { @Autowired private SysDeptMapper sysDeptMapper; //部门树 public List<DeptLevelDto> deptTree(){ //取出最基本的数据 List<SysDept> deptList = sysDeptMapper.getAllDept(); //将数据封装 List<DeptLevelDto> dtoList = Lists.newArrayList(); for (SysDept dept:deptList) { DeptLevelDto dto = DeptLevelDto.adapt(dept); dtoList.add(dto); } return deptListToTree(dtoList); } //数据核心组装 public List<DeptLevelDto> deptListToTree(List<DeptLevelDto> deptLevelList){ //判断是否为空 if (CollectionUtils.isEmpty(deptLevelList)){ return Lists.newArrayList(); } //level-->[dept1,dept2,....] Multimap数据机构 Map<String,List<Object>> Multimap<String,DeptLevelDto> levelDeptMap = ArrayListMultimap.create(); List<DeptLevelDto> rootList = Lists.newArrayList(); for (DeptLevelDto dto: deptLevelList) { levelDeptMap.put(dto.getLevel(),dto); if (LevelUtil.ROOT.equals(dto.getLevel())){ rootList.add(dto); } } //按照seq从小到大排序 Collections.sort(rootList, new Comparator<DeptLevelDto>() { //自定义比较器 public int compare(DeptLevelDto o1, DeptLevelDto o2) { return o1.getSeq() - o2.getSeq(); } }); //递归生成树 transFormDeptTree(rootList,LevelUtil.ROOT,levelDeptMap); return rootList; } //处理当前层级下面所有的数据 public void transFormDeptTree(List<DeptLevelDto> deptLevelList,String level, Multimap<String,DeptLevelDto> levelDeptMap){ //读取root里面的元素 for (int i = 0; i < deptLevelList.size() ; i++) { //遍历该层元素 DeptLevelDto deptLevelDto = deptLevelList.get(i); //处理当前层级的数据 取出下一级使用的节点 String nextLevel = LevelUtil.calculateLevel(level,deptLevelDto.getId()); //处理下一层 List<DeptLevelDto> tempDeptList = (List<DeptLevelDto>) levelDeptMap.get(nextLevel); if (CollectionUtils.isNotEmpty(tempDeptList)){ //排序 Collections.sort(tempDeptList,deptSeqComparator); //设置下一层部门 deptLevelDto.setDeptList(tempDeptList); //进入下一层处理 transFormDeptTree(tempDeptList,nextLevel,levelDeptMap); } } } public Comparator<DeptLevelDto> deptSeqComparator = new Comparator<DeptLevelDto>() { public int compare(DeptLevelDto o1, DeptLevelDto o2) { //根据seq的比较器 return o1.getSeq() - o2.getSeq() ; } }; } <file_sep>package com.legend.permission.dao; import com.legend.permission.model.SysDept; import com.sun.tracing.dtrace.ProviderAttributes; import org.apache.ibatis.annotations.Param; import java.util.List; public interface SysDeptMapper { int deleteByPrimaryKey(Integer id); int insert(SysDept record); int insertSelective(SysDept record); SysDept selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(SysDept record); int updateByPrimaryKey(SysDept record); // int countByNameAndParentId(@Param("parentId") Integer parentId,@Param("name") String name,@Param("id") Integer id); //新增方法获取所有的部门 List<SysDept> getAllDept(); //获取自部门 List<SysDept> getChildDeptListByLevel(@Param("level") String level); //批量更新 void batchUpdateLevel(List<SysDept> sysDeptList); }
0aece524e2fd42f70ef0b6f0f73e3040c4135853
[ "Java", "Markdown" ]
3
Java
qichunlin/Permission
5e8f9309cbb5d8a6fdb6685a18caf662ed6c836f
484b69332276c1c365510668ce40306479899734
refs/heads/master
<file_sep>## ❔ Sobre o projeto Uma plataforma para facilitar o encontro de orfanatos por pessoas que querem visita-los. O projeto está em desenvolvimento na [Next Level Week 3](https://nextlevelweek.com/episodios/omnistack/1/edicao/3) ## 🛠 Techs <NAME> ## ⚙ Instalação e Start 1. YARN install ou NPM install 2. YARN start ou NPM start ## 📜 License O projeto está sobre a licença [MIT](./LICENSE)
84887c4b8f69a91f7c2498bd0a9f7900f6818bc7
[ "Markdown" ]
1
Markdown
phprograming/happy-web
9c32c1655f90f5c432321fe42b04d09912e85026
fe53b9ffe7aea40ae82dfc4e2f08432f2837d0c6
refs/heads/main
<repo_name>liaoyuesheng/events<file_sep>/src/index.ts type Listener = (...args:any[]) => void type Listeners = Listener[] interface EventsObject { [key: string]: Listeners } function checkListener(listener) { const listenerType = typeof listener if (listenerType !== 'function') { throw new TypeError(`The "listener" argument must be of type Function. Received type ${listenerType}`) } } export default class Events { private _events: EventsObject = {} public on(eventName: string, listener: Listener, prepend = false): Events { checkListener(listener) if (!this._events[eventName]) { this._events[eventName] = [] } const listeners = this._events[eventName] if (prepend) { listeners.unshift(listener) } else { listeners.push(listener) } return this } public off(eventName: string, listener?: Listener): Events { const listeners = this._events[eventName] if (!listeners) return this if (listener) { checkListener(listener) this._events[eventName] = listeners.filter((currentListener) => { return currentListener !== listener }) } else { this._events[eventName] = [] } return this } public once(eventName: string, listener: Listener, prepend = false): Events { checkListener(listener) const proxyListener = (...args) => { this.off(eventName, proxyListener) listener.apply(this, args) } return this.on(eventName, proxyListener, prepend) } public emit(eventName: string, ...args: any[]): boolean { const listeners = this._events[eventName] if (!listeners || !listeners.length) { return false } listeners.forEach((listener) => { listener.apply(this, args) }) return true } } <file_sep>/README.md # @liaoys/events An event emitter. See [example](https://liaoyuesheng.github.io/events/) ## Installation ``` npm install @liaoys/events ``` ## Usage ```javascript import Events from "@liaoys/events" const event = new Events() // Add event listener event.on('foo', (param) => { console.log(`foo triggered! parameter is '${param}'`) }) // Add an event listener, and it will be invoked only once event.once('foo', () => { console.log('foo emitted!') }) // trigger event event.emit('foo', 'Hi!') ``` ## type: Listener (...args: any[]) => void; A callback function, accept some parameters from emit method of instance. ## Instance methods ### on(eventName: string, listener: Listener, prepend?: boolean): Events - `eventName` The name of the event - `listener` The callback function - `prepend` Add the listener to the beginning of the listeners array. default: false Add event listener. ### off(eventName: string, listener?: Listener): Events - `eventName` The name of the event - `listener` The callback function Remove the specified `listener` from the listeners array for the event named `eventName`. If without the parameter `listener`, will remove all the listeners from the listeners array for the event named `eventName`. ### once(eventName: string, listener: Listener, prepend?: boolean): Events - `eventName` The name of the event - `listener` The callback function - `prepend` Add the listener to the beginning of the listeners array. default: false Add an event listener, and it will be invoked only once. ### emit(eventName, ...args: any[]): boolean - `eventName` The name of the event - `args` Parameters passed to listener. Trigger the event named `eventName`. Returns `true` if the event had listeners, `false` otherwise. <file_sep>/dist/index.d.ts declare type Listener = (...args: any[]) => void; export default class Events { private _events; on(eventName: string, listener: Listener, prepend?: boolean): Events; off(eventName: string, listener?: Listener): Events; once(eventName: string, listener: Listener, prepend?: boolean): Events; emit(eventName: string, ...args: any[]): boolean; } export {};
80471f8f7ed1fb72a818be60872cf47b22744f43
[ "Markdown", "TypeScript" ]
3
Markdown
liaoyuesheng/events
0063d943621753059e3f257052f005e0769e8ae9
9fb0c3b8e5fd4cd5911140ce067cb94f388ba0b9
refs/heads/master
<repo_name>paperspoon/kor-simple-tax-table<file_sep>/index.js 'use strict'; const 간이세액표 = { get소득세: require('./src/kor-simple-tax-table'), get일용직소득세: require('./src/kor-daily-salary-tax'), } module.exports = { 간이세액표 }<file_sep>/README.md ## 대한민국 근로소득 간이세액표<file_sep>/src/kor-simple-tax-table.js 'use strict'; /** * http://www.nts.go.kr/cal/cal_06.asp 참조 */ function get소득세({ 과세지급액, 부양가족수, 지급일 }) { // 기본 1천원 단위 const smallSalary = 과세지급액 / 1000; // 기준일 const baseDateList = [ {year: '2018', startAt: new Date(2018, 1, 13)}, {year: '2017', startAt: new Date(2017, 1, 13)} ]; let baseDate = baseDateList.find(o => o.startAt - 지급일 < 0); if (baseDate === undefined) { console.warn(`2017년 2월 이전 데이터는 2017년 기준으로 계산합니다.`); baseDate = baseDateList[1]; } const table = require(`./table-${baseDate.year}.json`); // 세금을 계산할 필요가 없는 최소금액의 경우 if (smallSalary < table[0].o) { return 0; } // 천만원을 초과하는 경우 별도 계산, 억대연봉자 부럽 if (smallSalary > 10000) { const defaultTax = table[table.length -1].t[부양가족수 -1]; return baseDate.year === 2018 ? overTax2018({과세지급액, defaultTax}) : overTax2017({과세지급액, defaultTax}); } const row = table.find(o => o.o >= smallSalary); return row.t.length < 부양가족수 ? 0 : row.t[부양가족수 - 1]; } function overTax2018({과세지급액, defaultTax}) { let tax = 0; tax += defaultTax; if (과세지급액 <= 14000000) { tax += (과세지급액 - 10000000) * 0.98 * 0.35; } else if (salary <= 28000000) { tax += 1372000 +(과세지급액 - 14000000) * 0.98 * 0.38; } else if (salary <= 45000000) { tax += 6585600 + (과세지급액 - 28000000) * 0.98 * 0.40; } else { tax += 13249600 + (과세지급액 - 45000000) * 0.98 * 0.42; } return Math.floor(tax * 0.1) * 10; } function overTax2017({과세지급액, defaultTax}) { let tax = 0; tax += defaultTax; if (과세지급액 <= 14000000) { tax += Math.floor((과세지급액 - 10000000) * 0.98 * 0.35); } else if (과세지급액 <= 45000000) { tax += 1372000 + Math.floor((과세지급액 - 14000000) * 0.98 * 0.38); } else { tax += 12916400 + Math.floor((과세지급액 - 45000000) * 0.98 * 0.40); } return Math.floor(tax * 0.1) * 10; } module.exports = get소득세;<file_sep>/test/kor-daily-salary-tax.js 'use strict'; var expect = require('chai').expect; var simpleTax = require('../index'); describe('일용직 소득세 테스트', function(){ const param = { 총지급액: 150000, 근로일수: 1 } const expected = 1350; const actual = simpleTax.간이세액표.get일용직소득세(param); it(`일용직 총급지급액 ${param.총지급액}원에 근로일수가 총 ${param.근로일수}일이면 소득세는 ${actual}원 입니다.`, function(){ expect(actual).to.equal(expected); }); }) <file_sep>/src/kor-daily-salary-tax.js 'use strict'; /** * https://txsi.hometax.go.kr/docs/customer/comment/comment_jomun_main_internet.jsp?node_id=null&lawid=001565&jomunkey=0059005&lawnm=&jomun_nm=%EC%A0%9C59%EC%A1%B0%E3%80%90(%EA%B7%BC%EB%A1%9C%EC%86%8C%EB%93%9D%EC%84%B8%EC%95%A1%EA%B3%B5%EC%A0%9C)%E3%80%91&public_ilja=20171219&public_no=15225 참조 */ function get일용직소득세({ 총지급액, 근로일수 }) { const 일당 = 총지급액 / 근로일수; // 10만 미만의 경우 소득세 없음 if (일당 <= 100000) return 0; const 과세금액 = 총지급액 - (100000 * 근로일수); const 소득세 = Math.floor(과세금액 * 0.06 * 0.45); return 소득세; } module.exports = get일용직소득세;<file_sep>/index.d.ts export class 소득세Parameter { 과세지급액: number; 부양가족수: number; 지급일: Date; } export class 일용직소득세Parameter { 총지급액: number; 근로일수: number; } export namespace 간이세액표 { export function get소득세(param: 소득세Parameter): number; export function get일용직소득세(param: 일용직소득세Parameter): number; }
f5036139c234988d80db2182415bdba5382a8db3
[ "Markdown", "TypeScript", "JavaScript" ]
6
Markdown
paperspoon/kor-simple-tax-table
3d2783a02586ba34b9b88174723a243619146e0a
952259a3d477f8bd79754aad67111da5589d3f93
refs/heads/master
<file_sep># 2020MintaEmeltHalozat 2020-as minta emelt hálózat Feladatlap: https://www.nive.hu/Downloads/vizsga/agazati_szobeli_irasbeli_mintafeladatok_2020/DL.php?f=Informatikai_ismeretek_emelt_gyakorlati.pdf
6f70599b2f412e41250ac15e47c626359c8fd9ea
[ "Markdown" ]
1
Markdown
grandmastar27/2020MintaErettsegiEmeltHalozat
3025deda7fd18c93a3404b967711dea36e5e7a1c
48e95eac044e4c664928d88f72f2e957e01b041b
refs/heads/master
<file_sep># invie-app Remote repo invie example Test update readme
da1177ea9cb9631837b438d0596a366a2e0622c6
[ "Markdown" ]
1
Markdown
juaneins/invie-app
b8c6a7a2c4b2b1bc60b35eeae91c56a8f593a87c
107f6b05721e39079ae041c818190c478453a406
refs/heads/main
<repo_name>ken0901/Springboot-JPA-Blog<file_sep>/README.md # Springboot-JPA-Blog ## Functions * Create boards(user,comment,board) <br> * Update, Delete boards <br> * See content details <br> * Paging - Page changes according to the number of media <br> * Sign in, Sign up , Sign out - Spring Security <br> * Update user info, session value also updates * Sign up using OAuth with Kakao * Show comment list, add comment * Delete comment(only writer) * DI multiple ways * How to use native query in JPA * How to use DTO ## Skills * Front - JSP,JSTL, HTML, CSS, Javascript(ajax), Bootstrap <br> * Back - Java 1.8 with Spring boot, Spring data JPA, Spring Security, ORM, Hibernate <br> * DB - MYSQL * IDE - IntelliJ, VS code, MySQL Workbench ## Ref * https://www.youtube.com/playlist?list=PL93mKxaRDidECgjOBjPgI3Dyo8ka6Ilqm <file_sep>/src/main/resources/static/js/user.js let index = { init:function(){ // let _this = this; // if you want to use function uncomment this $("#btn-save").on("click",()=>{ // function(){}, ()=>{} for binding this keyword this.save(); }); $("#btn-update").on("click",()=>{ // function(){}, ()=>{} for binding this keyword this.update(); }); // $("#btn-login").on("click",()=>{ // function(){}, ()=>{} for binding this keyword // this.login(); // }); }, save: function(){ // alert('user function execute'); let data = { username: $("#username").val(), password: <PASSWORD>").val(), email: $("#email").val() }; // console.log(data); //call ajax, default is Asynchronous call // ajax communication , send 3 data with json format and request insert // ajax communication success, server returns json type , auto convert to java object $.ajax({ type: "POST", url: "/auth/joinProc", data: JSON.stringify(data), //http body data contentType: "application/json; charset=utf-8", // what kind of body data type(MIME) dataType: "json" // get request from the server, basically it's all string type(look like json) => convert to javascript object }).done(function(res){ if(res.status === 500){ alert("Failed sign up"); }else{ alert("Sign up completed"); location.href="/"; } }).fail(function(error){ alert(JSON.stringify(error)); }); }, update: function(){ let data = { id : $("#id").val(), username: $("#username").val(), password: <PASSWORD>").val(), email: $("#email").val() }; $.ajax({ type: "PUT", url: "/user", data: JSON.stringify(data), //http body data contentType: "application/json; charset=utf-8", // what kind of body data type(MIME) dataType: "json" // get request from the server, basically it's all string type(look like json) => convert to javascript object }).done(function(res){ alert("Updating complete"); location.href="/"; }).fail(function(error){ alert(JSON.stringify(error)); }); }, // old log in way without using spring security /*login: function(){ // alert('user function execute'); let data = { username: $("#username").val(), password: <PASSWORD>(), }; $.ajax({ type: "POST", url: "/blog/api/user/login", data: JSON.stringify(data), //http body data contentType: "application/json; charset=utf-8", // what kind of body data type(MIME) dataType: "json" // get request from the server, basically it's all string type(look like json) => convert to javascript object }).done(function(res){ //console.log(res); alert("Sign in completed"); location.href="/blog"; }).fail(function(error){ alert(JSON.stringify(error)); }); }*/ } index.init();<file_sep>/src/test/java/com/ken/blog/test/ReplyObjectTest.java package com.ken.blog.test; import com.ken.blog.model.Reply; import org.junit.jupiter.api.Test; public class ReplyObjectTest { @Test public void toStringTest(){ Reply reply = Reply.builder() .id(1) .user(null) .board(null) .content("hi") .build(); System.out.println(reply); } } <file_sep>/src/main/java/com/ken/blog/service/UserService.java package com.ken.blog.service; import com.ken.blog.model.RoleType; import com.ken.blog.model.User; import com.ken.blog.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; // Register bean to IOC through Spring component scan @Service public class UserService { @Autowired private UserRepository userRepository; @Autowired private BCryptPasswordEncoder encode; @Transactional(readOnly = true) public User findUser(String username) { User user = userRepository.findByUsername(username).orElseGet(()->{ return new User(); }); return user; } @Transactional public void signIn(User user) { String rawPassword = user.getPassword(); //1234 original String encPassword = encode.encode(rawPassword); // hash user.setPassword(encPassword); user.setRole(RoleType.USER); userRepository.save(user); } @Transactional public void update(User user) { // when it's updating, persist User object from persistence context and then update persisted User object // Bring User object (using select query ) from the DB because of the persistence // Updating persisted Object is auto-sending update query to DB User persistence = userRepository.findById(user.getId()).orElseThrow(() -> { return new IllegalArgumentException("No found user"); }); // Validate check -> enable updating when oauth field is empty ( already user) if(persistence.getOauth()==null || persistence.getOauth().equals("")){ String rawPassword = user.getPassword(); String encPassword = encode.encode(rawPassword); persistence.setPassword(encPassword); persistence.setEmail(user.getEmail()); } // updating user ends = service ends = transaction ends = auto commit // persistence object is changed, dirty checking starts (sending update query) } /*@Transactional(readOnly = true) // when it's selected transaction starts, service ends transaction also ends public User login(User user){ return userRepository.findByUsernameAndPassword(user.getUsername(),user.getPassword()); }*/ } <file_sep>/src/main/java/com/ken/blog/controller/UserController.java package com.ken.blog.controller; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.ken.blog.model.KakaoProfile; import com.ken.blog.model.OAuthToken; import com.ken.blog.model.User; import com.ken.blog.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.client.RestTemplate; // no log in users path - /auth/** enable // address is / - index.jsp enable // under static folder - /js/** , /css/** , /image/** @Controller public class UserController { @Value("${ken.key}") private String kenKey; @Autowired UserService userService; @Autowired private AuthenticationManager authenticationManager; @GetMapping("/auth/joinForm") public String joinForm() { return "user/joinForm"; } @GetMapping("/auth/loginForm") public String loginForm() { return "user/loginForm"; } @GetMapping("/user/updateForm") public String updateForm() { return "user/updateForm"; } @GetMapping("/auth/kakao/callback") public String kakaoCallback(String code) { // return data controller method // key=value (POST) data request to Kakao // HttpsURLConnection url new HttpsURLConnection(); // Retrofit2 // OkHttp // RestTemplate RestTemplate rt = new RestTemplate(); // Create HttpHeader object HttpHeaders headers = new HttpHeaders(); headers.add("Content-type", "application/x-www-form-urlencoded;charset=utf-8"); // Create Httpbody object MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); params.add("grant_type", "authorization_code"); params.add("client_id", "c434c3fc8ab1d6a968f0b4810f67bd62"); params.add("redirect_uri", "http://localhost:8000/auth/kakao/callback"); params.add("code", code); // Store HttpHeader and HttpBody in one object HttpEntity<MultiValueMap<String, String>> kakaoTokenRequest = new HttpEntity<>(params, headers); // Http request - POST method - receive response's value answer ResponseEntity<String> response = rt.exchange( "https://kauth.kakao.com/oauth/token", HttpMethod.POST, kakaoTokenRequest, String.class ); //Gson, Json Simple, ObjectMapper ObjectMapper objectMapper = new ObjectMapper(); OAuthToken oAuthToken = null; try { oAuthToken = objectMapper.readValue(response.getBody(), OAuthToken.class); } catch (JsonMappingException e) { e.printStackTrace(); } catch (JsonProcessingException e) { e.printStackTrace(); } System.out.println("kakao access token" + oAuthToken.getAccess_token()); RestTemplate rt2 = new RestTemplate(); // Create HttpHeader object HttpHeaders headers2 = new HttpHeaders(); headers2.add("Authorization", "Bearer " + oAuthToken.getAccess_token()); headers2.add("Content-type", "application/x-www-form-urlencoded;charset=utf-8"); // Store HttpHeader and HttpBody in one object HttpEntity<MultiValueMap<String, String>> kakaoProfileRequest2 = new HttpEntity<>(headers2); // Http request - POST method - receive response's value answer ResponseEntity<String> response2 = rt2.exchange( "https://kapi.kakao.com/v2/user/me", HttpMethod.POST, kakaoProfileRequest2, String.class ); ObjectMapper objectMapper2 = new ObjectMapper(); KakaoProfile kakaoProfile = null; try { kakaoProfile = objectMapper2.readValue(response2.getBody(), KakaoProfile.class); } catch (JsonMappingException e) { e.printStackTrace(); } catch (JsonProcessingException e) { e.printStackTrace(); } // User Object : username, password, email System.out.println("kakao id: " + kakaoProfile.getId()); System.out.println("kakao email: " + kakaoProfile.getKakao_account().getEmail()); System.out.println("blog server username: " + kakaoProfile.getKakao_account().getEmail() + "_" + kakaoProfile.getId()); System.out.println("blog server email" + kakaoProfile.getKakao_account().getEmail()); // UUID - not duplicated number System.out.println("blog server password: " + kenKey); User kakaoUser = User.builder() .username(kakaoProfile.getKakao_account().getEmail() + "_" + kakaoProfile.getId()) .password(<PASSWORD>) .email(kakaoProfile.getKakao_account().getEmail()) .oauth("kakao") .build(); // check already user or non-user User originUser = userService.findUser(kakaoUser.getUsername()); if (originUser.getUsername() == null) { System.out.println("You are not user! it will be auto signed up"); userService.signIn(kakaoUser); } // log in logic Authentication authentication = authenticationManager.authenticate( new UsernamePasswordAuthenticationToken(kakaoUser.getUsername(), kenKey)); SecurityContextHolder.getContext().setAuthentication(authentication); return "redirect:/"; } } <file_sep>/src/main/java/com/ken/blog/controller/api/BoardApiController.java package com.ken.blog.controller.api; import com.ken.blog.config.auth.PrincipalDetail; import com.ken.blog.dto.ReplySaveRequestDto; import com.ken.blog.dto.ResponseDto; import com.ken.blog.model.Board; import com.ken.blog.service.BoardService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.web.bind.annotation.*; @RestController public class BoardApiController { @Autowired private BoardService boardService; @PostMapping("/api/board") public ResponseDto<Integer> save(@RequestBody Board board, @AuthenticationPrincipal PrincipalDetail principalDetail) { boardService.writing(board, principalDetail.getUser()); return new ResponseDto<Integer>(HttpStatus.OK.value(), 1); } @DeleteMapping("/api/board/{id}") public ResponseDto<Integer> deleteById(@PathVariable int id) { boardService.delete(id); return new ResponseDto<Integer>(HttpStatus.OK.value(), 1); } @PutMapping("/api/board/{id}") public ResponseDto<Integer> update(@PathVariable int id, @RequestBody Board board) { boardService.updateOfContent(id, board); return new ResponseDto<Integer>(HttpStatus.OK.value(), 1); } // receive data in controller, creating dto layer is better for the program // doesn't use dto layer because it's small project @PostMapping("/api/board/{boardId}/reply") // @PathVariable int boardId, @RequestBody Reply reply, @AuthenticationPrincipal PrincipalDetail principalDetail public ResponseDto<Integer> replySave(@RequestBody ReplySaveRequestDto replySaveRequestDto) { boardService.comment(replySaveRequestDto); return new ResponseDto<Integer>(HttpStatus.OK.value(), 1); } @DeleteMapping("/api/board/{boardId}/reply/{replyId}") public ResponseDto<Integer> replyDelete(@PathVariable int replyId) { System.out.println("reply Delete execute"); boardService.DeleteComment(replyId); return new ResponseDto<Integer>(HttpStatus.OK.value(), 1); } } <file_sep>/src/main/java/com/ken/blog/config/auth/PrincipalDetail.java package com.ken.blog.config.auth; import com.ken.blog.model.User; import lombok.Getter; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import java.util.ArrayList; import java.util.Collection; // Spring security intercepts login logic and it's success // UserDetails type object will be stored in spring security primary session storage @Getter public class PrincipalDetail implements UserDetails { private User user; public PrincipalDetail(User user) { this.user = user; } @Override public String getPassword() { return user.getPassword(); } @Override public String getUsername() { return user.getUsername(); } //check account is expired or not (true: not expire) @Override public boolean isAccountNonExpired() { return true; } // check account is locked or not (true: not lock) @Override public boolean isAccountNonLocked() { return true; } // check password is expired or not (true: not expire) @Override public boolean isCredentialsNonExpired() { return true; } // check account is enable or not (true:enable) @Override public boolean isEnabled() { return true; } // check account's authority (authority could be multiple loops but here's one role) @Override public Collection<? extends GrantedAuthority> getAuthorities() { Collection<GrantedAuthority> collectors = new ArrayList<>(); /* collectors.add(new GrantedAuthority() { @Override public String getAuthority() { return "ROLE_"+user.getRole(); // ROLE_USER } }); */ // lambda collectors.add(() -> { return "ROLE_" + user.getRole(); // ROLE_USER }); return collectors; } } <file_sep>/src/main/java/com/ken/blog/test/DummyControllerTest.java package com.ken.blog.test; import com.ken.blog.model.RoleType; import com.ken.blog.model.User; import com.ken.blog.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.web.PageableDefault; import org.springframework.web.bind.annotation.*; import javax.transaction.Transactional; import java.util.List; import java.util.function.Supplier; // return data NOT HTML file @RestController public class DummyControllerTest { @Autowired // DI private UserRepository userRepository; @DeleteMapping("/dummy/user/{id}") public String deleteUser(@PathVariable int id){ try{ userRepository.deleteById(id); } catch (EmptyResultDataAccessException ie){ return "Deleting failed, id doesn't found"; } return "Deleting completed id: "+id; } // save function - there's no id , only insert data // save function - there's id,data exists then update data // save function - there's id, data no exist then insert // email, password @Transactional // function ends, auto commit @PutMapping("/dummy/user/{id}") public User updateUser(@PathVariable int id, @RequestBody User requestUser){ // Json data request => Java object(Convert data from MessageConverter's Jackson library ) System.out.println("id: "+id); System.out.println("email: "+requestUser.getEmail()); System.out.println("password: "+requestUser.getPassword()); User user = userRepository.findById(id).orElseThrow(()->{ return new IllegalArgumentException("Updating Failed"); }); //dirty checking , persistence user.setPassword(requestUser.getPassword()); user.setEmail(requestUser.getEmail()); // userRepository.save(user); return user; } // http://localhost:8000/blog/dummy/users @GetMapping("/dummy/users") public List<User> list(){ return userRepository.findAll(); } // 2 data in 1 page // paging @GetMapping("/dummy/user") public List<User> pageList(@PageableDefault(size = 2,sort = "id",direction = Sort.Direction.DESC)Pageable pageable){ Page<User> pagingUser = userRepository.findAll(pageable); List<User> users = pagingUser.getContent(); return users; } // {id} address with parameter // http://localhost:8000/blog/dummy/user/4 @GetMapping("/dummy/user/{id}") public User detail(@PathVariable int id){ // Ex) user/4 if id is 4 , find 4 in DB but 4 isn't found // then it will be null // Using Optional to solve this problem User user = userRepository.findById(id).orElseThrow(new Supplier<IllegalArgumentException>() { @Override public IllegalArgumentException get() { return new IllegalArgumentException("There's no user id: "+id); } }); // lambda // User user = userRepository.findById(id).orElseThrow(()->{ // return new IllegalArgumentException("There's no user id: "+id); // }); // request : web browser // user object = java object // convert ( understandable data for web browser) -> Json (Gson library) // Springboot = MessageConverter is auto executed when it's request // if java object is returned, MessageConverter calls Jackson library // to convert User object to browser return user; } // http://localhost:8000/blog/dummy/join (request) // Request with username,password,email in body of http @PostMapping("/dummy/join") public String join(User user){ System.out.println("id: "+user.getId()); System.out.println("username: "+user.getUsername()); System.out.println("password: "+user.getPassword()); System.out.println("email: "+user.getEmail()); System.out.println("role: "+user.getRole()); System.out.println("createDate: "+user.getCreateDate()); user.setRole(RoleType.USER); userRepository.save(user); return "Sign in Complete"; } } <file_sep>/src/main/java/com/ken/blog/model/User.java package com.ken.blog.model; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import org.hibernate.annotations.CreationTimestamp; import java.sql.Timestamp; import javax.persistence.*; @Data @NoArgsConstructor @AllArgsConstructor @Builder // ORM -> object mapping to table @Entity // User Class is stored in database //@DynamicInsert // when it's insert null field data can be removed public class User { @Id //Primary Key @GeneratedValue(strategy = GenerationType.IDENTITY) // follow db numbering which is connected a project private int id; //sequence, auto-increment @Column(nullable = false, length = 100, unique = true) private String username; // id @Column(nullable = false, length = 100) //length is 100 because implement encrypt with hashing private String password; @Column(nullable = false, length = 50) private String email; // DB has only RoleType // @ColumnDefault("'user'") // Enum is more accuracy @Enumerated(EnumType.STRING) private RoleType role; //ADMIN, USER private String oauth; // kakao, google // manually insert - Timestamp.valueOf(LocalDateTime.now()) @CreationTimestamp // auto insert time private Timestamp createDate; } <file_sep>/target/maven-archiver/pom.properties artifactId=firstblog groupId=org.example version=1.0-SNAPSHOT <file_sep>/src/main/java/com/ken/blog/model/RoleType.java package com.ken.blog.model; public enum RoleType { USER,ADMIN }
8f3cdff508940d3fc591e704430ea067b70bbe3d
[ "Java", "Markdown", "JavaScript", "INI" ]
11
Java
ken0901/Springboot-JPA-Blog
79601e72f3135f5fae852827dfb2f6cfd23660df
6f62aede1a267f2d6d279e882a819e769c258e8b
refs/heads/master
<repo_name>taojiawen/taojiawen.github.io<file_sep>/linux/vi.md # Linux中常用的文本编辑器 ## vi编辑器 ## vim编辑器 vi编辑器的增强版本,习惯上也称为vi ### 三种模式 - 命令模式-----一般模式 - 插入模式 - 末行模式-----底行模式 ### 插入命令 - i 在光标前插入 - I 在光标当前行开始插入 - a 在光标后插入 - A 在光标当前行末尾插入 - o 在光标当前行的下一行插入新行 - O 在光标当前行的上一行插入新行 ### 定位命令 - :set nu 显示行号 - :set nonu 取消行号 - gg 到文本的第一行 - G 到文本的最后一行 - :n 到文本的第n行 ### 删除命令 - dd:删除当前行 - ndd:删除光标所在当前行向下数n行 - D:删除当前行光标所在的位置后面的字符 - x:向后删除光标所在位置的字符 - X:向前删除光标前面的字符 - nX:删除前面的n个字符,光标所在的字符将不会被删 ### 复制和粘贴命令 - yy或Y:复制当前行 - nyy或nY:复制以下n行 - p:在光标后面插入buffer中的内容 - P:在光标前面插入buffer中的内容 ### 替换和撤销命令 - r:取代光标所在处的字符 - R:从光标所在处开始替换字符,按esc结束 - u:撤销上一步操作 ### 定位命令 - h:左移一个字符 - l:右移一个字符 - j:下移一行 - k:上移一行 - $:移至行尾 - 0:移至行首 - gg:移到第一行 - G:移到最后一行 - nG:移到第n行 ### 查找操作 - :set nu 设置行号 - :set nonu 取消行号 - :n 移到第n行 - :/查找的关键字 ### 替换操作 - :s /old/new 将当前行中查找到的第一个字符“old” 串替换为“new” - :s /old/new/g 将当前行中查找到的所有字符串“old” 替换为“new” - :#,# s/old/new/g 在行号“#,#”范围内替换所有的字符串“old”为“new” - :% s/old/new/g 在整个文件范围内替换所有的字符串“old”为“new” - :%s/old/new 查找文件中所有行第一次出现的old,替换为new ### 其他命令 - :W[文件路径]保存当前文件 - :q 如果未对文件做改动则退出 - :q! 放弃存储名退出 - :wq或:x 保存退出 ### 可视模式 - v:可视模式 - V:可视行模式 - Ctrl+v:可视块模式 - 注意 在所有可视模式中,d和x键可以用删除选定的内容 在可视块模式中,选中所需行,按I键输入内容,之后按两次esc键,可在所有选定行光标处添加同样的内容。 <file_sep>/linux/chown.md # 文件及目录权限管理 ## 权限 读(r):读取文件的内容;列出目录里的对象 写(w):允许修改文件;在目录里面新建或者删除文件 执行(x):允许执行文件;允许进入目录里 ### 数字权限 读:4 写:2 执行:1 ## chmod命令 格式 chmod [ugoa] [+-=] [rwx] file/dir 或 chmod nnn file/dir 参数解释 u:属主 g:属组 o:其他用户 a:所有用户 +:添加权限 -:删除权限 =:赋予权限 nnn:三位八进制的权限 常用命令选项 -R 递归修改指定目录下的所有子文件及文件夹的权限 -f 强制改变文件访问特权;如果是文件的拥有者,则得 不到任何错误信息 ## chown命令 格式 chown 属主 file/dir chown :属组 file/dir chown 属主:属组 file/dir 常用命令选项 -R:递归的修改指定目录下所有文件、子目录的归属<file_sep>/hive/hive0.md # Hive简介 Hive是基于Hadoop的一个数据仓库工具(离线),可以将结构化的数据文件 映射为一张数据库表,并提供类SQL查询功能。 ## 为什么使用Hive 直接使用hadoop所面临的问题 人员学习成本太高 项目周期要求太短 MapReduce实现复杂查询逻辑开发难度太大 操作接口采用类SQL语法,提供快速开发的能力。 避免了去写MapReduce,减少开发人员的学习成本。 功能扩展很方便。 # Hive的特点 可扩展 Hive可以自由的扩展集群的规模,一般情况下不需要重启服务。 延展性 Hive支持用户自定义函数,用户可以根据自己的需求来实现自己的函数。 容错 良好的容错性,节点出现问题SQL仍可完成执行。 ![图片112.png](https://upload-images.jianshu.io/upload_images/14465950-631b453e7c335eec.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) # hive安装 标准安装:将mysql作为元数据库 安装MySQL sudo yum -y install wget wget http://repo.mysql.com/mysql-community-release-el7-5.noarch.rpm sudo rpm -ivh mysql-community-release-el7-5.noarch.rpm sudo yum -y install mysql-server sudo yum -y install mysql systemctl start mysqld mysql -u root -p(没密码) 修改密码:需root登录 初始没有密码 UPDATE mysql.user SET authentication_string=PASSWORD('<PASSWORD>') where USER='root'; MySQL> UPDATE mysql.user SET Password=PASSWORD('新密码') where USER='root’; MySQL> flush privileges; MySQL> exit 设置远程访问数据库: 登录后输入: mysql>GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'youmysqlpassword' WITH GRANT OPTION; mysql>FLUSH PRIVILEGES 如果忘记密码: 用命令编辑/etc/my.cnf配置文件,即:vim /etc/my.cnf 或者 vi /etc/my.cnf service mysqld restart 上传一个mysql的驱动jar包到hive的安装目录的lib中 mysql-connector-java-5.1.34 放到~/hive/lib /etc/profile 配置HIVE_HOME touch ~/hive/conf/hive-site.xml 连接MySQ配置 插入如下 密码为<PASSWORD> <configuration> <property> <name>javax.jdo.option.ConnectionURL</name> <value>jdbc:mysql://127.0.0.1:3306/hivedb?createDatabaseIfNotExist=true</value> </property> <property> <name>javax.jdo.option.ConnectionDriverName</name> <value>com.mysql.jdbc.Driver</value> </property> <property> <name>javax.jdo.option.ConnectionUserName</name> <value>hadoop</value> <property> <name>javax.jdo.option.ConnectionPassword</name> <value>hadoop</value> </property> </configuration> hadoop-2.7.3/etc/hadoop/yarn-site.xml 插入如下 ip为hive所在节点 <property> <name>yarn.resourcemanager.address</name> <value>172.18.24.195:8032</value> </property> <property> <name>yarn.resourcemanager.scheduler.address</name> <value>172.18.24.195:8030</value> </property> <property> <name>yarn.resourcemanager.resource-tracker.address</name> <value>172.18.24.195:8031</value> </property> <file_sep>/hadoop/mapreduce4.md ## MapReduce与Yarn * yarn负责资源的调度:用户程序向yarn 申请资源,yarn负责分配资源 * 主管角色:resourceManager 提供具体运算:nodeManager ![image.png](https://upload-images.jianshu.io/upload_images/14466577-b12497419da39f1e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![image.png](https://upload-images.jianshu.io/upload_images/14466577-7df488507e0485df.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![1.png](https://upload-images.jianshu.io/upload_images/14466577-6336c6df63810e4e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 总结 ![TIM截图20181112100140.png](https://upload-images.jianshu.io/upload_images/14465950-707b67c26e2327cc.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 集群运行 步骤: 将mapreduce程序打包成jar包 改namenode和datanode的hostname名字为namenode,datanode1/2/3 向namenode和datanode的/etc/hosts内添加集群信息(同完全分布式) 配置namenode和datanode的yarn-site.xml(ip为) ![TIM截图20181107100119.png](https://upload-images.jianshu.io/upload_images/14465950-8ce3eaba3419ea71.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)<file_sep>/sqoop/sqoop.md # Sqoop数据迁移 ## 配置 ### 1.解压压缩包 ### 2.配置文件(需自己cp) ![TIM截图20181121160831.png](https://upload-images.jianshu.io/upload_images/14465950-07265abcf9c2aead.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181121160758.png](https://upload-images.jianshu.io/upload_images/14465950-d40c9dcfbf9fd2f9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### 3.mysql驱动包mysql-connector-java-5.1.34.jar放到lib目录下 ## Sqoop命令 ![TIM截图20181121161256.png](https://upload-images.jianshu.io/upload_images/14465950-16bddaae59ccf434.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### 从关系型数据库导入数据到hdfs 在bin/目录下执行演示(因为没指定存在哪个目录下 所以默认存在/user/用户名/表名) ./sqoop import \ --connect jdbc:mysql://172.18.24.195:3306/sqooptest \ --username root \ --password hadoop \ --table users \ --m 1 (加\换行不执行) ### 自定义指定存储位置增加配置--target-dir /要存放的路径(不能存在)数据以","分割 --target-dir /sqooptable/users ### 设置分隔符 --fields-terminated-by --fields-terminated-by '\t' ### 设置查询字段 --columns --columns name,pwd ### 往hive中导入数据 --hive-import(没指定存在默认库里 表名还是关系型数据库中表名) --hive-import ### 指定库名表名 --hive-table --hive-table datatao.usertao ### 使用查询结果导入 使用--query 必须在where后加$CONDITIONS 不能再设置--table --query 'select id,name from users where $CONDITIONS'<file_sep>/linux/awk.md # awk 行读取命令 ### 格式 awk 选项 command file -F 设置分隔符 默认根据" "空格来分割 NR 行号 NF (根据分隔符)列数 print printf ![TIM截图20181022160030.png](https://upload-images.jianshu.io/upload_images/14465950-d47a1c7588b3df01.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181022160836.png](https://upload-images.jianshu.io/upload_images/14465950-8eda3b7ecccd987a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181022161448.png](https://upload-images.jianshu.io/upload_images/14465950-6bd974988e61b931.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 要使用正则: ~/正则表达式/ ![TIM截图20181022162523.png](https://upload-images.jianshu.io/upload_images/14465950-959e379ba214288b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 如果用!~就是对正则匹配的内容取非 ![TIM截图20181022162704.png](https://upload-images.jianshu.io/upload_images/14465950-0cf11a22fa950fd2.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) awk扩展格式 awk 选项 'BEGIN{} command END{}' file ![TIM截图20181022163906.png](https://upload-images.jianshu.io/upload_images/14465950-af5eaad30e198d97.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181022165050.png](https://upload-images.jianshu.io/upload_images/14465950-1f68e7f0c3cf3655.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181022171821.png](https://upload-images.jianshu.io/upload_images/14465950-bd0b795bcf7d815d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181022171121.png](https://upload-images.jianshu.io/upload_images/14465950-022c34c6eb66a68e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181022165250.png](https://upload-images.jianshu.io/upload_images/14465950-35bbf776268a47fa.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) <file_sep>/linux/case.md # sudo root 用户下 visudo ![TIM截图20181025203651.png](https://upload-images.jianshu.io/upload_images/14465950-4cbe94c7b60450aa.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 就可以使用root权限了<file_sep>/hadoop/mapreduce2.md # 自定义类型 ![image.png](https://upload-images.jianshu.io/upload_images/14466577-6a4e69e895734439.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### JavaBean ``` @Override public void write(DataOutput paramDataOutput) throws IOException { // TODO Auto-generated method stub paramDataOutput.writeInt(this.uploadStream); paramDataOutput.writeInt(this.downloadStream); paramDataOutput.writeInt(this.sumStream); } @Override public void readFields(DataInput paramDataInput) throws IOException { // TODO Auto-generated method stub uploadStream = paramDataInput.readInt(); downloadStream = paramDataInput.readInt(); sumStream = paramDataInput.readInt(); } @Override public int compareTo(Object paramT) { // TODO Auto-generated method stub SortBean beanOne = (SortBean)paramT; System.out.println("this:"+this); System.out.println("beanone:"+beanOne); return this.sumStream>beanOne.sumStream?1:-1; } ``` 自定义类型作为value,只使用Writable接口就可以; * 自定义类型作为key,首先还需要序列化,同时key是要排序的, 我们必须提供compareTo方法,需要实现Comparable接口,故使 用Writable和Comparable最方便. * 如果不设置compareTo(): ![image.png](https://upload-images.jianshu.io/upload_images/14466577-21440808d779ea7f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### driver区 ``` package com.lanou.test; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import com.lanou.model.SortBean; import com.lanou.util.SortMapper; import com.lanou.util.SortReduce; public class SortTest { public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException { //总流量 上行流量 下行流量 ,手机号 //key value //总流量进行排序 //把上次计算后的内容作为这次计算的输入 //多MapReduce串行 /* * 从log中获取手机号 上行下行流量 总流量 * reduce之后 手机号 流量对象 * *使用自定义类型输出 *1.要根据我们的数据进行建模(创建实体类) *2.mapper形参怎么写 map()方法当中怎么对数据进行切割筛选 *将我们的数据放入bean中 想好将bean以key,还是value进行输出 *3.map的结果最终要写入磁盘,所以自定义bean要支持序列化 *Serializble是Java提供重量级序列化 在我们hadoop更建 *使用hadoop自身提供的WritableComparable来实现序列化和反序列化 *这时有write()写入文件和readFields()从文件中读取的方法实现 *否则在reduce阶段是获取不到数据的 而这里一定要注意的一点是readFields()方法 *调用read()的时候要按照写入的顺序获取 *4.reduce当中注意形参和输出位置,以及driver 区对应好输出类型 * *job.setOutputKeyClass(Text.class); *job.setOutputValueClass(StreamBean.class); * *5.一切OK后,reduce就可以正常输出到我们指定的位置 *但注意bean的toString()方法要重写 */ //这里driver简写 Configuration conf = new Configuration(); Job job = Job.getInstance(conf,"sort bean"); job.setJarByClass(SortTest.class); job.setMapperClass(SortMapper.class); job.setCombinerClass(SortReduce.class); job.setReducerClass(SortReduce.class); job.setOutputKeyClass(SortBean.class); job.setMapOutputValueClass(Text.class); FileInputFormat.addInputPath(job, new Path("D:\\hadoop-2.7.3\\mapreduce\\output\\beanoutput\\part-r-00000")); FileOutputFormat.setOutputPath(job, new Path("D:\\hadoop-2.7.3\\mapreduce\\output\\sortoutput1")); boolean waitForCompletion = job.waitForCompletion(true); System.exit(waitForCompletion?0:1); } } ``` ### mapper区 ``` public class SortMapper extends Mapper<Object, Text, SortBean, Text> { private Text phoneText = new Text(); @Override protected void map(Object key, Text value, Mapper<Object, Text, SortBean, Text>.Context context) throws IOException, InterruptedException { // TODO Auto-generated method stub String[] vals = value.toString().split("\\s+"); String phone = vals[0]; String uploadStream = vals[1]; String downloadStream = vals[2]; String sumStream = vals[3]; //将截取的数据存入bean实例中 SortBean sortBean = new SortBean(uploadStream,downloadStream,sumStream); phoneText.set(phone); context.write(sortBean, phoneText); } } ``` ### reducer区 ``` @Override protected void reduce(SortBean key, Iterable<Text> value, Reducer<SortBean, Text, SortBean, Text>.Context context) throws IOException, InterruptedException { // TODO Auto-generated method stub //value只有一个数据所以直接获取不用foreach context.write(key, value.iterator().next()); } ```<file_sep>/git/build.md # 新建并上传当前博客 ## git clone 仓库地址 ![clipboard.png](https://upload-images.jianshu.io/upload_images/14465950-a4d77d0cb47cb12f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## git clone 地址来源 ![clipboard7.png](https://upload-images.jianshu.io/upload_images/14465950-d22ef29ced0ba579.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 配置公钥 ### 公钥在C:\Users\Administrator\.ssh\id_rsa.pub里 ![clipboard1.png](https://upload-images.jianshu.io/upload_images/14465950-fa23d9c6cdcb40a5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 重新clone ![clipboard.png](https://upload-images.jianshu.io/upload_images/14465950-a4d77d0cb47cb12f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 新建文件 ![clipboard2.png](https://upload-images.jianshu.io/upload_images/14465950-6baff883469e9bd6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 检查状态 ![clipboard3.png](https://upload-images.jianshu.io/upload_images/14465950-e852dc72722aa17f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 选择要添加的文件 ![clipboard4.png](https://upload-images.jianshu.io/upload_images/14465950-f3a4e6b0ebac7704.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 提交文件(提交日志)到本地git仓库 ![clipboard5.png](https://upload-images.jianshu.io/upload_images/14465950-444ce6fa0b5cfea4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 输入邮箱 用户名 ## 提交文件到服务器 以后不需要 -u及后面(第一次设置以后默认往master分支提交代码) ![clipboard6.png](https://upload-images.jianshu.io/upload_images/14465950-4143430cc14ad967.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) <file_sep>/hadoop/javahdfs.md # Java操作hdfs代码 ### 第一步当然是向windows引hadoop包 项目右键 ->buildPath ->在libraries中选择add Library () ->userlibrary ->new ->自定义名字-> add external JARS ->将common下面的common-2.7.3 以及其依赖引入(依赖位于lib文件中) ,再将HDFS 文件夹中的hdfs-2.7.3及其依赖 引入 ``` package com.lanou.test; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.BlockLocation; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.LocatedFileStatus; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.RemoteIterator; import org.apache.hadoop.io.IOUtils; import org.junit.Before; import org.junit.Test; public class HDFSTest2 { private static FileSystem fileSystem; //创建文件夹 @Test public void mkdirs() throws IOException { fileSystem.mkdirs(new Path("/list/")); } //上传文件 @Test public void upload() throws IOException { fileSystem.copyFromLocalFile(new Path("D:/hehe/hadoop-2.7.3.tar.gz"), new Path("/list")); } //下载文件 @Test public void Download() throws IllegalArgumentException, IOException{ fileSystem.copyToLocalFile(false, new Path("/taobao/java.md"), new Path("D:/hdfs/output/"), true); } //删除文件 @Test public void delete() throws IllegalArgumentException, IOException{ fileSystem.delete(new Path("/taobao"),false); } //查看文件信息 @Test public void findInfo() throws FileNotFoundException, IllegalArgumentException, IOException{ //迭代器 RemoteIterator<LocatedFileStatus> listFiles = fileSystem.listFiles(new Path("/list"), true); // User user = new User(); // user.setUserId(123); // user.setPassword("asd"); // user.setUsername("as"); // System.out.println(user); // System.out.println(user.toString()); while (listFiles.hasNext()) { LocatedFileStatus next = (LocatedFileStatus) listFiles.next(); BlockLocation[] blockLocations = next.getBlockLocations(); for (BlockLocation blockLocation : blockLocations) { System.out.println(blockLocation); } System.out.println(next); } } //流上传文件 @Test public void uploadByStream() throws IllegalArgumentException, IOException{ //input FileInputStream fileInputStream = new FileInputStream("D:/hehe/eclipse-jee-neon-3-win32-x86_64.zip"); //output FSDataOutputStream hdfsOutputStream = fileSystem.create(new Path("/list/eclipse-jee-neon-3-win32-x86_64.zip")); IOUtils.copyBytes(fileInputStream,hdfsOutputStream, 4096); } //流下载文件 @Test public void downloadByStream() throws IllegalArgumentException, IOException{ FSDataInputStream inputStream = fileSystem.open(new Path("/list/in.txt")); FileOutputStream fileOutputStream = new FileOutputStream("D:/hdfs/output/in.txt"); org.apache.commons.io.IOUtils.copy(inputStream,fileOutputStream); } //seek偏移下载 @Test public void downloadBySeek() throws IllegalArgumentException, IOException{ FSDataInputStream inputStream = fileSystem.open(new Path("/list/hadoop-2.7.3.tar.gz")); //偏移 inputStream.seek(10); FileOutputStream fileOutputStream = new FileOutputStream("D:/hdfs/output/out.txt"); org.apache.commons.io.IOUtils.copy(inputStream,fileOutputStream); } //只有两个block块下载第二个block块 @Test public void downloadBlock() throws FileNotFoundException, IllegalArgumentException, IOException{ FSDataInputStream inputStream = fileSystem.open(new Path("/list/eclipse-jee-neon-3-win32-x86_64.zip")); RemoteIterator<LocatedFileStatus> listFiles = fileSystem.listFiles(new Path("/list/eclipse-jee-neon-3-win32-x86_64.zip"), false); while (listFiles.hasNext()) { LocatedFileStatus next = (LocatedFileStatus) listFiles.next(); BlockLocation[] blockLocations = next.getBlockLocations(); for (int i = 0; i < blockLocations.length; i++) { System.out.println(blockLocations[i].getOffset()); if (i==1) { inputStream.seek(blockLocations[i].getOffset()); break; } } } FileOutputStream fileOutputStream = new FileOutputStream("D:/hdfs/output/block2.zip"); org.apache.commons.io.IOUtils.copy(inputStream,fileOutputStream); } //两个以上block块下载第二个 @Test public void copyLargeBlock() throws FileNotFoundException, IllegalArgumentException, IOException{ FSDataInputStream inputStream = fileSystem.open(new Path("/list/eclipse-jee-neon-3-win32-x86_64.zip")); FileOutputStream fileOutputStream = new FileOutputStream("D:/hdfs/output/block2.zip"); RemoteIterator<LocatedFileStatus> listFiles = fileSystem.listFiles(new Path("/list/eclipse-jee-neon-3-win32-x86_64.zip"), false); while (listFiles.hasNext()) { LocatedFileStatus next = (LocatedFileStatus) listFiles.next(); BlockLocation[] blockLocations = next.getBlockLocations(); for (int i = 0; i < blockLocations.length; i++) { System.out.println(blockLocations[i].getOffset()); if (i==1) { long inputoffset = blockLocations[i].getOffset(); long length = blockLocations[1].getLength(); org.apache.commons.io.IOUtils.copyLarge(inputStream, fileOutputStream, inputoffset, length); break; } } } } //两个以上block块下载每个block块 @Test public void copyLargeEachBlock() throws FileNotFoundException, IllegalArgumentException, IOException{ RemoteIterator<LocatedFileStatus> listFiles = fileSystem.listFiles(new Path("/list/eclipse-jee-neon-3-win32-x86_64.zip"), false); while (listFiles.hasNext()) { LocatedFileStatus next = (LocatedFileStatus) listFiles.next(); BlockLocation[] blockLocations = next.getBlockLocations(); FSDataInputStream inputStream = fileSystem.open(new Path("/list/eclipse-jee-neon-3-win32-x86_64.zip")); for (int i = 0; i < blockLocations.length; i++) { //inputStream.seek(0); FileOutputStream fileOutputStream = new FileOutputStream("D:/hdfs/output/blocks"+(i+01)+".zip"); System.out.println(blockLocations[i].getOffset()); //long inputoffset = blockLocations[i].getOffset(); long length = blockLocations[i].getLength(); org.apache.commons.io.IOUtils.copyLarge(inputStream, fileOutputStream, 0, length); } } } //用io流两个以上block块下载每个block块 @Test public void copyIOEachBlock() throws FileNotFoundException, IllegalArgumentException, IOException{ RemoteIterator<LocatedFileStatus> listFiles = fileSystem.listFiles(new Path("/list/eclipse-jee-neon-3-win32-x86_64.zip"), false); while (listFiles.hasNext()) { LocatedFileStatus next = (LocatedFileStatus) listFiles.next(); BlockLocation[] blockLocations = next.getBlockLocations(); long offset = 0; FSDataInputStream inputStream = fileSystem.open(new Path("/list/eclipse-jee-neon-3-win32-x86_64.zip")); for (int i = 0; i < blockLocations.length; i++) { FileOutputStream fileOutputStream = new FileOutputStream("D:/hdfs/output/blocks"+(i+1)+".zip"); long inputoffset = blockLocations[i].getOffset(); System.out.println(inputoffset); long length = blockLocations[i].getLength(); System.out.println(length); byte[] b = new byte[4096]; int numberRead = 0; while((numberRead = inputStream.read(b)) != -1 ) { offset = offset+numberRead; fileOutputStream.write(b,0,numberRead); if (offset == length+inputoffset ) { break; } } fileOutputStream.close(); } inputStream.close(); } } //连接hdfs @Before public void befores() throws IOException, URISyntaxException, InterruptedException{ // Configuration configuration = new Configuration(); // //设置要使用的文件系统是hdfs -> 地址为..... //设置用户 // System.setProperty("HADOOP_USER_NAME", "hadoop"); // configuration.set("fs.defaultFS", "hdfs://172.18.24.195:9000"); // fileSystem = FileSystem.get(configuration); // System.out.println(fileSystem); Configuration configuration = new Configuration(); // Hadoop的用户名 String hdfsUserName = "hadoop"; // HDFS的访问路径 URI hdfsUri = new URI("hdfs://172.18.24.195:9000"); // 根据远程的NN节点,获取配置信息,创建HDFS对象 fileSystem = FileSystem.get(hdfsUri,configuration,hdfsUserName); } } ```<file_sep>/hadoop/config.md # 单节点Hadoop ### 配置 防火墙关闭 systemctl stop firewalld systemctl disable firewalld systemctl status firewalld JDK 下载 解压 配置环境变量 hadoop配置 下载hadoop包 解压 配置环境变量(bin\sbin) 生效配置文件 . etc/profile ![TIM截图20181025195618.png](https://upload-images.jianshu.io/upload_images/14465950-0d39d3c60e9f8ab3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) # 伪分布式 cd hadoop-2.7.3/etc/ ![TIM截图20181025153957.png](https://upload-images.jianshu.io/upload_images/14465950-879bc9f454adccd8.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) (1)hadoop-env.sh $JAVA_HOME路径设置成/.../jdk (2)core-site.xml 临时文件 <property> <name>hadoop.tmp.dir</name> <value>/.../hadoop/tmp</value> </property> <property> <name>fs.defaultFS</name> <value>hdfs://namecode ip:9000</value> </property> (3)hdfs-site.xml 可有可无 <property> <name>dfs.replication</name> <value>1</value> </property> <property> <name>dfs.namenode.name.dir</name> <value>file:/.../hadoop/dfs/name</value> </property> <property> <name>dfs.datanode.data.dir</name> <value>file:/.../hadoop/dfs/data</value> </property> (4)yarn-site.xml <property> <name>mapreduce.framework.name</name> <value>yarn</value> </property> <property> <name>yarn.nodemanager.aux-services</name> <value>mapreduce_shuffle</value> </property> (5)mapred-site.xml(cp mapred-site.xml.templete) <property> <name>mapreduce.framework.name</name> <value>yarn</value> </property> 格式化HDFS (1)hadoop namenode -format Storage:.....successfully ![TIM截图20181025154313.png](https://upload-images.jianshu.io/upload_images/14465950-80cdf2c83f6bbbbe.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 启动HADOOP服务 start-all.sh 关闭hadoop服务 Stop-all.sh<file_sep>/hadoop/mapreduce3.md # Mapreduce 分区 # driver区 如果reduceTask的数量>= getPartition的结果数 ,则会多产生几个空的输出文件part-r-000xx 如果 1 < reduceTask的数量 < getPartition的结果数 ,则有一部分分区数据无处安放,会Exception!!! 如果 reduceTask的数量=1,则不管mapTask端输出多少个分区文件,最终结果都交给这一个reduceTask, 最终也就只会产生一个结果文件 part-r-00000. ``` //设置reduceTasks进程数量 job.setNumReduceTasks(4); //设置分区使用的partitioner job.setPartitionerClass(MobilePartioner.class); ``` ### 创建分区类,继承Partitioner类,实现getPartition()方法 ``` package com.lanou.util; import java.util.HashMap; import java.util.Map; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Partitioner; import com.lanou.model.StreamBean; public class MobilePartioner extends Partitioner<Text, StreamBean> { //1. map方法context.write()的key //2. map方法context.write()的value //3. reduceTask数量 private static Map map; static{ map = new HashMap<String,Integer>(); map.put("134", 0); map.put("135", 1); map.put("136", 2); } @Override public int getPartition(Text paramKey, StreamBean paramValue, int paramInt) { // TODO Auto-generated method stub // System.out.println("get 134 partition:"+map.get("134")); // System.out.println("get 135 partition:"+map.get("135")); // System.out.println("get 136 partition:"+map.get("136")); String key = paramKey.toString().substring(0,3); // System.out.println(paramKey); // System.out.println(paramValue); // System.out.println(paramInt); Integer result = (Integer) map.get(key); if (result == null) { result = 3; } // 返回值设置数据交给哪一个reduceTask return result; } } ``` ### Mapper区 ``` package com.lanou.util; import java.io.IOException; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import com.lanou.model.StreamBean; public class BeanStreamMapper extends Mapper<Object, Text, Text, StreamBean > { private Text phoneText = new Text(); @Override protected void map(Object key, Text value, Mapper<Object, Text, Text, StreamBean>.Context context) throws IOException, InterruptedException { // TODO Auto-generated method stub String[] vals = value.toString().split("\\s+"); String phone = vals[1]; String uploatStr = vals[vals.length-3]; String downloatStr = vals[vals.length-2]; StreamBean streamBean = new StreamBean(uploatStr,downloatStr); phoneText.set(phone); context.write(phoneText, streamBean); } } ``` ### Reducer区 ``` package com.lanou.util; import java.io.IOException; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer; import com.lanou.model.StreamBean; public class BeanStreamReduce extends Reducer<Text, StreamBean, Text, StreamBean >{ @Override protected void reduce(Text key, Iterable<StreamBean> lists, Reducer<Text, StreamBean, Text, StreamBean>.Context context) throws IOException, InterruptedException { // TODO Auto-generated method stub int uploadSum = 0; int downloadSum = 0; for (StreamBean streamBean : lists) { uploadSum += streamBean.getUploadStream(); downloadSum += streamBean.getDownloadStream(); } StreamBean streamBean = new StreamBean(uploadSum,downloadSum); context.write(key,streamBean ); } } ```<file_sep>/index.md # 佳文欢迎您 ## 相应博客链接如下 - git - [github blog build](http://taojiawen.github.io/git/build) - [git命令](http://taojiawen.github.io/git/1.jpg) - [git 常见错误](http://taojiawen.github.io/git/wrong) - [git 回顾](http://taojiawen.github.io/git/more) - linux - [Linux基础](http://taojiawen.github.io/linux/linux) - [vi编译器](http://taojiawen.github.io/linux/vi) - [用户 组管理](http://taojiawen.github.io/linux/user) - [文件权限管理](http://taojiawen.github.io/linux/chown) - [sed命令](http://taojiawen.github.io/linux/sed) - [awk命令](http://taojiawen.github.io/linux/awk) - [shell](http://taojiawen.github.io/linux/shell) - [sudo](http://taojiawen.github.io/linux/case) - hadoop - [伪分布式环境搭建](http://taojiawen.github.io/hadoop/config) - [完全分布式](http://taojiawen.github.io/hadoop/hadoop) - hdfs - [HDFS基本概念篇](http://taojiawen.github.io/hadoop/hdfs) - [HDFS读写原理篇](http://taojiawen.github.io/hadoop/node) - [NAMENODE工作机制](http://taojiawen.github.io/hadoop/namenode) - [DATANODE的工作机制](http://taojiawen.github.io/hadoop/datanode) - [HDFS应用开发篇](http://taojiawen.github.io/hadoop/javaHadoop) - [Java操作hdfs代码](http://taojiawen.github.io/hadoop/javahdfs) - mapreduce - [MapReduce](http://taojiawen.github.io/hadoop/mapreduce1) - [MapReduce](http://taojiawen.github.io/hadoop/mapreduce2) - [MapReduce](http://taojiawen.github.io/hadoop/mapreduce3) - [MapReduce](http://taojiawen.github.io/hadoop/mapreduce4) - [MapReduce](http://taojiawen.github.io/hadoop/mapreduce5) - [MapReduce](http://taojiawen.github.io/hadoop/mapreduce6) - [MapReduce](http://taojiawen.github.io/hadoop/mapreduce7) - hive - [hive简介](http://taojiawen.github.io/hive/hive0) - [hive库表操作](http://taojiawen.github.io/hive/hive1) - [hive查询语法和数据类型](http://taojiawen.github.io/hive/hive2) - [hive内置函数](http://taojiawen.github.io/hive/hive3)<file_sep>/hive/hive2.md # hive查询语法 # 分组 ![TIM截图20181115191331.png](https://upload-images.jianshu.io/upload_images/14465950-b26cb34ac68a7d27.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) # 排序 - order by: 会对输入做全局排序,因此只有一个reducer,只有一个 reduce task的结果,比如文件名是000000_0, 会导致当输入规模较大时,需要较长的计算时间 - sort by: 不是全局排序,其在数据进入reducer前完成排序。因此,如果用sort by进行排序,并且设置mapred.r- educe.tasks>1,则 sort by只保证每个reducer的输出有序,不保证全局有序 - distribute by:根据指定的字段将数据分到不同的reducer,且分发算法是hash散列 - Cluster by: 除了具有Distribute by的功能外,还会对该字段进行排序。因此,如果分桶和sort字段是同一个时, 此时clustered by = distribute by + sort by如果我们要分桶的字段和要 排序的字段不一样,那么我们就不能适用clustered by。分桶表的作用:最大的作用是用来提高 join 操作的效率 ![TIM截图20181115192142.png](https://upload-images.jianshu.io/upload_images/14465950-f51444bddf9dd04c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181115192245.png](https://upload-images.jianshu.io/upload_images/14465950-aba94a3f4c65b948.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181115192040.png](https://upload-images.jianshu.io/upload_images/14465950-06609b615854a124.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181115192302.png](https://upload-images.jianshu.io/upload_images/14465950-ad55cb0b14b0f311.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181115192317.png](https://upload-images.jianshu.io/upload_images/14465950-08fc9fb73a820d64.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) # join 联表查询 ## 内连接inner可以省略 ![TIM截图20181115192922.png](https://upload-images.jianshu.io/upload_images/14465950-9eb3c8f8318ade3b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181115202007.png](https://upload-images.jianshu.io/upload_images/14465950-e156ecfd8a6f1e2d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 左连接 ![TIM截图20181115202035.png](https://upload-images.jianshu.io/upload_images/14465950-c925560bab47fec0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) left semi join Left semi join :相当于join连接两个表后产生的数据中的左半部分 in/exists关键字(1.2.1之后新特性) in关键字 select * from t_a a where a.id in (select id from t_b); 效果等同于left semi join ## 全连接 ![TIM截图20181115202016.png](https://upload-images.jianshu.io/upload_images/14465950-d36e75d54a17cdd8.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) # 子查询 ![TIM截图20181115202047.png](https://upload-images.jianshu.io/upload_images/14465950-3a03fec37f196c37.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) # 数据类型 TINYINT (1字节整数) SMALLINT (2字节整数) INT/INTEGER (4字节整数) BIGINT (8字节整数) FLOAT (4字节浮点数) DOUBLE (8字节双精度浮点数) BOOLEAN(布尔类型):true false 字符串类型 STRING VARCHAR(20) (字符串1-65535长度,超长截断) CHAR (字符串,最大长度255) 时间类型 TIMESTAMP (时间戳) (包含年月日时分秒毫秒的一种封装) DATE (日期)(只包含年月日) ## array类型字段 ![TIM截图20181115202205.png](https://upload-images.jianshu.io/upload_images/14465950-7737635981e34723.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## map类型字段 ![TIM截图20181115202226.png](https://upload-images.jianshu.io/upload_images/14465950-e242ac942037b7bf.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## struct类型字段(类似对象) ![TIM截图20181116104903.png](https://upload-images.jianshu.io/upload_images/14465950-91e61f7d1322028b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181116104942.png](https://upload-images.jianshu.io/upload_images/14465950-bb18b9c578eeee27.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) <file_sep>/hive/hive3.md # 内置函数 ## 常见分组聚合函数 sum(字段) : 求这个字段在一个组中的所有值的和 avg(字段) : 求这个字段在一个组中的所有值的平均值 max(字段) :求这个字段在一个组中的所有值的最大值 min(字段) :求这个字段在一个组中的所有值的最小值 ### 求平均数 ![TIM截图20181115190752.png](https://upload-images.jianshu.io/upload_images/14465950-ec108ea8a3b70f54.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 条件控制函数 IF select id,if(age>25,'working','worked') from t_user; select moive_name,if(array_contains(actors,'吴刚'),'好电影',’烂片儿’) from t_movie; case when 语法: CASE [ expression ] WHEN condition1 THEN result1 WHEN condition2 THEN result2 ... WHEN conditionn THEN resultn ELSE result END ![TIM截图20181116142859.png](https://upload-images.jianshu.io/upload_images/14465950-01b59579275e1742.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### contain函数 ![TIM截图20181116142918.png](https://upload-images.jianshu.io/upload_images/14465950-e7d450d69bfc1ad9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### 类型转 select cast("5" as int) ; select cast("2017-08-03" as date) ; select cast(current_timestamp as date); ![TIM截图20181116143239.png](https://upload-images.jianshu.io/upload_images/14465950-953ab20dbc4672f5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### 数学运算函数 select round(5.4); ## 5 四舍五入 select round(5.1345,3) ; ##5.135 select ceil(5.4) ; // select ceiling(5.4) ; ## 6 向上取整 select floor(5.4); ## 5 向下取整 select abs(-5.4) ; ## 5.4 绝对值 select greatest(id1,id2,id3) ; ## 6 单行函数 select least(3,5,6) ; ##求多个输入参数中的最小值 ![TIM截图20181116143214.png](https://upload-images.jianshu.io/upload_images/14465950-37606514899b4d96.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### 字符串函数 substr(string str, int start) ## 截取子串 substring(string str, int start) ![TIM截图20181116143153.png](https://upload-images.jianshu.io/upload_images/14465950-7474f533b34f2976.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### 时间函数 select current_timestamp; 返回值类型:timestamp,获取当前的时间戳(详细时间信息) select current_date; 返回值类型:date,获取当前的日期 unix时间戳转字符串格式——from_unixtime from_unixtime(bigint unixtime[, string format]) 如果不带参数,取当前时间的秒数时间戳long--(距离格林威治时间1970-1-1 0:0:0秒的差距) select unix_timestamp(); unix_timestamp(string date, string pattern) 示例: select unix_timestamp("2017-08-10 17:50:30"); select unix_timestamp("2017-08-10 17:50:30","yyyy-MM-dd HH:mm:ss"); ## 将字符串转成日期date select to_date("2017-09-17 16:58:32"); ![TIM截图20181116143130.png](https://upload-images.jianshu.io/upload_images/14465950-265ce2a7c4cbb0ae.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### 集合函数 ![TIM截图20181116143529.png](https://upload-images.jianshu.io/upload_images/14465950-9200feaad68d48cb.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181116143451.png](https://upload-images.jianshu.io/upload_images/14465950-70a93f4debf2ff63.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### map函数 ![TIM截图20181116144942.png](https://upload-images.jianshu.io/upload_images/14465950-ac4db3237ad6535f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181116143857.png](https://upload-images.jianshu.io/upload_images/14465950-ce0eb9e378e0b798.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181116143651.png](https://upload-images.jianshu.io/upload_images/14465950-b848f9f1c73bacb3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### collect_set() :将某个字段在一组中的所有值形成一个集合(数组)返回 ### 行转列函数:explode() 两表互转 ![TIM截图20181116162828.png](https://upload-images.jianshu.io/upload_images/14465950-b9f999c01fd558ba.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181116162116.png](https://upload-images.jianshu.io/upload_images/14465950-46b641d3d52211f8.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181116160806.png](https://upload-images.jianshu.io/upload_images/14465950-86252a8038e34b81.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181116160427.png](https://upload-images.jianshu.io/upload_images/14465950-00764eeb5cebc410.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### count():求一个组中的满足某条件的数据条数 ![TIM截图20181116151239.png](https://upload-images.jianshu.io/upload_images/14465950-612af35a8bd6fa31.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### json解析函数:表生成函数 ![TIM截图20181116170249.png](https://upload-images.jianshu.io/upload_images/14465950-cf92b16d036e8bfc.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 窗口分析函数 ### row_number() over() 分组TOPN ![TIM截图20181116175408.png](https://upload-images.jianshu.io/upload_images/14465950-cc1256ea63401b0c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### sum() over()——级联求和 ![TIM截图20181116192640.png](https://upload-images.jianshu.io/upload_images/14465950-1f90c5b4bcd40c14.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) <file_sep>/azkaban/azkaban_start.md # azkaban 工作流调度器 ## azkaban配置 ### 1.三个压缩包解压放到一个文件夹下好管理 azkaban-2.5.0 存放 azkaban 运行需要的sql (sql执行完就不需要了) azkaban-executor-2.5.0 存放执行器 azkaban-web-2.5.0 存放web服务器 ### 2.MySQL下执行sql语句 只需执行其中create-all-sql-2.5.0.sql ![TIM截图20181121095802.png](https://upload-images.jianshu.io/upload_images/14465950-147874b28ef63e80.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### 2.1数据库里生成表 ![TIM截图20181121110815.png](https://upload-images.jianshu.io/upload_images/14465950-e858e16797a25f42.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### 3.ssl设置(密码记住后面要用) keytool -keystore keystore -alias jetty -genkey -keyalg RSA ![TIM截图20181121100554.png](https://upload-images.jianshu.io/upload_images/14465950-0f326339302f4333.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### 4.生成的keystore放到web下 ![TIM截图20181121100729.png](https://upload-images.jianshu.io/upload_images/14465950-7da6fec589fd01b5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### 5.配置web配置proprerties文件 ![TIM截图20181121100915.png](https://upload-images.jianshu.io/upload_images/14465950-7561fa2d57dbb63d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### 5.1修改时区 Asia/Shanghai ![TIM截图20181121101440.png](https://upload-images.jianshu.io/upload_images/14465950-0f7455ab06289c6c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### 5.2修改MySQL配置 ![TIM截图20181121101419.png](https://upload-images.jianshu.io/upload_images/14465950-c2f197b403e46fab.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### 5.3修改jetty(ssl)配置(之前设置ssl的密码) ![TIM截图20181121101535.png](https://upload-images.jianshu.io/upload_images/14465950-bf1c4e256d2da974.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### 6.配置web配置users文件(设置登录azkaban用户和权限) <user username="admin" password="<PASSWORD>" roles="admin,metrics" /> ![TIM截图20181121101945.png](https://upload-images.jianshu.io/upload_images/14465950-88ed1667da9ac818.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### 7.配置executor执行器 ![TIM截图20181121102117.png](https://upload-images.jianshu.io/upload_images/14465950-dd22192e0964e068.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### 7.1配置proprerties文件 ![TIM截图20181121102257.png](https://upload-images.jianshu.io/upload_images/14465950-0925540140587b18.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### 8.启动(关闭shutdown)executor服务 ![TIM截图20181121102341.png](https://upload-images.jianshu.io/upload_images/14465950-0b4756e0745d7847.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### 8.1在错误文件夹下不能执行 ![TIM截图20181121102502.png](https://upload-images.jianshu.io/upload_images/14465950-0a895d8cff31b512.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### 8.2 在executor根目录下用相对路径执行 ![TIM截图20181121102703.png](https://upload-images.jianshu.io/upload_images/14465950-b387f8e6b520dd93.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### 9.启动(关闭shutdown)web服务 ![TIM截图20181121102818.png](https://upload-images.jianshu.io/upload_images/14465950-2ba059b80e970a6e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181121102908.png](https://upload-images.jianshu.io/upload_images/14465950-291550f248e0d082.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ps 服务启动成功 ![TIM截图20181121103022.png](https://upload-images.jianshu.io/upload_images/14465950-72ae8eccdc67921a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### 10.浏览器访问(注意用HTTPS 端口8443) ![TIM截图20181121103122.png](https://upload-images.jianshu.io/upload_images/14465950-329eafe8a328f864.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### 10.1登录名密码就是我们设置的超级用户 ![TIM截图20181121103142.png](https://upload-images.jianshu.io/upload_images/14465950-e5dd78a90ff04c67.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### 11.新建工程 ![TIM截图20181121113841.png](https://upload-images.jianshu.io/upload_images/14465950-9afc6ecaa23bc97f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### 12.上传工作 ![TIM截图20181121111640.png](https://upload-images.jianshu.io/upload_images/14465950-70bb046701079f25.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### 12.1上传的必须是zip格式的压缩包(.job文件) ![TIM截图20181121111750.png](https://upload-images.jianshu.io/upload_images/14465950-48989b713ee8c5ad.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### 13.执行工作 ![TIM截图20181121112030.png](https://upload-images.jianshu.io/upload_images/14465950-b53a9a3dfd7953b0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181121112132.png](https://upload-images.jianshu.io/upload_images/14465950-63b9969384573ea3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### 14.查看详情 ![TIM截图20181121112300.png](https://upload-images.jianshu.io/upload_images/14465950-04e85bc105f27c4b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### 通过command命令来执行 type=command command=真正要执行的命令 ### 例子1(依赖 两个文件一起压缩 可以有先后顺序 依赖的job先执行完再执行自身 dependencies=job的名称) start.job type=command command=echo start end.job type=command dependencies=start command=echo end ### 例子2(执行hdfs命令) hdfs.job type=command command=hadoop fs -mkdir /azkaban #### 执行命令工作文件夹 ![TIM截图20181121115051.png](https://upload-images.jianshu.io/upload_images/14465950-3c819c61c32f696a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### 例子3(执行MapReduce job中设置要执行的命令 job和jar包一起压缩) wordcount.job type=command command=hadoop jar hadoop-mapreduce-examples-2.6.1.jar wordcount /acinput /acoutput ### 例子4(执行hive命令) hive-e.job type=command command=hive -e 'select * from datatao.orders'; #### 执行结果 ![TIM截图20181121145149.png](https://upload-images.jianshu.io/upload_images/14465950-b6cd04ee481579f1.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### 例子5(执行sql文件 同样一起压缩) selects.sql use datatao; select * from orders; hive-f.job type=command command=hive -f 'selects.sql' <file_sep>/hadoop/namenode.md # NAMENODE工作机制 ### NAMENODE职责 负责客户端请求的响应 元数据的管理(查询,修改) ### 元数据管理 namenode对数据的管理采用了三种存储形式: 内存元数据(NameSystem) 磁盘元数据镜像文件 数据操作日志文件(可通过日志运算出元数据) 内存中有一份完整的元数据(内存meta data) 磁盘有一个“准完整”的元数据镜像(fsimage)文件(在namenode的工作目录中) 用于衔接内存metadata和持久化元数据镜像fsimage之间的操作日志(edits文件) 注:当客户端对hdfs中的文件进行新增或者修改操作,操作记录首先被记入edits日志文件中, 当客户端操作成功后,相应的元数据会更新到内存meta.data中 ### 元数据的checkpoint 每隔一段时间,会由secondary namenode将namenode上积累的所有edits和一个最新的fsimage 下载到本地,并加载到内存进行merge(这个过程称为checkpoint)如果secondary namenode 有最新的fsimage 就不用下载了 fsimage - 它是在NameNode启动时对整个文件系统的快照 edit logs - 它是在NameNode启动后,对文件系统的改动序列 只有在NameNode重启时,edit logs才会合并到fsimage文件中,从而得到一个文件系统的最新 快照。但是在产品集群中NameNode是很少重启的,这也意味着当NameNode运行了很长时间后, edit logs文件会变得很大。在这种情况下就会出现下面一些问题: edit logs文件会变的很大,怎么去管理这个文件是一个挑战。 NameNode的重启会花费很长时间,因为有很多改动要合并到fsimage文件上。如果NameNode挂掉 了,那我们就丢失了很多改动因为此时的fsimage文件非常旧。 因此为了克服这个问题,我们需要一个易于管理的机制来帮助我们减小edit logs文件的大小和 得到一个最新的fsimage文件,这样也会减小在NameNode上的压力。这跟Windows的恢复点是非常 像的,Windows的恢复点机制允许我们对OS进行快照,这样当系统发生问题时,我们能够回滚到 最新的一次恢复点上。 ![图片03.png](https://upload-images.jianshu.io/upload_images/14465950-7694f9100bfc98ff.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### checkpoint操作的触发条件配置参数 dfs.namenode.checkpoint.check.period=60 #检查触发条件是否满足的频率,60秒 dfs.namenode.checkpoint.dir=file://${hadoop.tmp.dir}/dfs/namesecondary #以上两个参数做checkpoint操作时,secondary namenode的本地工作目录 dfs.namenode.checkpoint.edits.dir=${dfs.namenode.checkpoint.dir} dfs.namenode.checkpoint.max-retries=3 #最大重试次数 dfs.namenode.checkpoint.period=3600 #两次checkpoint之间的时间间隔3600秒 ### checkpoint的附带作用 namenode和secondary namenode的工作目录存储结构完全相同,所以,当namenode故障退出需要 重新恢复时,可以从secondary namenode的工作目录中将fsimage拷贝到namenode的工作目录,以 恢复namenode的元数据 ### 元数据目录说明 在第一次部署好Hadoop集群的时候,我们需要在NameNode(NN)节点上格式化磁盘: $HADOOP_HOME/bin/hdfs namenode -format 格式化完成之后,将会在$dfs.namenode.name.dir/current目录下如下的文件结构 current/ |-- VERSION |-- edits_* |-- fsimage_0000000000008547077 |-- fsimage_0000000000008547077.md5 `-- seen_txid 其中的dfs.name.dir是在hdfs-site.xml文件中配置的,默认值如下: <property> <name>dfs.name.dir</name> <value>file://${hadoop.tmp.dir}/dfs/name</value> </property> hadoop.tmp.dir是在core-site.xml中配置的,默认值如下 <property> <name>hadoop.tmp.dir</name> <value>/tmp/hadoop-${user.name}</value> <description>A base for other temporary directories.</description> </property> dfs.namenode.name.dir属性可以配置多个目录, 如/data1/dfs/name,/data2/dfs/name,/data3/dfs/name,....。各个目录存储的文件结构和内容都 完全一样,相当于备份,这样做的好处是当其中一个目录损坏了,也不会影响到Hadoop的元数据, 特别是当其中一个目录是NFS(网络文件系统Network File System,NFS)之上,即使你这台机器 损坏了,元数据也得到保存。 下面对$dfs.namenode.name.dir/current/目录下的文件进行解释。 1、VERSION文件是Java属性文件,内容大致如下: #Fri Nov 15 19:47:46 CST 2013 namespaceID=934548976 clusterID=CID-cdff7d73-93cd-4783-9399-0a22e6dce196 cTime=0 storageType=NAME_NODE blockpoolID=BP-893790215-192.168.24.72-1383809616115 layoutVersion=-47 其中   (1)、namespaceID是文件系统的唯一标识符,在文件系统首次格式化之后生成的;   (2)、storageType说明这个文件存储的是什么进程的数据结构信息 (如果是DataNode,storageType=DATA_NODE);   (3)、cTime表示NameNode存储时间的创建时间,由于我的NameNode没有更新过,所以这里的记录值 为0,以后对NameNode升级之后,cTime将会记录更新时间戳;   (4)、layoutVersion表示HDFS永久性数据结构的版本信息, 只要数据结构变更,版本号也要递减, 此时的HDFS也需要升级,否则磁盘仍旧是使用旧版本的数据结构,这会导致新版本的NameNode无 法使用;   (5)、clusterID是系统生成或手动指定的集群ID,在-clusterid选项中可以使用它;如下说明 a、使用如下命令格式化一个Namenode: $HADOOP_HOME/bin/hdfs namenode -format [-clusterId <cluster_id>] 选择一个唯一的cluster_id,并且这个cluster_id不能与环境中其他集群有冲突。如果没有提供 cluster_id,则会自动生成一个唯一的ClusterID。 b、使用如下命令格式化其他Namenode: $HADOOP_HOME/bin/hdfs namenode -format -clusterId <cluster_id> c、升级集群至最新版本。在升级过程中需要提供一个ClusterID,例如: $HADOOP_PREFIX_HOME/bin/hdfs start namenode --config $HADOOP_CONF_DIR  -upgrade -clusterId <cluster_ID> 如果没有提供ClusterID,则会自动生成一个ClusterID。   (6)、blockpoolID:是针对每一个Namespace所对应的blockpool的ID,上面的这个BP-893790215-192. 168.24.72-1383809616115就是在我的ns1的namespace下的存储块池的ID,这个ID包括了其对应的NameNode 节点的ip地址。    2、$dfs.namenode.name.dir/current/seen_txid非常重要,是存放transactionId的文件,format之后是0, 它代表的是namenode里面的edits_*文件的尾数,namenode重启的时候,会按照seen_txid的数字,循序从头 跑edits_0000001~到seen_txid的数字。所以当你的hdfs发生异常重启的时候,一定要比对seen_txid内的数 字是不是你edits最后的尾数,不然会发生建置namenode时metaData的资料有缺少,导致误删Datanode上多 余Block的资讯。 3、$dfs.namenode.name.dir/current目录下在format的同时也会生成fsimage和edits文件,及其对应的md5 校验文件。 补充:seen_txid 文件中记录的是edits滚动的序号,每次重启namenode时,namenode就知道要将哪些edits进行加载 <file_sep>/hadoop/node.md # HDFS读写原理篇 ## hdfs的工作机制 特点如下: 能够运行在廉价机器上,硬件出错常态,需要具备高容错性 流式数据访问,而不是随机读写 面向大规模数据集,能够进行批处理、能够横向扩展 简单一致性模型,假定文件是一次写入、多次读取 缺点: 不支持低延迟数据访问 不适合大量小文件存储(因为每条元数据占用空间是一定的) 不支持并发写入,一个文件只能有一个写入者 不支持文件随机修改,仅支持追加写入 HDFS中的block、packet、chunk block 这个大家应该知道,文件上传前需要分块,这个块就是block,一般为128MB,当然你可以去改, 不顾不推荐。因为块太小: 寻址时间占比过高。块太大:Map任务数太少,作业执行速度变慢。它是最大的一个单位。 packet packet是第二大的单位,它是client端向DataNode,或DataNode的PipLine之间传数据的基 本单位,默认64KB。 chunk chunk是最小的单位,它是client向DataNode,或DataNode的PipLine之间进行数据校验的基 本单位,默认512Byte,因为用作校验,故每个chunk需要带有4Byte的校验位。所以实际每个 chunk写入packet的大小为516Byte。由此可见真实数据与校验值数据的比值约为128 : 1。 (即64*1024 / 512) 例如,在client端向DataNode传数据的时候,HDFSOutputStream会有一个chunk buff,写满 一个chunk后,会计算校验和并写入当前的chunk。之后再把带有校验和的chunk写入packet, 当一个packet写满后,packet会进入dataQueue队列,其他的DataNode就是从这个dataQueue 获取client端上传的数据并存储的。同时一个DataNode成功存储一个packet后之后会返回一 个ack packet,放入ack Queue中。 概述 1.HDFS集群分为两大角色:NameNode、DataNode (Secondary Namenode) 2.NameNode负责管理整个文件系统的元数据 3.DataNode 负责管理用户的文件数据块 4.文件会按照固定的大小(blocksize)切成若干块后分布式存储在若干台datanode上 5.每一个文件块可以有多个副本,并存放在不同的datanode上 6.Datanode会定期向Namenode汇报自身所保存的文件block信息,而namenode则会负责保持文 件的副本数量 7.HDFS的内部工作机制对客户端保持透明,客户端请求访问HDFS都是通过向namenode申请来 进行 写详细步骤: 客户端向NameNode发出写文件请求。 检查是否已存在文件、检查权限。若通过检查,直接先将操作写入EditLog,并返回输出流对 象。 (注:WAL,write ahead log,先写Log,再写内存,因为EditLog记录的是最新的HDFS 客户端执行所有的写操作。如果后续真实写操作失败了,由于在真实写操作之前,操作就被写 入EditLog中了,故EditLog中仍会有记录,我们不用担心后续client读不到相应的数据块,因 为在第5步中DataNode收到块后会有一返回确认信息,若没写成功,发送端没收到确认信息, 会一直重试,直到成功)client端按128MB的块切分文件。client将NameNode返回的分配的可 写的DataNode列表和Data数据一同发送给最近的第一个DataNode节点,此后client端和NameNode 分配的多个DataNode构成pipeline管道,client端向输出流对象中写数据。client每向第一个 DataNode写入一个packet,这个packet便会直接在pipeline里传给第二个、第三个…DataNode。 (注:并不是写好一个块或一整个文件后才向后分发) 每个DataNode写完一个块后,会返回确认信息。 (注:并不是每写完一个packet后就返回确认信息,个人觉得因为packet中的每个chunk都携带 校验信息,没必要每写一个就汇报一下,这样效率太慢。正确的做法是写完一个block块后,对 校验信息进行汇总分析,就能得出是否有块写错的情况发生) 写完数据,关闭输输出流。 发送完成信号给NameNode。 (注:发送完成信号的时机取决于集群是强一致性还是最终一致性,强一致性则需要所有DataNode 写完后才向NameNode汇报。 最终一致性则其中任意一个DataNode写完后就能单独向NameNode汇报,HDFS一般情况下都是强调强 一致性) ![图片02.png](https://upload-images.jianshu.io/upload_images/14465950-12548792688c83f9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 读 1、跟namenode通信查询元数据,找到文件块所在的datanode服务器 2、挑选一台datanode(就近原则,然后随机)服务器,请求建立socket流 3、datanode开始发送数据(从磁盘里面读取数据放入流,以packet为单位来做校验) 4、客户端以packet为单位接收,现在本地缓存,然后写入目标文件 ![图片01.png](https://upload-images.jianshu.io/upload_images/14465950-5fdf7eafd1d2e319.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) <file_sep>/hadoop/mapreduce5.md # 分组 ## driver区 ``` job.setGroupingComparatorClass(GroupByOrderComparator.class); ``` ## 自定义GroupingComparator ``` package com.lanou.util; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.io.WritableComparator; import com.lanou.bean.OrderInfo; public class GroupByOrderComparator extends WritableComparator { //构造时直接调用 protected GroupByOrderComparator() { // TODO Auto-generated constructor stub super(OrderInfo.class,true); } @Override //返回0则分为一组进入一个reduce public int compare(WritableComparable a, WritableComparable b) { // TODO Auto-generated method stub OrderInfo orderInfo1 = (OrderInfo)a; OrderInfo orderInfo2 = (OrderInfo)b; //orerid 相同分为一组 int compareTo = orderInfo1.getOrderId().compareTo(orderInfo2.getOrderId()); return compareTo; } } ``` 分组前提要先排序(因为分组只比较相邻的对象 直到返回不是0就进入reduce) bean 重写 compareTo()方法 ``` @Override public int compareTo(OrderInfo o) { // TODO Auto-generated method stub int res = orderId.compareTo(o.getOrderId()); if(res == 0 ){ res = price.compareTo(o.getPrice()); } return res; } ``` mapper区 对想要的数据进行获取封装 ``` @Override protected void map(Object key, Text value, Mapper<Object, Text, Text, OrderInfo>.Context context) throws IOException, InterruptedException { // TODO Auto-generated method stub String[] vals = value.toString().split("\\s+"); orderinfo.setOrder(vals[0], vals[1], vals[2]); ordeText.set(orderinfo.getOrderId()); context.write(ordeText, orderinfo); } ``` reducer区 对已经分好组的数据进行比较 最后输出 ``` @Override protected void reduce(Text orderId, Iterable<OrderInfo> orderList, Reducer<Text, OrderInfo, OrderInfo, NullWritable>.Context context) throws IOException, InterruptedException { // TODO Auto-generated method stub OrderInfo maxOrder = new OrderInfo(); for (OrderInfo orderInfo : orderList) { if (orderInfo.getPrice() > maxOrder.getPrice()) { //深拷贝 try { BeanUtils.copyProperties(maxOrder, orderInfo); } catch (IllegalAccessException | InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } context.write(maxOrder, NullWritable.get()); } ```<file_sep>/hadoop/mapreduce1.md # MapReduce ## 第一步还是引入jar包(步骤如hdfs篇) ##### MapReduce 适合离线处理,不擅长实时计算,流式计算 ##### 并行编程模型:用于对大规模数据集(大于1TB)的并行处理 ### MapReduce()只需要制定两个方法: ##### map():对元素进行制定操作,可以高度并行 ##### reduce():对列表元素进行合并 ## WordCount实例 ![image.png](https://upload-images.jianshu.io/upload_images/14466577-a4907da159050d4d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ``` package com.lanou.test; import java.io.IOException; import java.util.StringTokenizer; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.util.GenericOptionsParser; import com.lanou.util.CountMapper; import com.lanou.util.CountReduce; public class WordCountTest { //mapper区 public static class TokenizerMapper extends Mapper<Object, Text, Text, IntWritable> { private static final IntWritable one = new IntWritable(1); private Text word = new Text(); //key默认是字节偏移量,value是获取的一行内容 public void map(Object key, Text value, Mapper<Object, Text, Text, IntWritable>.Context context) throws IOException, InterruptedException { //分割每个单词计数1 StringTokenizer itr = new StringTokenizer(value.toString()); while (itr.hasMoreTokens()) { this.word.set(itr.nextToken()); //如果我们使用自定义类需要序列化 因为会写入文件 //将处理的数据以需要的形式进行写入 context.write(this.word, one); } } } //reducer区 public static class IntSumReducer extends Reducer<Text, IntWritable, Text, IntWritable> { private IntWritable result = new IntWritable(); // public void reduce(Text key, Iterable<IntWritable> values, Reducer<Text, IntWritable, Text, IntWritable>.Context context) throws IOException, InterruptedException { int sum = 0; for (IntWritable val : values) { sum += val.get(); } this.result.set(sum); context.write(key, this.result); } } //driver区 public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs(); if (otherArgs.length < 2) { System.err.println("Usage: wordcount <in> [<in>...] <out>"); System.exit(2); } //工作 Job job = Job.getInstance(conf, "word count"); //打包 job.setJarByClass(WordCountTest.class); //设置map job.setMapperClass(CountMapper.class); //合并 job.setCombinerClass(IntSumReducer.class); //设置reduce job.setReducerClass(CountReduce.class); //设置输出结果类型 job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); for (int i = 0; i < otherArgs.length - 1; i++) { //告诉job我们要读取的路径(除了输出路径的其他参数) FileInputFormat.addInputPath(job, new Path(otherArgs[i])); } //设置输出路径文件夹(最后一个参数) FileOutputFormat.setOutputPath(job, new Path(otherArgs[(otherArgs.length - 1)])); //将我们是设置好的job真正提交给yarn帮我们分配资源,开始工作根据返回值判断是否退出 System.exit(job.waitForCompletion(true) ? 0 : 1); } } ``` <file_sep>/linux/linux.md # Linux 常用指令 ### 1.重启命令 - reboot - shutdown -r now 立刻重启(root用户使用) - shutdown -r 10 过十分钟自动重启(root用户使用) - shutdown -r 20:12 在时间为20:12重启(root用户使用) - 如果是通过shutdown命令设置重启的话,可以用shutdown -c命令取消重启 ### 2.关机命令 - halt 立即关机 - poweroff 立即关机 - shutdown -h now 立即关机(root用户使用) - shutdown -h 10 10分钟后自动关机 ### 3.Linux 运行级别 ![TIM截图20181017191402.png](https://upload-images.jianshu.io/upload_images/14465950-55274248149eb9b3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### 4.关于主机名 - hostname 查看主机名 - hostname 新主机名 (临时修改 重启后变回原来的) - 修改配置文件 /etc/hostname文件(永久修改) ### 5.ping命令 - ping 目标主机 - Ctrl + C 中止测试 ### 6.查看网络接口信息 - ifconfig命令 - ifconfig不能用 使用 yum install net-tools ### 7.虚拟机网络配置图 ![图片1.png](https://upload-images.jianshu.io/upload_images/14465950-c671b21d92d4ea4d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### 8.设置防火墙 - service firewalld status 查看防火墙状态 - systemctl stop firewalld 关闭防火墙(临时关闭) - systemctl disable firewalld (禁止开机启动) ### 9./etc/hosts文件 - 保存主机名与IP地址的映射记录 - 访问时先在本地查找,找不到去DNS服务器找 ### 10.设置SELinux - getenforce 查看状态 - setenforce [ Enforcing | Permissive| 1| 0 ] 该命令可以立即改变SELinux运行状态,在Enforcing 和Permissive 之间切换,关机重启之后失效。 - 修改配置文件/etc/selinux/config,将SELINUX=enforcing修改为SELINUX=disabled重启生效 ### 11.Linux基础命令 #### 内部命令:属于Shell解析器的一部分 #### cd 切换目录(change directory) - ./ :当前目录 - ../:上层目录 #### pwd 显示当前工作目录(print working directory) #### help 帮助 #### 外部命令:独立于Shell解析器之外的文件程序 #### ls 显示文件和目录列表(list) - -l:详细信息显示 - -a:显示所有子目录和文件的信息,包括隐藏文件 - -A:类似于“-a”,但不显示“.”和“..”目录的信息 - -R:递归显示内容 #### mkdir 创建目录(make directoriy) -p: 可以创建路径全部文件夹 #### cp 复制文件或目录(copy) - -r:递归复制整个目录树 - -p:保持源文件的属性不变 - -f:强制覆盖目标同名文件或目录 - -i:需要覆盖文件或目录时进行提醒 #### 查看帮助文档 - 内部命令:help + 命令(help cd) - 外部命令:man + 命令(man ls) #### du 统计目录及文件的空间占用情况 - -a:统计时包括所有的文件,而不仅仅只统计目录 - -h:以更易读的字节单位(K、M等)显示信息 - -s:只统计每个参数所占用空间总的大小 #### touch命令 - 新建空文件 - `>` 用法相同 - echo "内容" >> 文件名 (往文件里输出,文件不存在直接创建) #### file命令 查看文件类型 #### rm命令 - -f:强行删除文件,不进行提醒 - -i:删除文件时提醒用户确认 - -r:递归删除整个目录树 #### mv命令 移动(Move)文件或目录—— 如果目标位置与源位置相同,则相当于改名 #### which命令 显示系统命令所在目录 #### find命令 - -name 根据文件名查找 - -user 根据文件拥有者查找 - -group 根据文件所属组寻找文件 - -perm 根据文件权限查找文件 - -size 根据文件大小查找文件 - -type 根据文件类型查找(f-普通文件,c-字符设备文件,b-块设备文件,l-链接文件,d-目录) - -o 表达式或 - -and 表达式与 #### cat命令 显示出文件的全部内容 #### more命令 全屏方式分页显示文件内容 - 按Enter键向下逐行滚动 - 按空格键向下翻一屏、按b键向上翻一屏 - 按q键退出 #### less命令 与more命令相同 #### head命令 查看文件开头的一部分内容(默认为10行) - head -5 查看文件开头5行 #### tail命令 查看文件结尾的少部分内容(默认为10行) - tail -5 查看文件结尾5行 #### wc命令 统计文件中的单词数量(Word Count)等信息 - -l:统计行数 - -w:统计单词个数 - -c:统计字节数 #### grep命令 查找文件里符合条件的字符串 - -c:计算匹配关键字的行数 - -i:忽略字符大小写的差别 - -n:显示匹配的行及其行号 - -s: 不显示不存在或不匹配文本的错误信息 - -h: 查询多个文件时不显示文件名 - -l: 查询文件时只显示匹配字符所在的文件名 - --color=auto:将找到的关键字部分加上颜色显示 - 正则表达式简单规则 - . : 任意一个字符 - a* : 任意多个a(零个或多个a) - a? : 零个或一个a - a+ : 一个或多个a - .* : 任意多个任意字符 - \. : 转义. - o\{2\} : o重复两次 #### gzip 压缩(解压)文件或目录,压缩文件后缀为gz - -d将压缩文件解压(decompress) - -l显示压缩文件的大小,未压缩文件的大小,压缩比(list) - -v显示文件名和压缩比(verbose) - -num用指定的数字num调整压缩的速度,-1或--fast表示最快压缩方法(低压缩比),-9或--best表示最慢压缩方法(高压缩比)。系统缺省值为6 #### bzip2 压缩(解压)文件或目录,压缩文件后缀为bz2 - -c将压缩的过程产生的数据输出到屏幕上 - -d解压缩的参数(decompress) - -z压缩的参数(compress) - -num 用指定的数字num调整压缩的速度,-1或--fast表示最快压缩方法(低压缩比),-9或--best表示最慢压缩方法(高压缩比)。系统缺省值为6 #### tar 文件、目录打(解)包 - -c:创建 .tar 格式的包文件 - -x:解开.tar格式的包文件 - -v:输出详细信息 - -f:表示使用归档文件 <file_sep>/git/wrong.md # 两种远端本地不同步错误 ## 如果遇到需要解决代码冲突的问题 1.git stash对我们的本地代码进行入栈操作 2.git pull 将我们远端仓库的代码拉取下来 3.git stash pop将我们的本地代码进行出栈(远端代码和本地代码有冲突的部分会出现 ![123.png](https://upload-images.jianshu.io/upload_images/14465950-93fc3c63b123c75e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 这种样子,我们只需要将<,=,>都删掉,然后将冲突代码都改成我们最终想要的样子保存重新提交就好了) ![1539655762(1).jpg](https://upload-images.jianshu.io/upload_images/14465950-5e986d3a8aef2c9e.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![C)4L__M$5_L@7H)OJUW1EW5.png](https://upload-images.jianshu.io/upload_images/14465950-6edf10b83723d59b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 远端更新先本地拉取 ![F0D3LZZ3%0DQLXCK$V)NEDN.png](https://upload-images.jianshu.io/upload_images/14465950-daa2946b4ae081c6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) <file_sep>/git/more.md # git使用回顾 ## 一、如果是直接从远程仓库进行克隆 1.git clone 仓库路径 2.创建自己的文件 3.git add 要上传的文件 4.git commit -m "提交的信息" 5.git pull(因为你不知道什么时候远端代码会跟本地仓库版本不匹配,所以要提交之前先进行拉取再推送) 6.git push ## 二、如果是自己在本地创建仓库,然后讲内容同步到远程仓库 1.git init (初始化生成git仓库,生成.git文件夹) ![$G7KIJAA@~0[]1N%X})BG4.png](https://upload-images.jianshu.io/upload_images/14465950-7337fd3f5ee1f7d3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 2.操作自己的文件 3.git add 要上传的文件 4.git commit -m "提交的信息" 5.git remote add origin 要连接的远程仓库的地址(因为刚开始初始化的仓库并不知道接下来的代码要提交到哪个远端仓库中) ![M3N9NUO2EOZNF7}F~%A%C%E.png](https://upload-images.jianshu.io/upload_images/14465950-2a4218cd2e3c85f3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![JN1R41{AD3}$S5UNFTJA5I.png](https://upload-images.jianshu.io/upload_images/14465950-4aea1e8f7c758372.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 6.第一次要将代码上传到远端空的仓库是不需要进行拉取操作的,之后的每一次推送前要都先进行pull的操作 git pull origin master(如果没进行push指令进行默认的分支选择,直接使用git pull命令会失效) 7.git push -u origin master(只有第一次需要执行以后的操作都是默认往master这个主分支上面进行操作才 需要加,以后push,和pull都只需要git push/pull就好了) ## 三、默认情况下哪个账号创建的仓库,只有本人能提交东西上来,如果想要多人开发需要邀请别人成为协作者,或者通过创建组织、团队来实现多人共同维护一个仓库 <file_sep>/linux/user.md # Linux 用户 ## 配置文件 - 保存用户信息的文件:/etc/passwd - 保存密码的文件:/etc/shadow - 保存用户组的文件:/etc/group - 保存用户组密码的文件:/etc/gshadow - 用户配置文件:/etc/default/useradd ## 用户在系统中是分为角色的,通过UID来识别角色 root用户,系统唯一,可以操作系统任何文件和命令,拥有最高权限,UID=0 虚拟用户(系统账户),不具有登录系统能力,但却是系统运行不可缺少的用户。如:bin、daemon、ftp、mail等,UID为1---499之间 普通真实用户,可以登录系统,权限有限,靠管理员创建,UID为500—60000之间 ## 系统账户 - 1 – 99:由distributions自行创建的系统账号 - 100 – 499:若用户有系统账号需求时,可以使用的UID ### 为了更好的管理用户,出现组group的概念 基本组(私有组) 当用户创建文件和文件夹时,默认属于私有组 附加组(公共组) # 用户管理 ## 用户管理配置文件 ### 用户账号文件--/etc/passwd ![TIM截图20181018212652.png](https://upload-images.jianshu.io/upload_images/14465950-55fd4b1d6bd150af.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### 用户密码文件--/etc/shadow ![TIM截图20181018212830.png](https://upload-images.jianshu.io/upload_images/14465950-6b6c32df1a1ae3c2.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 用户管理命令 ### useradd 添加用户命令 - -u 指定组ID(uid) - -g 指定所属的组名(gid) - -G 指定多个组,用逗号“,”分开(Groups) - -c 用户描述(comment) - -e 失效时间(expire date) ### passwd 设置密码 - -d:清空用户的密码,使之无需密码即可登录 - -l:锁定用户帐号 - -S:查看用户帐号的状态(是否被锁定) - -u:解锁用户帐号 - -x: 最大密码使用时间(天) - -n: 最小密码使用时间(天) ### usermod 修改已有用户属性 - -l 修改用户名 (login)usermod -l a b(b改为a) - -g 添加组 usermod -g sys tom - -G添加多个组 usermod -G sys,root tom - –L 锁定用户账号密码(Lock) - –U 解锁用户账号(Unlock) ### userdel 删除用户命令 - -r 删除账号时同时删除目录(remove) # 组管理 ## 组管理配置文件 ### 用户组文件:/etc/group ![TIM截图20181018213530.png](https://upload-images.jianshu.io/upload_images/14465950-79f4784095090891.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### 用户组密码文件: /etc/gshadow ![TIM截图20181018213625.png](https://upload-images.jianshu.io/upload_images/14465950-ef96b6e3c26003df.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 组命令管理 ### groupadd 添加组账号 -g 指定gid ### groupmod 修改组 - -g:设置想要使用的GID - -o:使用已经存在的GID - -n:设置想要使用的群组名称 ### gpasswd 设置组帐号密码(极少用)、添加/删除组成员 - -a:向组内添加一个用户 - -d:从组内删除一个用户成员 - -M:定义组成员列表,以逗号分隔 ### groupdel 删除组账号 注意:只能删除那些没有被任何用户指定为主组的组。 显示用户所属组 ### groups 查看当前组 <file_sep>/linux/shell.md # shell ## shell基础 ### shell基本格式 #!/bin/bash echo “hello world!” ### shell执行方式 - sh方式 - source方式 (source命令也称为“点命令”,也就是一个点符号.) - 直接执行该脚本文件 ./test.sh (注意,一定要写成 ./test.sh,而不是 test.sh) ## Base简介 Bash( Bourne Again SHell)是GNU计划的一个组件,与Unix上 的Bourne Shell完全兼容,是其增强版本;支持命令行输入、操 作历史、快捷键、输入输出重定向、管道、变量等功能。 ### history 在Bash中输入history指令可以查询用户的过往操作历史命令会默 认保存1000条,可以在环境变量配置文件中/etc/profile进行修改 History表存储在内存中,在用户logout时会记录入用户家目录的 .bash_history文件中,在下次login时载入 -c:清除历史命令 -w:把缓存中的历史命令写入历史命令保存文件 保存位置: ~/.bash_history ### tab 在bash中,命令与文件补全是非常方便与常用的功能,我们只需要 在输入命令或者文件时,按“Tab”就会自动补全。 连续两下[Tab] 可以输出以前面字母开头的所有命令 ### alias(别名) ![TIM截图20181023094215.png](https://upload-images.jianshu.io/upload_images/14465950-79843df0f7c5ba6a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 用户可以键入alias指令,来查询当前已经定义的alias列表; 用户也可以用unalias来取消一条别名记录; ### | 管道符 将左侧的命令输出结果,作为右侧命令的处理对象 例如 [root@master ~]# cat test.txt | wc -l ### 通配符 * 代表 0 个到无穷多个任意字符 ? 代表一定有一个任意字符 [] 代表一定有一个在括号内的字符(非任意字符)。例如 [abcd] 代 表一定有一个字符, 可能是 a, b, c, d 这四个任何一个 。 [ - ]若有减号在中括号内时,代表在编码顺序内的所有字符。例如 [0-9] 代表 0 到 9 之间的所有数字,因为数字的语系编码是连续的! [^]若中括号内的第一个字符为指数符号 (^) ,那表示反向选择,例 如 [^abc] 代表 一定有一个字符,只要是非 a, b, c 的其他字符就 接受的意思. ### 常用热键 Ctrl + d 输入已结束 Ctrl + c 键盘中断请求 Ctrl + s 暂停屏幕输出 Ctrl + q 恢复屏幕输出 Ctrl + l 清屏,相当于clear Tab 自动补完命令行与文件名 Ctrl + u 删除当前光标前的所有字符 Ctrl + k 删除当前光标后的所有字符 ### cut 截取命令 功能说明:显示文件中的某一列 语法: cut <选项> 文件 常用选项 -d:指定分隔符 -f:依据 -d 的分隔字符将一段信息分割成为数段,用 -f 取出第几段的意思 -c:指定几个字符对应的列 例如 将PATH变量取出,找出第三和第五个路径 [root@master ~]# echo $PATH | cut -d ':' -f 3,5 /usr/sbin ## shell编程 ### shell中的变量 Linux Shell中的变量分为“系统变量”和“用户自定义变量”,可以通过set命令 查看那系统变量 系统变量:$HOME、$PWD、$SHELL、$USER等等 显示当前shell中所有变量 : set #### 自定义变量 格式:变量名=变量值 规则 变量与变量内容以一个等号来连结 等号两侧不能有空格 变量名以字母或下划线开头,区分大小写,建议全大写 STR="hello world" A=9 unset A 撤销变量 A readonly B=2 声明静态的变量 B=2 ,不能 unset export 变量名 可把变量提升为全局环境变量,可供其他shell程序使用 #### 赋值时使用引号 双引号:允许通过$符号引用其变量值 单引号:禁止引用其他变量值,$视为普通字符 反撇号:命令替换,提取命令执行后的输出结果,也可用$(命令) 从键盘输入内容变为赋值 read -p(提示语句)-n(字符个数) -t(等待时间) 将命令的返回值赋给变量 A=$(ls -la) #### 特殊变量 $#:表示参数的个数,常用于循环 $*:参数的内容 $$:当前shell进程的pid值 $?:前一命令返回的状态值(0为正常) $0 表示当前脚本名称 $1 第一个参数 $N 第N个参数 ### 算数运算 格式:expr 变量1 运算符 变量2 [运算符 变量3] ... 例如 计算(2+3)x4的值 [root@master~]# expr $(expr 2 + 3) \* 4 ### test命令 测试特定的表达式是否成立,当条件成立时,测试语句的返回值为0, 否则为其他数值 test 条件表达式 [ 条件表达式 ] #### 文件测试 格式:[ 操作符 文件或目录 ] 注意condition前后要有空格 常用的测试操作符 -d:测试是否为目录(Directory) -e:测试目录或文件是否存在(Exist) -f:测试是否为文件(File) -b: 该文件是否存在且为一个块设备文件 -c: 该文件是否存在且为一个字符设备文件 -S: 该文件是否存在且为一个Socket文件 -p: 该文件是否存在且为一个FIFO(pipe)文件 -L: 该文件是否存在且为一个链接文件 ![TIM截图20181023141100.png](https://upload-images.jianshu.io/upload_images/14465950-f229ced67d31e13f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181023141441.png](https://upload-images.jianshu.io/upload_images/14465950-76f9c29da17bc146.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181023142116.png](https://upload-images.jianshu.io/upload_images/14465950-de272803eaa0dc1d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) #### 文件权限测试 格式:[ 操作符 文件或目录 ] 常用的测试操作符 -r:测试当前用户是否有权限读取(Read) -w:测试当前用户是否有权限写入(Write) -x:测试当前用户是否有权限执行(eXcute) -u: 测试该文件是否存在且具有suid属性 -g: 测试该文件是否存在且具有sgid属性 -k: 测试该文件是否存在且具有sticky bit属性 -s :测试该文件是否存在且为非空文件 ![TIM截图20181023142825.png](https://upload-images.jianshu.io/upload_images/14465950-71028f993db4acfe.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) #### 数值比较 格式:[ 整数1 操作符 整数2 ] 常用的测试操作符 -eq:等于(Equal) -ne:不等于(Not Equal) -gt:大于(Greater Than) -lt:小于(Lesser Than) -le:小于或等于(Lesser or Equal) -ge:大于或等于(Greater or Equal) ![TIM截图20181023143656.png](https://upload-images.jianshu.io/upload_images/14465950-0bb64b3e0cc85d3c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181023143834.png](https://upload-images.jianshu.io/upload_images/14465950-5c92a0b2ed629521.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) #### 字符串比较 格式 [ 字符串1 = 字符串2 ] [ 字符串1 != 字符串2 ] [ -z 字符串 ]字符串内容为空 常用的测试操作符 =:字符串内容相同 !=:字符串内容不同,! 号表示相反的意思 ![TIM截图20181023144654.png](https://upload-images.jianshu.io/upload_images/14465950-78a2d16dfa5d9dc5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181023144941.png](https://upload-images.jianshu.io/upload_images/14465950-34fa5a57e51070e8.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181023150026.png](https://upload-images.jianshu.io/upload_images/14465950-f2d01b6fcc5b20f1.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### if语句结构 ![TIM截图20181023210941.png](https://upload-images.jianshu.io/upload_images/14465950-07c44f9597529451.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181023211007.png](https://upload-images.jianshu.io/upload_images/14465950-24252ca4d14fb630.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181023211029.png](https://upload-images.jianshu.io/upload_images/14465950-3aa6beab70838beb.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### case语句结构 ![TIM截图20181023211103.png](https://upload-images.jianshu.io/upload_images/14465950-dc94f5a0d917ca91.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### for语句结构 ![TIM截图20181023211134.png](https://upload-images.jianshu.io/upload_images/14465950-f61e41b0dbab9d7f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181023211148.png](https://upload-images.jianshu.io/upload_images/14465950-4cabc80b377478ec.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### while语句的结构 ![TIM截图20181023211228.png](https://upload-images.jianshu.io/upload_images/14465950-dc446e1c3ded2f9b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### Shell自定义函数 ![TIM截图20181023211259.png](https://upload-images.jianshu.io/upload_images/14465950-eaa27522a52ff11c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) [shell 括号](https://blog.csdn.net/liweigao01/article/details/78669674) <file_sep>/linux/sed.md # sed命令 ### 格式:sed 选项 动作 filename ### 选项 -n (使用安静(silent)模式。被处理的行才会在命令行打印) ### 动作 - a 往下一行新增 ![TIM截图20181022191629.png](https://upload-images.jianshu.io/upload_images/14465950-8d3310f411f2a7fb.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) - i 往上一行新增 用法与a类似 - c 替换(1,5c会将这一块区域整个替换,不会每行都替换) ![TIM截图20181022192711.png](https://upload-images.jianshu.io/upload_images/14465950-64c6ea4e8813ff98.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) - d 删除 ![TIM截图20181022110522.png](https://upload-images.jianshu.io/upload_images/14465950-18293410c4bd731a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) - p 输出 (多和 -n 一起使用) - w 写入 sed 'w 要被写入的文件(目标文件)' 读取内容的文件(源文件)只要是w向文件 中进行写入就会将目标文件之前的内容全部干掉 - r 读取 sed '2r 要读取的文件' 加入数据的文件(目标文件) - s 替换经常配合正则进行操作 ![TIM截图20181022111819.png](https://upload-images.jianshu.io/upload_images/14465950-602a09a2072d7c33.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) - 高级操作 | 管道符,使用该符号配合其他命令 {} 可以让sed执行多个动作,只是动作之间要用";"分号隔开 &替换 &相当于占位符的作用 就是我们 s/查询条件/查询到的内容 可以在s/查询条件/要替换成的内容中进行使用,实现追加的效果 \u转成大写可以配合我们的&来实现将匹配内容转换成大写的操作 ![TIM截图20181022114542.png](https://upload-images.jianshu.io/upload_images/14465950-fac7da2c2f3adebd.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ()分组功能 获取分组的内容 首先分组的序号是从1开始的并且按照从左到右的顺序排的 要获取使用\分组的序号来获取,例如\1就是占位符 ![TIM截图20181022141939.png](https://upload-images.jianshu.io/upload_images/14465950-0307d235885b9e42.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) <file_sep>/hadoop/datanode.md # DATANODE的工作机制 ### 概述 1、Datanode工作职责: 存储管理用户的文件块数据 定期向namenode汇报自身所持有的block信息(通过心跳信息上报) (这点很重要,因为,当集群中发生某些block副本失效时,集群如何恢复block初始副本数量的问题) <property> <name>dfs.blockreport.intervalMsec</name> <value>3600000</value> <description>Determines block reporting interval in milliseconds.</description> </property> 2、Datanode掉线判断时限参数: datanode进程死亡或者网络故障造成datanode无法与namenode通信,namenode不会立即把该节点判定为 死亡,要经过一段时间,这段时间暂称作超时时长。HDFS默认的超时时长为10分钟+30秒。如果定义超时 时间为timeout,则超时时长的计算公式为: timeout = 2 * heartbeat.recheck.interval + 10 * dfs.heartbeat.interval。 而默认的heartbeat.recheck.interval 大小为5分钟,dfs.heartbeat.interval默认为3秒。 需要注意的是hdfs-site.xml 配置文件中的heartbeat.recheck.interval的单位为毫秒, dfs.heartbeat.interval的单位为秒。所以,举个例子,如果heartbeat.recheck.interval设置为 5000(毫秒),dfs.heartbeat.interval设置为3(秒,默认),则总的超时时间为40秒。 <property> <name>heartbeat.recheck.interval</name> <value>2000</value> </property> <property> <name>dfs.heartbeat.interval</name> <value>1</value> </property><file_sep>/hadoop/hadoop.md # 完整hadoop分布式 ### 准备工作 虚拟机 hadoop 用户 visudo yum install -y (vim net-tools) /home/hadoop 下有 hadoop.gz jdk.gz systemctl stop firewalld 作为namenode 克隆三个作为datanode ### 开始配置 配置namenode为伪分布式参照上一篇 [环境搭建](http://taojiawen.github.io/hadoop/config) vim ~/hadoop-2.7.3/etc/hadoop/slaves 加入datanode ip地址 datanode同样配置为单节点hadoop 只要 datanode 路径与 namenode 一致 可以 scp -r 想传的文件 用户名@ip地址:目标地址 把namenode的配置传给DataNode sudo vim /etc/hosts 把ip namenode ip datanode(datanode别名需要不同) 写入 此时就可以在namenode开启datanode的dfs和yarn 但是需要反复输入密码 so ssh-keygen生成密钥(过程回车即可) ssh-copy-id 用户名@IP地址 把公钥发给datanode ssh-copy-id localhost 设置本地免密 到这里已经生成并追加完成 ps authorized_keys:存放远程免密登录的公钥,主要通过这个文件记录多台机器的公钥 id_rsa : 生成的私钥文件 id_rsa.pub : 生成的公钥文件 know_hosts : 已知的主机公钥清单 ![1.jpg](https://upload-images.jianshu.io/upload_images/14465950-db7a7be76e591951.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) <file_sep>/hadoop/mapreduce6.md # join ## reduce端的join #### 将关联的添加作为map端的key,将两表满足join条件的数据并携带来源发往一个reducetask,在reduce中进行数据串联 #### 实例:获取商品的完整数据 * 商品goods表:goodsId goodsname stockcount(库存) .. ![image.png](https://upload-images.jianshu.io/upload_images/14466577-a4fcb67255f1aa25.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) * 订单order表:orderId .. goodsId count(购买数量) ![image.png](https://upload-images.jianshu.io/upload_images/14466577-69345206ed8b24dc.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) #### JoinBean类 因为创建一个完整信息,所以表中属性同时包括order,good两表中所有的属性,而且为基本javabean类 输出需要toString() 因为之后要用到reduce,需要用到序列化与反序列化,进行文件的存入与读取,类还作为key,所以只实现Writable接口就好 ![image.png](https://upload-images.jianshu.io/upload_images/14466577-e5e7e1a9864cd071.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![image.png](https://upload-images.jianshu.io/upload_images/14466577-544dba00d5eda8bf.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 根据map和reduce端需要创建的方法 ![image.png](https://upload-images.jianshu.io/upload_images/14466577-bc3a5cb2e817a5ad.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) #### mapper区 ![image.png](https://upload-images.jianshu.io/upload_images/14466577-b71e10fd6d136c2c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 结果:goodsId-order:1-多 goodsId-goods:1-1 ![image.png](https://upload-images.jianshu.io/upload_images/14466577-6225b713ddfdfdce.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![image.png](https://upload-images.jianshu.io/upload_images/14466577-5e364b352d2b30c4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) * reduce ![image.png](https://upload-images.jianshu.io/upload_images/14466577-086ca3a0302699ce.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) #### driver区 结果: ![image.png](https://upload-images.jianshu.io/upload_images/14466577-cefda1789668db70.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 总结 ![image.png](https://upload-images.jianshu.io/upload_images/14466577-1aa9b9f5e1655c35.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 缺点:reduce处理压力大,map运算负载很低,利用率不高,在reduce端容易数据倾斜 解决方法:[map端的join](https://dsm9966.github.io/notebook/mapReduce/22)<file_sep>/hive/hive1.md # hive的使用 ![TIM截图20181114101304.png](https://upload-images.jianshu.io/upload_images/14465950-a146acba8f91ce15.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181114101356.png](https://upload-images.jianshu.io/upload_images/14465950-9490206d14c42dd5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) # hive库 hive中有一个默认的库: 库名: default 库目录:hdfs://hdp20-01:9000/user/hive/warehouse 新建库: create database db_order; 库建好后,在hdfs中会生成一个库目录: hdfs://hdp20-01:9000/user/hive/warehouse/db_order.db # hive表 ## 删除表(内部表是完整删除,外部表则只删除MySQL上元文件) ![TIM截图20181113174341.png](https://upload-images.jianshu.io/upload_images/14465950-b8c1092a2a42ccbf.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 清空表 ![TIM截图20181113174319.png](https://upload-images.jianshu.io/upload_images/14465950-eac93af0d08a5c2d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 建一个内部表 ![TIM截图20181114092114.png](https://upload-images.jianshu.io/upload_images/14465950-ae960c3146820482.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 展示表结构 ![TIM截图20181114092204.png](https://upload-images.jianshu.io/upload_images/14465950-53638b9024596902.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 向表中插入数据(原文件移动到表目录下) ![TIM截图20181114102420.png](https://upload-images.jianshu.io/upload_images/14465950-151f9a5f8f09b2ac.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 向一个表内插入一样的文件自动改名 ![TIM图片20181114094357.png](https://upload-images.jianshu.io/upload_images/14465950-f014dbc937656580.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 建一个外部表 ![TIM截图20181114094807.png](https://upload-images.jianshu.io/upload_images/14465950-115885454addce38.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 无法清空外部表 ![TIM截图20181114095233.png](https://upload-images.jianshu.io/upload_images/14465950-2196413844b0fa92.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 直接创建表时引入数据(路径是存数据文件的文件夹) ![TIM截图20181114100116.png](https://upload-images.jianshu.io/upload_images/14465950-e1117dcbec0c3b2d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181114100029.png](https://upload-images.jianshu.io/upload_images/14465950-7ded49eba3d9eb78.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 不设置分割建表插入数据 ![TIM截图20181114102514.png](https://upload-images.jianshu.io/upload_images/14465950-74e026fec9f1198a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181114102919.png](https://upload-images.jianshu.io/upload_images/14465950-33e9737bd8860fbf.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 总结 ![TIM截图20181114102143.png](https://upload-images.jianshu.io/upload_images/14465950-49efe7d35f3dc149.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) # 建一个分区表 ![TIM截图20181114111359.png](https://upload-images.jianshu.io/upload_images/14465950-c4679e323ad70a1e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 直接向分区表插入数据 ![TIM截图20181114111748.png](https://upload-images.jianshu.io/upload_images/14465950-22d61b5e7010709e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 正确插入 ![TIM截图20181114112033.png](https://upload-images.jianshu.io/upload_images/14465950-4a672fe5b9b1752b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 分区表目录结构 ![TIM截图20181114112143.png](https://upload-images.jianshu.io/upload_images/14465950-7f98382dbfb1d2f0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181114112131.png](https://upload-images.jianshu.io/upload_images/14465950-ab8c8de8a03ae5b2.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 分区表方便查询 ![TIM截图20181114112546.png](https://upload-images.jianshu.io/upload_images/14465950-b4729b25ecc853e2.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181114112648.png](https://upload-images.jianshu.io/upload_images/14465950-e122e43a96e0705e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181114112817.png](https://upload-images.jianshu.io/upload_images/14465950-544e931a3150c284.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 查看表分区 ![TIM截图20181114112855.png](https://upload-images.jianshu.io/upload_images/14465950-f50c815ef238c68e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 建一个两层分区的表插入数据 ![TIM截图20181114113254.png](https://upload-images.jianshu.io/upload_images/14465950-2cc322dfa0089ae1.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181114113820.png](https://upload-images.jianshu.io/upload_images/14465950-ba4a382386475013.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181114113836.png](https://upload-images.jianshu.io/upload_images/14465950-bc1b02345984db13.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) # 修改表 ## 修改表名 ![TIM截图20181114140814.png](https://upload-images.jianshu.io/upload_images/14465950-5afe69a0264f995b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 添加表字段 ![TIM截图20181114140929.png](https://upload-images.jianshu.io/upload_images/14465950-0fd7247e8fedde61.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 修改表字段名 ![TIM截图20181114141052.png](https://upload-images.jianshu.io/upload_images/14465950-f85e89305be84d69.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 重置表字段 ![TIM截图20181114141316.png](https://upload-images.jianshu.io/upload_images/14465950-b8732a0d576b4669.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 给一个表添加分区 ### 普通表 ![TIM截图20181114141717.png](https://upload-images.jianshu.io/upload_images/14465950-c652a79f67eeefef.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### 分区表 ![TIM截图20181114142028.png](https://upload-images.jianshu.io/upload_images/14465950-6201bea8c211ecc5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 删除表分区(注意满足条件的都会删除,所以多层分区只删一个要写全条件) ![TIM截图20181114143139.png](https://upload-images.jianshu.io/upload_images/14465950-20a358e0df9ce5b9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 向表里插入一条数据(通过MapReduce) ![TIM截图20181114144344.png](https://upload-images.jianshu.io/upload_images/14465950-e24bf44d208476f9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 如果出现如下情况说明hive配置出问题了 ![TIM图片20181114144719.png](https://upload-images.jianshu.io/upload_images/14465950-224bc7a4dc7fdda7.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## insert 插入数据存储文件 ![TIM截图20181114150321.png](https://upload-images.jianshu.io/upload_images/14465950-1a0dbd2b0b0e2c6b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 通过查询其他表数据向表里插入数据 ![TIM截图20181114162418.png](https://upload-images.jianshu.io/upload_images/14465950-61b1a03b2363e9c7.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 用已有表数据建新表 ![TIM截图20181114162947.png](https://upload-images.jianshu.io/upload_images/14465950-c45d9ca0f8a088a9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 向分区表内直接插入数据报错 ![TIM截图20181114171907.png](https://upload-images.jianshu.io/upload_images/14465950-5beb2a5b05cce363.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 设置动态分区插入数据(最后一字段默认作为分区) ![TIM截图20181114172142.png](https://upload-images.jianshu.io/upload_images/14465950-b54b6555686a3249.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181114210034.png](https://upload-images.jianshu.io/upload_images/14465950-3ccd1c1aae7e88e0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) # 创建分桶表 ![TIM截图20181115113011.png](https://upload-images.jianshu.io/upload_images/14465950-8f3223048a6f7aac.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) # 错误插入 ![TIM截图20181115113501.png](https://upload-images.jianshu.io/upload_images/14465950-19e106ad47c89de3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181115113222.png](https://upload-images.jianshu.io/upload_images/14465950-c48ea3bb75a3840c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) # 设置强制分桶(分桶表多用于两个表根据一个外键分桶便于连表查询) ![TIM截图20181115113545.png](https://upload-images.jianshu.io/upload_images/14465950-c890e9efe0ca9e77.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181115113854.png](https://upload-images.jianshu.io/upload_images/14465950-05a313aa65d09f9f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181115113909.png](https://upload-images.jianshu.io/upload_images/14465950-beca5a3c89ff6c8a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 总结 ![TIM截图20181114175313.png](https://upload-images.jianshu.io/upload_images/14465950-05c162f925dfaad6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) <file_sep>/hadoop/javaHadoop.md # HDFS应用开发篇 ### HDFS的java操作 #### 搭建开发环境 1.把 hadoop-eclipse-plugin-2.7.3 插件导入eclipse目录下plugin中 (如不好用,再导入dropins 还不好用请换个workspace)成功如下图: ![TIM截图20181101201928.png](https://upload-images.jianshu.io/upload_images/14465950-94453698d9ea5beb.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![微信图片_20181101202741.png](https://upload-images.jianshu.io/upload_images/14465950-bbb15f4d750fc91b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181101203031.png](https://upload-images.jianshu.io/upload_images/14465950-f626a2739398aec2.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181101203156.png](https://upload-images.jianshu.io/upload_images/14465950-4d09f905534439b7.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181101203316.png](https://upload-images.jianshu.io/upload_images/14465950-a2f2a1d111f458ed.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181101203340.png](https://upload-images.jianshu.io/upload_images/14465950-7f6609652e75e8c4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 2.建一个Java工程 ![TIM截图20181101204007.png](https://upload-images.jianshu.io/upload_images/14465950-52469fbda8db0033.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![微信截图_20181101204052.png](https://upload-images.jianshu.io/upload_images/14465950-dc86eb40c4358cb3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) #### 现在就可以开始使用Java操作HDFS了 ### JUnit测试 单元测试 ![TIM截图20181101205301.png](https://upload-images.jianshu.io/upload_images/14465950-e2674bc27606a08c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181101205416.png](https://upload-images.jianshu.io/upload_images/14465950-3cece0582f4cee76.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181101205431.png](https://upload-images.jianshu.io/upload_images/14465950-30de9c5b471ac0ff.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181101205532.png](https://upload-images.jianshu.io/upload_images/14465950-a8a690fa039fadcf.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![TIM截图20181101205702.png](https://upload-images.jianshu.io/upload_images/14465950-6798f3417c9c86e3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 还有@before和@after 作用就是在test执行之前或之后执行<file_sep>/hadoop/mapreduce7.md ## join #### map端的join(1)(不需要reduce) #### 把小表分发到map节点缓存中,这样mapper端就可以在本地对自己的大表数据进行join,并输出最终结果,提高join操作并发度,加快处理速度 mapper区 自定义bean作为key setup()只在map初始化上执行一次,在setup中处理缓存文件,直接用本地IO读取(maptask本地工作目录下的一个小文件) ``` public class JoinMapper extends Mapper<Object, Text, MapJoinBean, NullWritable> { private MapJoinBean mapJoinBean = new MapJoinBean(); //用一个map属性存setup中获取的从表的数据 private Map<String,MapJoinBean> containMap = new HashMap<>(); //private Text keyText = new Text(); //在map之前执行一次 @Override protected void setup(Mapper<Object, Text, MapJoinBean,NullWritable>.Context context) throws IOException, InterruptedException { // TODO Auto-generated method stub //先按流读可以考虑编码问题 //Reader可以按行读 FileInputStream fileInputStream = new FileInputStream("goods.txt"); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream)); String line = null; //定义一个容器存获取的数据(map) while (StringUtils.isNotEmpty(line = bufferedReader.readLine())) { System.out.println("line" + line); String[] goods = line.split("\\s+"); MapJoinBean goodsBean = new MapJoinBean(); goodsBean.setGoods(goods[0], goods[1], goods[2]); containMap.put(goodsBean.getGoodsId(), goodsBean); } //FieldReader fieldReader = new FieldReader("goods.txt", null); } @Override protected void map(Object key, Text value, Mapper<Object, Text, MapJoinBean,NullWritable>.Context context) throws IOException, InterruptedException { // TODO Auto-generated method stub String[] vals = value.toString().split("\\s+"); mapJoinBean.setOrder(vals[0], vals[2], vals[3]); //根据goodsId找到商品进行数据填充 MapJoinBean goodsBean = containMap.get(mapJoinBean.getGoodsId()); mapJoinBean.setGoods(goodsBean.getGoodsName(), goodsBean.getStockCount()); //keyText.set(mapJoinBean.getGoodsId()); context.write(mapJoinBean,NullWritable.get()); } } ``` driver区将hdfs上数据放入缓存 ``` job.addCacheFile(new URI("hdfs://172.18.24.195:9000/input/goods.txt")); ``` ## map端的join(2)(需要reduce) bean ``` @Override public void readFields(DataInput input) throws IOException { // TODO Auto-generated method stub this.orderId = input.readInt(); this.goodsId = input.readUTF(); } @Override public void write(DataOutput output) throws IOException { // TODO Auto-generated method stub output.writeInt(this.orderId); output.writeUTF(this.goodsId); } @Override public int compareTo(MapJoinBean arg0) { // TODO Auto-generated method stub //先按orderID排序再按goodsID排序 int result = - (this.getOrderId()-arg0.getOrderId()); if (result == 0) { result = - this.getGoodsId().compareTo(arg0.getGoodsId()); } return result; } ``` mapper端 setup同(1)中的setup map 把自定义bean作为value ``` protected void map(Object key, Text value, Mapper<Object, Text, Text, MapJoinBean>.Context context) throws IOException, InterruptedException { // TODO Auto-generated method stub String[] vals = value.toString().split("\\s+"); mapJoinBean.setOrder(vals[0], vals[2], vals[3]); //根据goodsId找到商品进行数据填充 MapJoinBean goodsBean = containMap.get(mapJoinBean.getGoodsId()); mapJoinBean.setGoods(goodsBean.getGoodsName(), goodsBean.getStockCount()); keyText.set(mapJoinBean.getGoodsId()); context.write(keyText, mapJoinBean); } ``` * reducer端 ``` @Override protected void reduce(OrderInfo orderInfo, Iterable<NullWritable> arg1, Reducer<OrderInfo, NullWritable, OrderInfo, NullWritable>.Context context) throws IOException, InterruptedException { // TODO Auto-generated method stub context.write(orderInfo, NullWritable.get()); } ``` * 小结 ![image.png](https://upload-images.jianshu.io/upload_images/14466577-4368d0de22ea8d79.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) <file_sep>/hadoop/hdfs.md # HDFS基本概念篇 ## HDFS的概念和特性 首先,它是一个文件系统,用于存储文件,通过统一的命名空间——目录树来定位文件 其次,它是分布式的,由很多服务器联合起来实现其功能,集群中的服务器有各自的角色; 重要特性如下: (1)HDFS中的文件在物理上是分块存储(block),块的大小可以通过配置参数 ( dfs.blocksize)来规定, 默认大小在hadoop2.x版本中是128M,老版本中是64M (2)HDFS文件系统会给客户端提供一个统一的抽象目录树,客户端通过路径来访问文件,形如: hdfs://namenode:port/dir-a/dir-b/dir-c/file.data (3)目录结构及文件分块信息(元数据)的管理由namenode节点承担 ——namenode是HDFS集群主节点,负责维护整个hdfs文件系统的目录树,以及每一个路径(文件) 所对应的 block块信息(block的id,及所在的datanode服务器) (4)文件的各个block的存储管理由datanode节点承担 -- datanode是HDFS集群从节点,每一个block都可以在多个datanode上存储多个副本(副本数 量也可以通过参数设置dfs.replication) (5)HDFS是设计成适应一次写入,多次读出的场景,且不支持文件的修改 (注:适合用来做数据分析,并不适合用来做网盘应用,因为,不便修改,延迟大,网络开销大, 成本太高) ## HDFS的shell(命令行客户端)操作 3.1 HDFS命令行客户端使用 HDFS提供shell命令行客户端,使用方法如下: 3.2 命令行客户端支持的命令参数 [-appendToFile <localsrc> ... <dst>] [-cat [-ignoreCrc] <src> ...] [-checksum <src> ...] [-chgrp [-R] GROUP PATH...] [-chmod [-R] <MODE[,MODE]... | OCTALMODE> PATH...] [-chown [-R] [OWNER][:[GROUP]] PATH...] [-copyFromLocal [-f] [-p] <localsrc> ... <dst>] [-copyToLocal [-p] [-ignoreCrc] [-crc] <src> ... <localdst>] [-count [-q] <path> ...] [-cp [-f] [-p] <src> ... <dst>] [-createSnapshot <snapshotDir> [<snapshotName>]] [-deleteSnapshot <snapshotDir> <snapshotName>] [-df [-h] [<path> ...]] [-du [-s] [-h] <path> ...] [-expunge] [-get [-p] [-ignoreCrc] [-crc] <src> ... <localdst>] [-getfacl [-R] <path>] [-getmerge [-nl] <src> <localdst>] [-help [cmd ...]] [-ls [-d] [-h] [-R] [<path> ...]] [-mkdir [-p] <path> ...] [-moveFromLocal <localsrc> ... <dst>] [-moveToLocal <src> <localdst>] [-mv <src> ... <dst>] [-put [-f] [-p] <localsrc> ... <dst>] [-renameSnapshot <snapshotDir> <oldName> <newName>] [-rm [-f] [-r|-R] [-skipTrash] <src> ...] [-rmdir [--ignore-fail-on-non-empty] <dir> ...] [-setfacl [-R] [{-b|-k} {-m|-x <acl_spec>} <path>]|[--set <acl_spec> <path>]] [-setrep [-R] [-w] <rep> <path> ...] [-stat [format] <path> ...] [-tail [-f] <file>] [-test -[defsz] <path>] [-text [-ignoreCrc] <src> ...] [-touchz <path> ...] [-usage [cmd ...]] ### 常用命令参数介绍 -help 功能:输出这个命令参数手册 -ls 功能:显示目录信息 示例: hadoop fs -ls hdfs://hadoop-server01:9000/ 备注:这些参数中,所有的hdfs路径都可以简写 -->hadoop fs -ls / 等同于上一条命令的效果 -mkdir 功能:在hdfs上创建目录 示例:hadoop fs -mkdir -p /aaa/bbb/cc/dd -moveFromLocal 功能:从本地剪切粘贴到hdfs 示例:hadoop fs - moveFromLocal /home/hadoop/a.txt /aaa/bbb/cc/dd -moveToLocal 功能:从hdfs剪切粘贴到本地 示例:hadoop fs - moveToLocal /aaa/bbb/cc/dd /home/hadoop/a.txt --appendToFile 功能:追加一个文件到已经存在的文件末尾 示例: hadoop fs -appendToFile ./hello.txt hdfs://hadoop-server01:9000/hello.txt 可以简写为: Hadoop fs -appendToFile ./hello.txt /hello.txt -cat 功能:显示文件内容 示例:hadoop fs -cat /hello.txt -tail 功能:显示一个文件的末尾 示例:hadoop fs -tail /weblog/access_log.1 -text 功能:以字符形式打印一个文件的内容 示例:hadoop fs -text /weblog/access_log.1 -chgrp -chmod -chown 功能:linux文件系统中的用法一样,对文件所属权限 示例: hadoop fs -chmod 666 /hello.txt hadoop fs -chown someuser:somegrp /hello.txt -copyFromLocal 功能:从本地文件系统中拷贝文件到hdfs路径去 示例:hadoop fs -copyFromLocal ./jdk.tar.gz /aaa/ -copyToLocal 功能:从hdfs拷贝到本地 示例:hadoop fs -copyToLocal /aaa/jdk.tar.gz -cp 功能:从hdfs的一个路径拷贝hdfs的另一个路径 示例: hadoop fs -cp /aaa/jdk.tar.gz /bbb/jdk.tar.gz.2 -mv 功能:在hdfs目录中移动文件 示例: hadoop fs -mv /aaa/jdk.tar.gz / -get 功能:等同于copyToLocal,就是从hdfs下载文件到本地 示例:hadoop fs -get /aaa/jdk.tar.gz -getmerge 功能:合并下载多个文件 示例:比如hdfs的目录 /aaa/下有多个文件:log.1, log.2,log.3,... hadoop fs -getmerge /aaa/log.* ./log.sum -put 功能:等同于copyFromLocal 示例:hadoop fs -put /aaa/jdk.tar.gz /bbb/jdk.tar.gz.2 -rm 功能:删除文件或文件夹 示例:hadoop fs -rm -r /aaa/bbb/ -rmdir 功能:删除空目录 示例:hadoop fs -rmdir /aaa/bbb/ccc -df 功能:统计文件系统的可用空间信息 示例:hadoop fs -df -h / -du 功能:统计文件夹的大小信息 示例: hadoop fs -du -s -h /aaa/* -count 功能:统计一个指定目录下的文件节点数量 示例:hadoop fs -count /aaa/ -setrep 功能:设置hdfs中文件的副本数量 示例:hadoop fs -setrep 3 /aaa/jdk.tar.gz
90d8e6c75e76ca09ce1dcbeb9a461aebd31187d1
[ "Markdown" ]
33
Markdown
taojiawen/taojiawen.github.io
599ed54da85b7509d63227bbbcceca9283d00228
083f3e5c0e3dfa4b72758e012bcef164f1ede281
refs/heads/master
<file_sep>**Description:** A clear and concise description of what the bug is. **Expected Behavior:** A clear and concise description of what you expected to happen. **System and Software:** * Browser: * Exact URL: **Additional context** Add any other context about the problem here. <file_sep>**Pull request recommendations:** - [ ] Link to any relevant issue in the PR description. Ex: _Resolves #7, adds CI for the project_ - [ ] Provide context of changes. - [ ] Provide relevant tests for your feature or bug fix (if applicable). - [ ] Provide or update documentation for any feature added by your pull request (if applicable). - [ ] Provide a link to a staging deployment or screenshots of changes (if applicable). Thanks for contributing!
34824c2d04269cab9d41f045892b5b22914b7a69
[ "Markdown" ]
2
Markdown
gussmith23/convictionvacation
fdedfbe2c1d62f968830cf23a7ef8e7651e2abf7
5539176dcbd7e98037c2e24ca2deb3ef888f8b8e
refs/heads/main
<file_sep>import numpy as np import cv2 import sdl2 import sdl2.ext class Display: """ Wrapper library to create a quick video display using cv2 and sdl2 Args: width(int): The video width in pixels height(int): The video height in pixels Returns: None """ def __init__(self, width, height): sdl2.ext.init() self.width, self.height = width, height self.window = sdl2.ext.Window( title="SLAM", size=(width, height), position=(800, 500) ) self.window.show() self.orb = cv2.ORB_create() self.matcher = cv2.BFMatcher() self.last = None def process_frame(self, frame): """ Resize the frame from the raw size to the given width and height Args: frame(numpy.ndarray): The frame from cv2 Returns: numpy.ndarray: The resized frame """ return cv2.resize(frame, (self.width, self.height)) def find_orbs(self, frame): """ Use ORBs to find and extract the keypoints and descriptors in the frame. https://docs.opencv.org/3.4/d1/d89/tutorial_py_orb.html Args: frame(numpy.ndarray): The frame from cv2 Returns: numpy.ndarray: The resized frame """ features = cv2.goodFeaturesToTrack( image=np.mean(frame, axis=2).astype(np.uint8), maxCorners=3000, qualityLevel=0.01, minDistance=3, ) keypoints = [] for feature in features: u, v = map(lambda x: int(round(x)), feature[0]) cv2.circle(img=frame, center=(u, v), color=(0, 255, 0), radius=2) keypoint = cv2.KeyPoint(x=feature[0][0], y=feature[0][1], _size=20) keypoints.append(keypoint) return self.orb.compute(frame, keypoints) def find_matches(self, descriptors): """ Use the Orb descriptors to match discovered features between frames in the video Args: descriptors(numpy.ndarray): The descriptors for the current frame Returns: list[cv2.DMatch]: A list of the discovered matches """ if self.last: good_matches = [] matches = self.matcher.knnMatch(descriptors, self.last["descriptors"], k=2) for m, n in matches: if m.distance < 0.75 * n.distance: good_matches.append([m]) return good_matches else: return [] def draw(self, frame): """ Open a display window and draw the frames Args: frame(numpy.ndarray): The frame from cv2 Returns: None """ resized_frame = self.process_frame(frame) keypoints, descriptors = self.find_orbs(resized_frame) matches = self.find_matches(descriptors) self.last = {"keypoints": keypoints, "descriptors": descriptors} events = sdl2.ext.get_events() for event in events: if event.type == sdl2.SDL_QUIT: exit(0) surface = sdl2.ext.pixels3d(self.window.get_surface()) surface[:, :, 0:3] = resized_frame.swapaxes(0, 1) self.window.refresh() <file_sep>appdirs==1.4.4 black==20.8b1 certifi==2020.6.20 click==7.1.2 mypy-extensions==0.4.3 numpy==1.19.4 opencv-python==4.4.0.46 pathspec==0.8.0 PySDL2==0.9.7 regex==2020.10.28 toml==0.10.2 typed-ast==1.4.1 typing-extensions==3.7.4.3<file_sep># HATCH 2021 This repository gives an overview of commonly used tools and libraries for scientific analysis with python for the [HudsonAlpha tech challenge](https://hudsonalpha.org/techchallenge/). These libraries are not meant to be an exhaustive collection, rather some of the most common frameworks. The [examples](./examples) directory contains demonstration code of some of these tools and libraries. ### Typical Scientific Python Data Packages 1. Scikit - Package for data processing and machine learning. 2. Numpy - Matrix operations. 3. Pandas - Data loading and transformation. 4. Tensorflow - Tensor operations for neural networks. ### Image Processing Python Packages 1. opencv-python - Package with lots of utility functions for manipulating images and video. 2. PySDL2 - Library used to generate animations/renderings. 3. scikit-image - Commonly used image processing functions for ML applications. ### Geographic Python Packages 1. Geopandas - Extends pandas data manipulation to geographic data 2. Shapely - Python utility to manipulate geometric data. 3. Rtree - spatial indexing for python ### Examples #### SLAM Example - [Source](https://github.com/geohot/twitchslam) Use video and image processing libraries to demonstrate SLAM modeling. #### Hurricane Katrina Example - [Source](https://www.datacamp.com/community/tutorials/geospatial-data-python) Use various libraries shown here to examine data from Hurricane Katrina. #### Predicting Hurricane Path. Can we use past hurricane data to determine the path of a new hurricane? *[Source](https://arxiv.org/abs/1802.02548) *[Source](https://medium.com/@kap923/hurricane-path-prediction-using-deep-learning-2f9fbb390f18) *[Source](https://pdfs.semanticscholar.org/cb33/81448d1e79ab28796d74218a988f203b12ee.pdf)<file_sep>#!/usr/bin/env python import cv2 from src.display import Display width = 3840 // 4 height = 2160 // 4 display = Display(width, height) capture = cv2.VideoCapture("./data/production_ID_4608279.mp4") while capture.isOpened(): ret, frame = capture.read() if ret: display.draw(frame) else: break <file_sep>#!/usr/bin/env python import os from IPython.display import Image import geopandas import numpy as np import pandas as pd from shapely.geometry import Point from shapely.geometry import LineString import missingno as msn import seaborn as sns import matplotlib.pyplot as plt import geohash2 from sklearn import preprocessing from keras.preprocessing.sequence import pad_sequences from keras.optimizers import Adam from keras.models import Sequential from keras.utils import to_categorical from keras.layers.core import Dense, Dropout, Activation, Masking from keras.layers.recurrent import LSTM from keras.layers import Flatten, Embedding from tensorflow.python.client import device_lib # Verify GPU device is recognized print(device_lib.list_local_devices()) app_dir = os.path.dirname(__file__) # Read in all Atlantic hurricane data hurricanes = pd.read_csv(app_dir + '/data/atlantic_hurricanes.csv') # Create a date column and only use hurricanes since 1990 hurricanes['Date'] = pd.to_datetime(hurricanes['Date'], errors='coerce') hurricanes.dropna(inplace=True) hurricanes['year'] = hurricanes['Date'].dt.year.astype(int) hurricanes = hurricanes[hurricanes['year'] >= 1950] hurricanes = hurricanes[hurricanes['Name'] != 'Unnamed'] # ETL to make lat/long correct, and convert them to shapely points hurricanes['slug'] = hurricanes['Name'] + '-' + hurricanes['year'].astype(str) hurricanes['Long'] = 0 - hurricanes['Long'] hurricanes['coordinates'] = hurricanes[['Long', 'Lat']].values.tolist() hurricanes['coordinates'] = hurricanes['coordinates'].apply(Point) # Extract the movement speed of the hurricane as a feature hurricanes['movement_speed'] = hurricanes['Movement'].str.extract(r'(\d+)\s?[mph|MPH]') hurricanes.fillna(value=0, inplace=True) # Create geohashes from the lat/long for use in modeling geohashes = [] for index,row in hurricanes.iterrows(): latitude = row['coordinates'].x longitude = row['coordinates'].y geohash = geohash2.encode( latitude=latitude, longitude=longitude, precision=5 ) geohashes.append(geohash) hurricanes['geohash'] = geohashes n_classes = len(set(hurricanes['geohash'])) label_encoder = preprocessing.LabelEncoder() min_max_scaler = preprocessing.MinMaxScaler() # Encode the geohash labels as integers hurricanes['encoded_label'] = label_encoder.fit_transform(hurricanes['geohash']) features = ['Lat', 'Long', 'Wind', 'Pres', 'movement_speed'] label = 'encoded_label' test_slug = 'Katrina-2005' # Scale the input data between 0-1 for feature in features: values = hurricanes[feature].values hurricanes[feature] = min_max_scaler.fit_transform( values.reshape(-1, 1) ) pre_train_x = [] pre_train_y = [] pre_test_x = [] pre_test_y = [] # Create tensors of the feature and labels for name, group in hurricanes.groupby('slug'): temp_df = hurricanes[hurricanes['slug'] == name] if name == test_slug: pre_test_x.append(temp_df[features].to_numpy()) pre_test_y.append(temp_df[label].to_numpy()) if len(temp_df) >= 40: pre_train_x.append(temp_df[features].to_numpy()) pre_train_y.append(temp_df[label].to_numpy()) # All of the hurricanes paths need to be the same length # We can use a kera tool to do this. def pad_sequence(data): padded = pad_sequences( sequences=data, maxlen=50, dtype='object', padding='post', truncating='pre', value=0.0 ) return padded.astype('float32') # Build the layer structures of the RNN def build_structure(): model = Sequential() model.add(LSTM( units=1000, input_shape=(50, 5), activation='tanh', recurrent_activation='hard_sigmoid', return_sequences=True, dropout=0.2, recurrent_dropout=0.2 )) model.add(LSTM( units=500, input_shape=(50, 5), activation='tanh', recurrent_activation='hard_sigmoid', return_sequences=True, dropout=0.1, recurrent_dropout=0.1 )) model.add(LSTM( units=500, input_shape=(50, 5), activation='tanh', recurrent_activation='hard_sigmoid', return_sequences=True, dropout=0.1, recurrent_dropout=0.1 )) model.add(LSTM( units=250, input_shape=(50, 5), activation='tanh', recurrent_activation='hard_sigmoid', return_sequences=True, dropout=0.05, recurrent_dropout=0.05 )) # Output layer model.add(Dense( units=n_classes, activation='softmax' )) model.compile( loss='sparse_categorical_crossentropy', optimizer='Adagrad', metrics=['sparse_categorical_accuracy'] ) return model post_train_x = pad_sequence(data=pre_train_x) post_train_y = pad_sequence(data=pre_train_y) post_train_y = post_train_y.reshape( np.shape(pre_train_x)[0], 50, 1 ) post_test_x = pad_sequence(data=pre_test_x) post_test_y = pad_sequence(data=pre_test_y) post_test_y = post_test_y.reshape(1, 50, 1) model = build_structure() model.fit( x=post_train_x, y=post_train_y, epochs=10000, verbose=2, validation_split=0.2 ) print(np.argmax(model.predict(post_test_x), axis=-1))
5b11c9a285c928ade716db50be2cd98fcb054faf
[ "Markdown", "Text", "Python" ]
5
Markdown
scottypate/hatch-2021
2ff693564facb34765b4f99633724910f87dbab4
8501c29444cb65b9335239b7562de268507d609b
refs/heads/master
<repo_name>ionmx/IonD3.js<file_sep>/IonD3.js var IonD3 = IonD3 || {}; IonD3.Utils = {} IonD3.Utils.mergeProperties = function(a, b) { for (var prop in b) { a[prop] = b[prop]; } } IonD3.Utils.sumRow = function(row) { var sum = 0; row.map(function(value, index) { sum += value; }); return sum; } IonD3.Stacked = function(e) { var element_id = e; var data = []; var options = { barWidth: 20, barSpacing: 10 }; IonD3.Stacked.prototype.draw = function(_data, _options) { data = _data; IonD3.Utils.mergeProperties(options, _options); var headers = data.shift(); var y_labels = []; data.map(function(value, index) { y_labels.push(data[index].shift()); }); var columns = headers.length - 1; options.height = (options.barWidth + options.barSpacing) * data.length; var x = d3.scale.linear() .domain([0, d3.max(data, function(datum, index) { return IonD3.Utils.sumRow(datum); })]) .rangeRound([0, options.width - options.labelWidth]); var y = d3.scale.linear() .domain([0, data.length]) .range([0, options.height]); var color = d3.scale.category20(); var chart = d3.select(element_id) .append("svg") .attr("width", options.width + options.margin.left + options.margin.right) .attr("height", options.height + options.margin.top + options.margin.bottom) .append("g") .attr("transform", "translate(10,20)"); chart.selectAll("line") .data(x.ticks(10)) .enter().append("line") .attr("transform", "translate(" + options.labelWidth + ",0)") .attr("x1", x) .attr("x2", x) .attr("y1", 0) .attr("y2", options.height) .style("stroke", "#ccc"); for (var i = 0; i < columns; i++) { chart.selectAll("data_" + i) .data(data) .enter() .append("svg:rect") .attr("transform", "translate(" + options.labelWidth + ",0)") .attr("x", function(datum) { len = 0; for(var j = 0; j < i; j++) {len += datum[j]; }; return x(len); }) .attr("y", function(datum, index) { return y(index); }) .attr("width", function(datum) { return x(datum[i]); }) .attr("height", options.barWidth) .attr("class", "bar_section") .attr("fill", color(i)); chart.selectAll("data_" + i + "_label") .data(data) .enter() .append("svg:text") .attr("transform", "translate(" + options.labelWidth + ",0)") .attr("x", function(datum) { len = 0; for(var j = 0; j <= i; j++) {len += datum[j]; }; return x(len); }) .attr("y", function(datum, index) { return y(index) + options.barWidth; }) .attr("dx", -options.barWidth/2) .attr("dy", -options.barWidth/2 + 4) .attr("text-anchor", "middle") .text(function(datum) { return datum[i]; }) .attr("fill", "white"); } chart.selectAll(".rule") .data(x.ticks(20)) .enter().append("text") .attr("transform", "translate(" + options.labelWidth + ",0)") .attr("class", "rule") .attr("x", x) .attr("y", options.height) .attr("dy", 12) .attr("text-anchor", "middle") .text(String); chart.append("line") .attr("transform", "translate(" + options.labelWidth + ",0)") .attr("y1", 0) .attr("y2", options.height) .style("stroke", "#000"); chart.selectAll("text.y_labels") .data(y_labels) .enter().append("svg:text") .attr("x", options.labelWidth - 10) .attr("y", function(datum, index) { return y(index); }) //.attr("dy", options.barWidth) .attr("text-anchor", "end") .attr("style", "font-size: 12; font-family: Helvetica, sans-serif") .text(function(datum) { return datum;}) .attr("transform", "translate(0, 18)") .attr("class", "yAxis"); }; }; <file_sep>/README.md IonD3.js ======== Reusable D3 charts.
8ac6ce1e6f16d6d356fe136ebdbc206dba342741
[ "Markdown", "JavaScript" ]
2
Markdown
ionmx/IonD3.js
b6505a7c9975a77d17784d98c271833b9f852f13
1031cfb40d575a426e9fbdc478ce5c9403af0ca1
refs/heads/master
<file_sep>#include "videoModule.h" #include "SYSCall.h" #include "stdint.h" void clearScreen() { systemCall((uint64_t)WRITE, (uint64_t)CLEAR, 0, 0, 0, 0); } void deleteChar() { char d = '\b'; systemCall((uint64_t)WRITE, (uint64_t)CHARACTER,(uint64_t) &d, 0, 0, 0); } void drawBall(Color color, int radio, int x, int y){ systemCall((uint64_t)BALL, (uint64_t) &color, (uint64_t)&radio, (uint64_t)&x, (uint64_t)&y, 0); } void drawRectangle(Color color, int x, int y, int b, int h){ systemCall((uint64_t)RECTANGLE, (uint64_t)&color, (uint64_t) &b, (uint64_t)&h, (uint64_t) &x, (uint64_t)&y); } void getSize(int * x, int * y){ systemCall((uint64_t)READ, (uint64_t)SCREENSIZE, (uint64_t)x, (uint64_t)y, 0, 0); }<file_sep>#ifndef INTERRUPTIONS_H_ #define INTERRUPTIONS_H_ #include <IDTLoader.h> void _irq00Handler(void); void _irq01Handler(void); void _exception0Handler(void); void _exceptionInvalidOpcodeHandler(void); void _syscall_handler(void); void _cli(void); void _sti(void); void _hlt(void); void picMasterMask(uint8_t mask); void picSlaveMask(uint8_t mask); //Finishes CPU process. void haltcpu(void); #endif /* INTERRUPS_H_ */ <file_sep>#define ZERO_EXCEPTION_ID 0 #include <naiveConsole.h> //static void zero_division(); void exceptionDispatcher(int exception) { /* if (exception == ZERO_EXCEPTION_ID) zero_division();*/ } //static void zero_division() { // Handler para manejar excepcíon //}<file_sep>#ifndef SYSCDispatcher_H_ #define SYSCDispatcher_H_ #define READ 0 #define WRITE 1 #define WAIT 2 #define BALL 3 #define RECTANGLE 4 #define KEY 0 #define TIME 1 #define SCREENSIZE 2 #define CHARACTER 0 #define DRAWCHAR 1 #define CLEAR 2 #define HOUR 0 #define MINUTE 1 #define SECOND 2 void syscallDispatcher(uint64_t syscall, uint64_t p1, uint64_t p2, uint64_t p3, uint64_t p4, uint64_t p5); void read(uint64_t mode, uint64_t p1, uint64_t p2); void write(uint64_t mode, uint64_t p1, uint64_t p2, uint64_t p3, uint64_t p4); void getTime(unsigned int * dest, uint64_t time); #endif <file_sep>#ifndef videoDriver_h #define videoDriver_h #include <stdint.h> /* Credit: Osdev.org user: Omarrx024 ** VESA tutorial ** */ typedef struct __attribute__((packed)) ModeInfoBlock { uint16_t ModeAttributes; uint8_t WinAAttributes; uint8_t WinBAttributes; uint16_t WinGranularity; uint16_t WinSize; uint16_t WinSegmentA; uint16_t WinSegmentB; uint32_t WinRealFctPtr; uint16_t pitch; // Bytes per ScanLine. uint16_t XResolution; uint16_t YResolution; uint8_t XcharSize; uint8_t YcharSize; uint8_t NumberOfPlanes; uint8_t BitsPerPixel; uint8_t NumberOfBanks; uint8_t MemoryModel; uint8_t BankSize; uint8_t NumberOfImagePages; uint8_t ReservedPage; uint8_t RedMaskSize; uint8_t RedMaskPosition; uint8_t GreenMaskSize; uint8_t GreenMaskPosition; uint8_t BlueMaskSize; uint8_t BlueMaskPosition; uint8_t ReservedMaskSize; uint8_t ReservedMaskPosition; uint8_t DirectColorAttributes; uint32_t PhysBasePtr; // Your LFB (Linear Framebuffer) address. uint32_t OffScreenMemOffset; uint16_t OffScreenMemSize; } Vesa; typedef struct ModeInfoBlock * vesaModeStruct; /* data type color based on RGB composition */ typedef struct Color{ uint8_t red; uint8_t green; uint8_t blue; } Color; Color getColor(int intRGB); void plotPixel(int x, int y, Color color); void drawChar(char c, int x, int y, Color color); void printChar(char c, Color color); void delChar(); void newLine(); void accomodateScreen(); void clear(); void getSize(int * x, int * y); void drawBall(Color color, int radius, int x, int y); void drawRectangle(Color color, int b, int h, int x, int y); #endif<file_sep>#ifndef TEST_H #define TEST_H void paramT(); void param(int a, int b, int c, int d, int e, int f, int g); void paramTest(int a, int b, int c, int d, int e, int f, int g); #endif<file_sep>#ifndef systemCall_h #define systemCall_h #include <stdint.h> #include "videoModule.h" #define READ 0 #define WRITE 1 #define WAIT 2 #define BALL 3 #define RECTANGLE 4 #define KEY 0 #define TIME 1 #define SCREENSIZE 2 #define CHARACTER 0 #define DRAWCHAR 1 #define CLEAR 2 #define HOUR 0 #define MINUTE 1 #define SECOND 2 #define BUFFER_SIZE 256 unsigned int systemCall(uint64_t syscall, uint64_t p1, uint64_t p2, uint64_t p3, uint64_t p4, uint64_t p5); #endif <file_sep>#ifndef STDLIB_H #define STDLIB_H #include <stdint.h> void printf(char * fmt, ...); void putChar(char c); void putDec(int i); char getChar(); char * decToStr(int num, char * buffer); void scanAndPrint(char * buffer); int strCmp(char * a, char * b); void clearBuffer(char * buffer); int abs(int n); #endif<file_sep>#include <stdint.h> #include "keyboardDriver.h" #include "videoDriver.h" #include "timeDriver.h" #include "SYSCDispatcher.h" #include "test.h" void syscallDispatcher(uint64_t syscall, uint64_t p1, uint64_t p2, uint64_t p3, uint64_t p4, uint64_t p5) { switch(syscall) { case READ: read(p1, p2, p3); break; case WRITE: write(p1, p2, p3, p4, p5); break; case WAIT: wait( *( (int*) p1) ); break; case BALL: drawBall( *((Color*) p1), *((int*)p2), *((int*) p3), *((int*) p4)); break; case RECTANGLE: drawRectangle(*((Color*) p1), *((int*) p2), *((int*) p3), *((int*) p4), *((int*) p5)); break; } } void read(uint64_t mode, uint64_t p1, uint64_t p2) { unsigned int * t = (unsigned int *) p1; char * c = (char *) p1; switch(mode) { case TIME: getTime(t, p2); break; case KEY: *c = getKey(); break; case SCREENSIZE: getSize((int*) p1, (int*) p2); break; } } void write(uint64_t mode, uint64_t p1, uint64_t p2, uint64_t p3, uint64_t p4) { Color white = {255, 255, 255}; switch(mode) { case CHARACTER: printChar(*((char*) p1), *((Color*) p2)); break; case DRAWCHAR: drawChar(*((char*) p1), *((int*) p3), *((int*) p4), *((Color*) p2)); case CLEAR: clear(); break; } } void getTime(unsigned int * t, uint64_t time) { switch(time) { case HOUR: *t = getHour(); break; case MINUTE: *t = getMinute(); break; case SECOND: *t = getSecond(); break; } }<file_sep>#include "videoDriver.h" void paramT(); void param(int a, int b, int c, int d, int e, int f, int g); void paramTest(int a, int b, int c, int d, int e, int f, int g); void paramT() { param(1, 2, 3, 4, 5, 6, 7); } void paramTest(int a, int b, int c, int d, int e, int f, int g){ Color w = {255, 255, 255}; printChar(g + 48, w); }<file_sep>GLOBAL _getKeyPress section .text _getKeyPress: push rbp mov rbp, rsp mov rax, 0h in al, 60h mov bl, al in al, 64h and al, 11111110b out 64h, al mov al, bl mov rsp, rbp pop rbp ret <file_sep>#ifndef TIMEDriverASM_h #define TIMEDriverASM_h int* _getHour(); int* _getMinute(); int* _getSecond(); #endif<file_sep>#include "timeModule.h" #include "stdint.h" #include "SYSCall.h" unsigned int getHour() { unsigned int t; systemCall((uint64_t)READ, (uint64_t)TIME, (uint64_t)&t, (uint64_t)HOUR, 0, 0); if (t<3) { t = 24 - t; } else t -= 3; return t; } unsigned int getMinute() { unsigned int t; systemCall((uint64_t)READ, (uint64_t)TIME, (uint64_t)&t, (uint64_t)MINUTE, 0, 0); return t; } unsigned int getSecond() { unsigned int t; systemCall((uint64_t)READ, (uint64_t)TIME, (uint64_t)&t, (uint64_t)SECOND, 0, 0); return t; } void wait(int n) { systemCall((uint64_t) WAIT, (uint64_t) &n, 0, 0, 0, 0); }<file_sep>#include <keyboardDriver.h> char SHIFT_ON = 0; char CAPSLOCK_ON = 0; int size = 0; char buffer[BUFFER_SIZE] = {0}; int index = 0; int getIndex = 0; static unsigned char keys[] = { 0, ESC, '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=', BACKSPACE,TAB, 'q', 'w','e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '[', ']', ENTER, 0,'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', '\'', 0, LEFT_SHIFT,'\\','z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '/', RIGHT_SHIFT, '*', LEFT_ALT,SPACE, CAPSLOCK,F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, NUM_LOCK, SCROLL_LOCK,HOME, UP, REPAG,'-', LEFT, 0, RIGHT, '+', END, DOWN,AVPAG, INSERT, SUPR, 0, 0, 0, F11, F12 }; static unsigned char keysWithShift[] = { 0, ESC, '!', '@', '#', '$', '%','^', '&', '*', '(', ')', '_', '+', BACKSPACE,TAB,'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '{', '}', ENTER, 0,'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ':','"', '|', LEFT_SHIFT, '>','Z', 'X', 'C', 'V', 'B', 'N', 'M', '<', '>', '?', 0, 0,LEFT_ALT,SPACE, CAPSLOCK,F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, NUM_LOCK,SCROLL_LOCK,HOME, UP, REPAG, '-', LEFT, 0, RIGHT, '+', END, DOWN,AVPAG, INSERT, SUPR, 0, 0, '>', F11, F12 }; void keyboardHandler() { unsigned char scanCode = _getKeyPress(); unsigned char ascii; switch(scanCode) { case LEFT_SHIFT_SC: SHIFT_ON = 1; break; case RIGHT_SHIFT_SC: SHIFT_ON = 1; break; case CAPSLOCK_SC: CAPSLOCK_ON = !CAPSLOCK_ON; } if (isNotPressed(scanCode)) { //shift is released if (scanCode == LEFT_SHIFT_RELEASE || scanCode == RIGHT_SHIFT_RELEASE) { SHIFT_ON = 0; } return; } if((SHIFT_ON && CAPSLOCK_ON) || (!SHIFT_ON && !CAPSLOCK_ON)) ascii = keys[scanCode]; else { ascii = keysWithShift[scanCode]; } addToBuffer(ascii); } void addToBuffer(unsigned char ascii) { buffer[index % BUFFER_SIZE] = ascii; index++; if (size < BUFFER_SIZE) size++; } int isNotPressed(unsigned char c) { return ( c & 0x80 );//return 1 if first bit is 1 } unsigned char getKey() { if (size <= 0) { return 0; } unsigned char key = buffer[getIndex%BUFFER_SIZE]; getIndex++; size--; return key; } <file_sep>#include "shell.h" #include "stdlib.h" #include <stdint.h> #include "timeModule.h" #include "videoModule.h" #include "pongModule.h" void initShell(){ printf("~~Welcome to lenias shell, es una cagada %d/%d~~\n\n\n", 0, 10); int on = 1; char command[MAXLEN]; while (on){ printf("$> "); clearBuffer(command); scanAndPrint(command); int com = getCommand(command); switch(com) { case HELP: help(); break; case CLEAR: clear(); break; case TIME: time(); break; case PONG: pong(); printf("lenia te amo\n"); break; case ZERODIV: zeroDiv(); break; case INVOPCODE: invOpCode(); break; case LENIA: lenia(); break; case EXIT: exit(); break; case INVCOM: invCom(); } } printf("\n\n killme"); } int getCommand(char * command) { if (!strCmp("help", command)) return HELP; if (!strCmp("clear", command)) return CLEAR; if (!strCmp("time", command)) return TIME; if (!strCmp("pong", command)) return PONG; if (!strCmp("zerodiv", command)) return ZERODIV; if (!strCmp("invopcode", command)) return INVOPCODE; if (!strCmp("lenia", command)) return LENIA; if (!strCmp("exit", command)) return EXIT; return INVCOM; } void help() { printf("\n******** Help Menu ********\n"); printf(" * clear : Clears screen\n"); printf(" * pong : Iniciates pong when user presses 'enter' which will run until\n"); printf(" end of game or until user presses 'backspace' to leave\n"); printf(" * invopcode : Executes Invalid OP Code Interruption\n"); printf(" * zerodiv : Executes Zero Division Interruption\n"); printf(" * exit : Exits shell\n"); printf(" * lenia : IMPRIME BOLA\n"); printf(" * time : Displays current time\n"); printf("\n Any other command will be taken as invalid\n\n"); } void clear() { clearScreen(); printf("~~Welcome tooo Lenia's Shell~~\n\n\n"); } void time(){ unsigned int h = getHour(); unsigned int m = getMinute(); unsigned int s = getSecond(); printf("\nLocal Time: %d:%d:%d\n", h, m, s); } void pong() { startPong(); clear(); initShell(); return; } void zeroDiv() { } void invOpCode() { } void lenia() { Color b = {0, 0, 255}; printf("\nlenia te amo <3\n"); wait(10); printf("\n<<<<<<<<<<<<<<<<<<<<<<3333333333333333\n"); /*drawBall(100, 150, 200); drawBall(150, 150, 400); //drawRectangle(512, 260, 30, 60); int x; int y; getSize(&x, &y); printf("\nX res: %d\nY res: %d\n", x, y); drawBall(50, x/2, y/2);*/ } void exit() { //on = 0; } void invCom() { printf("\nInvalid command\n"); }<file_sep>#include "timeDriver.h" #include "timeDriverASM.h" #include "videoDriver.h" static unsigned long ticks = 0; Color w ={255, 255, 255}; void timeHandler() { ticks++; /*Color w = {255, 255, 255}; printChar((ticks%10) + 48, w);*/ } static unsigned long ticksElapsed() { unsigned long t = ticks; return t; } void wait(int n) { _sti(); unsigned long t = ticksElapsed() + n; while(ticksElapsed() < t); } unsigned int getHour() { unsigned int t = _getHour(); return t; } unsigned int getMinute() { unsigned int t = _getMinute(); return t; } unsigned int getSecond() { unsigned int t = _getSecond(); return t; }<file_sep>#include "stdint.h" #include <SYSCall.h> #include <stdarg.h> #include <stdlib.h> char buffer[BUFFER_SIZE] = {0}; void printf(char * fmt, ...) { va_list args; va_start(args, fmt); int aux; char * str; while(*fmt) { if (*fmt != '%') { putChar(*fmt); } else { switch(*(fmt+1)) { case 'd': aux = va_arg(args, int); putDec(aux); break; case 's': str = va_arg(args, char *); while(*str){ putChar(*str); str++; } break; case 'c': aux = va_arg(args, char); putChar(aux); break; } fmt++; } fmt++; } va_end(args); } void putChar(char c) { Color white = {255, 255, 255}; systemCall((uint64_t)WRITE, (uint64_t)CHARACTER, (uint64_t) &c, (uint64_t) &white, 0, 0); } void putDec(int i) { char buffer[11] = {0}; char * b = decToStr(i, buffer); printf(b); } char * decToStr(int num, char * buffer) { char const digit[] = "0123456789"; char* p = buffer; if(num<0){ *p++ = '-'; num *= -1; } int shifter = num; do{ //Move to where representation ends ++p; shifter = shifter/10; }while(shifter); *p = '\0'; do{ //Move back, inserting digits as u go *--p = digit[num%10]; num = num/10; }while(num); return buffer; } char getChar() { char c; systemCall((uint64_t)READ,(uint64_t) KEY, (uint64_t)&c, 0, 0, 0); return c; } void scanAndPrint(char * buffer) { char c; char * p = buffer; int idx = 0; while((c = getChar()) != '\n') { if (c>0) { if (c == '\b' && idx > 0) { deleteChar(); p--; idx--; } else if (c!='\b'){ putChar(c); *p = c; p++; idx++; } } } *p = 0; } void clearBuffer(char * buffer) { char * b = buffer; while (*b) { *b = 0; b++; } } int strCmp(char * a, char * b) { while (*a && *b) { if (*a > *b) return 1; if (*a < *b) return -1; a++; b++; } if (*a) return 1; if (*b) return -1; return 0; } int abs(int n) { if (n>0) return n; return -n; }<file_sep>//#include <time.h> #include <stdint.h> #include <keyboardDriver.h> #include <videoDriver.h> #include <naiveConsole.h> #include <timeDriver.h> void int20(void); void int21(void); void irqDispatcher(uint64_t irq) { switch (irq) { case 0: int20(); //timer tick interruption break; case 1: int21(); //keyboard interruption break; } return; } void int20() { timeHandler(); } void int21() { keyboardHandler(); }<file_sep>#include "pongModule.h" #include "videoModule.h" #include "stdlib.h" #include "timeModule.h" int xResolution; int yResolution; Color white = {255, 255, 255}; Color black = {0, 0, 0}; void startPong() { getSize(&xResolution, &yResolution); Player p1; Player p2; Ball ball; p1->pos = yResolution/2; p1->side = 0; p1->points = 0; p2->pos = yResolution/2; p2->side = 1; p2->points = 0; ball->posX = xResolution/2; ball->posY = yResolution/2; ball->dirX = 10; ball->dirY = 17; char c; printInitScreen(ball, p1, p2); while(c = getChar() != '\n' && c != '\b'){ if (c == '\b') { clearScreen(); return; } } int exitStatus = play(ball, p1, p2); if (exitStatus == 0) { clearScreen(); return; } //printWinScreen(exitStatus); clearScreen(); return; } int play(Ball ball, Player p1, Player p2) { int playing = 1; int exitStatus = 0; while (playing) { wait(2); char command = getChar(); if (command == '\b') { playing = 0; } act(command, p1, p2); int goal = moveBall(ball, p1, p2); if (goal) { scoreGoal(goal, ball, p1, p2); } } return exitStatus; return 1; } void act(char command, Player p1, Player p2) { switch(command) { case P1UP: movePlayer(p1, UP); break; case P1DOWN: movePlayer(p1, DOWN); break; case P2UP: movePlayer(p2, UP); break; case P2DOWN: movePlayer(p2, DOWN); break; } } int moveBall(Ball ball, Player p1, Player p2) { int goal = 0; printBall(black, ball); if (onEdge(ball)) { ball->dirY = -ball->dirY; } if (onGoal(ball)) { goal = 1; } if (onPlayer(ball, p1, p2)) { ball->dirX = -ball->dirX; } ball->posX += ball->dirX; ball->posY += ball->dirY; printBall(white, ball); return goal; } int onPlayer(Ball ball, Player p1, Player p2) { int touchRightX = 0; int touchLeftX = 0; int touchRightY = 0; int touchLeftY = 0; if (ball->posX + ball->dirX + 10 >= xResolution-30) { touchRightX = 1; } else if (ball->posX + ball->dirX - 10 <= 30) { touchLeftX = 1; } if (touchRightX) { if (ball->posY + ball->dirY <= p2->pos + 70 && ball->posY + ball->dirY >= p2->pos - 70) { return 1; } return 0; } else if (touchLeftX) { if (ball->posY + ball->dirY <= p1->pos + 70 && ball->posY + ball->dirY >= p1->pos - 70) { return 1; } return 0; } return 0; } int onGoal(Ball ball) { if (ball->posX + ball->dirX + 10 >= xResolution-2){ return 2; } if (ball->posX + ball->dirX - 10 <= 2){ return 1; } return 0; } void scoreGoal(int goal, Ball ball, Player p1, Player p2) { if (goal == 1) { p1->points = p1->points + 1; } else { p2->points = p2->points + 1; } p1->pos = yResolution/2; p2->pos = yResolution/2; ball->posX = xResolution/2; ball->posY = yResolution/2; ball->dirX = 10; ball->dirY = 17; printGoalScreen(goal, ball, p1, p2); return; } void printGoalScreen(int goal, Ball ball, Player p1, Player p2) { printInitScreen(ball, p1, p2); } int onEdge(Ball ball) { if (ball->posY + ball->dirY + 10 >= yResolution-2 || ball->posY + ball->dirY - 10 <= 2){ return 1; } return 0; } void movePlayer(Player p, int step) { int xPos = p->side == 0? 30 : xResolution-30; int yPos = step < 0 ? (p->pos + 70) - abs(step/2) : (p->pos - 70) + abs(step/2); drawRectangle(black, xPos, yPos, 4, abs(step/2)); yPos = step > 0 ? (p->pos + 70) - abs(step/2) + step : (p->pos - 70) + abs(step/2) + step; drawRectangle(white, xPos, yPos, 4, abs(step/2)); p->pos = p->pos + step; } void printInitScreen(Ball ball, Player p1, Player p2) { clearScreen(); printFrame(); printPlayer(white, p1); printPlayer(white, p2); printBall(white, ball); } void printPlayer(Color color, Player p) { int xPos = p->side == 0? 30 : xResolution-30; int yPos = p->pos; drawRectangle(color, xPos, yPos, 4, 70); } void printBall(Color color, Ball b) { drawBall(color, 10, b->posX, b->posY); } void printFrame() { drawRectangle(white, xResolution/2, 2, (xResolution/2 )-2, 0); drawRectangle(white, xResolution/2, yResolution-2, (xResolution/2 )-2, 0); drawRectangle(white, 2, yResolution/2, 1, (yResolution/2)-2); drawRectangle(white, xResolution-2, yResolution/2, 1, (yResolution/2)-2); } <file_sep>#ifndef VIDEOMODULE_H #define VIDEOMODULE_H #include <stdint.h> typedef struct Color{ uint8_t red; uint8_t green; uint8_t blue; } Color; void clearScreen(); void deleteChar(); void drawBall(Color color, int radio, int x, int y); void drawRectangle(Color color, int x, int y, int b, int h); void getSize(int * x, int * y); #endif<file_sep>#ifndef TIMEDriver_h #define TIMEDriver_h void timeHandler(); static unsigned long ticksElapsed(); unsigned int getHour(); unsigned int getMinute(); unsigned int getSecond(); void wait(int n); #endif<file_sep>#ifndef SHELL_H #define SHELL_H #define INVCOM 0 #define HELP 1 #define CLEAR 2 #define TIME 3 #define PONG 4 #define ZERODIV 5 #define INVOPCODE 6 #define ALEPUTO 7 #define LENIA 8 #define SHELLSHOCK 9 #define EXIT 10 #define MAXLEN 256 void initShell(); int getCommand(char * command); void help(); void clear(); void time(); void pong(); void zeroDiv(); void invOpCode(); void aleDuto(); void lenia(); void shellShock(); void exit(); void invCom(); #endif<file_sep>#define BUFFER_SIZE 256 #define LEFT_SHIFT_SC 42 #define RIGHT_SHIFT_SC 54 #define CAPSLOCK_SC 58 #define LEFT_SHIFT_RELEASE 170 #define RIGHT_SHIFT_RELEASE 182 #define CTRL 0 #define ALT 0 #define UP 11 #define RIGHT 0 #define LEFT 0 #define DOWN 10 #define ESC 0 #define BACKSPACE '\b' #define TAB 0 #define ENTER '\n' #define LEFT_SHIFT 0 #define RIGHT_SHIFT 0 #define LEFT_ALT 0 #define SPACE ' ' #define CAPSLOCK 0 #define F1 0 #define F2 0 #define F3 0 #define F4 0 #define F5 0 #define F6 0 #define F7 0 #define F8 0 #define F9 0 #define F10 0 #define F11 0 #define F12 0 #define NUM_LOCK 0 #define SCROLL_LOCK 0 #define INSERT 0 #define SUPR 0 #define HOME 0 #define END 0 #define REPAG 0 #define AVPAG 0 unsigned int _getKeyPress(); void keyboardHandler(); void addToBuffer(unsigned char c); int isNotPressed(unsigned char c); unsigned char getKey();<file_sep>#ifndef PONGMODULE_H #define PONGMODULE_H #define LEFT 0 #define RIGHT 1 #define P1UP 119 #define P1DOWN 115 #define P2UP 11 #define P2DOWN 10 #define UP -45 #define DOWN 45 #include "videoModule.h" typedef struct player{ int points; int pos; int side; } PlayerStruct; typedef struct ball{ int posX; int posY; int dirX; int dirY; } BallStruct; typedef PlayerStruct * Player; typedef BallStruct * Ball; void startPong(); int play(Ball ball, Player p1, Player p2); void printInitScreen(Ball ball, Player p1, Player p2); //void printWinScreen(int player); //void updateScreen(); void printPlayer(Color color, Player player); void printBall(Color color, Ball ball); void printGoalScreen(int goal, Ball ball, Player p1, Player p2); //void printExitScreen(); void printFrame(); void movePlayer(Player p, int step); int moveBall(Ball ball, Player p1, Player p2); int onEdge(Ball ball); int onGoal(Ball ball); int onPlayer(Ball ball, Player p1, Player p2); void scoreGoal(int goal, Ball ball, Player p1, Player p2); //void hitBall(int x, int y); void act(char com, Player p1, Player p2); #endif
0ff432b3f7a0a751fe837284745afcfe5e04ac9e
[ "Assembly", "C" ]
24
Assembly
mtarradellas/TPArqui
422eb502ee0aed76587b06a4894cad2d56bc8d00
1a97fcb5c9b19b339e0296a1d96edd5cb8c2a245
refs/heads/master
<repo_name>NordicPlayground/nrf5-ble-docomo-linking<file_sep>/examples/ble_peripheral/experimental_ble_app_linking_beacon_solar/src/sensor_beacon.c /* Copyright (c) Nordic Semiconductor ASA * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * 3. Neither the name of Nordic Semiconductor ASA nor the names of other * contributors to this software may be used to endorse or promote products * derived from this software without specific prior written permission. * * 4. This software must only be used in a processor manufactured by Nordic * Semiconductor ASA, or in a processor manufactured by a third party that * is used in combination with a processor manufactured by Nordic Semiconductor. * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "hal_radio.h" #include "hal_timer.h" #include "hal_clock.h" #include "drv_lps25h.h" #include "drv_lps25h_bitfields.h" #include "hal_serial.h" #include "hal_twi.h" #include "nrf.h" #include "ble_pdlp_beacon.h" #include "ble_pdlp_common.h" #include <stdint.h> #include <stdbool.h> #include <string.h> #include <stdlib.h> //#define DBG_RADIO_ACTIVE_ENABLE //#define DBG_BEACON_START_PIN (16) //#define DBG_HFCLK_ENABLED_PIN (27) //#define DBG_HFCLK_DISABLED_PIN (26) //#define DBG_PKT_SENT_PIN (9) //#define DBG_CALCULATE_BEGIN_PIN (15) //#define DBG_CALCULATE_END_PIN (15) //#define DBG_RADIO_ACTIVE_PIN (24) //#define DBG_WFE_BEGIN_PIN (25) //#define DBG_WFE_END_PIN (25) //#define DBG_BEACON_START \ //{ \ // NRF_GPIO->OUTSET = (1 << DBG_BEACON_START_PIN); \ // NRF_GPIO->DIRSET = (1 << DBG_BEACON_START_PIN); \ // NRF_GPIO->DIRCLR = (1 << DBG_BEACON_START_PIN); \ // NRF_GPIO->OUTCLR = (1 << DBG_BEACON_START_PIN); \ //} //#define DBG_HFCLK_ENABLED \ //{ \ // NRF_GPIO->OUTSET = (1 << DBG_HFCLK_ENABLED_PIN); \ // NRF_GPIO->DIRSET = (1 << DBG_HFCLK_ENABLED_PIN); \ // NRF_GPIO->DIRCLR = (1 << DBG_HFCLK_ENABLED_PIN); \ // NRF_GPIO->OUTCLR = (1 << DBG_HFCLK_ENABLED_PIN); \ //} //#define DBG_HFCLK_DISABLED \ //{ \ // NRF_GPIO->OUTSET = (1 << DBG_HFCLK_DISABLED_PIN); \ // NRF_GPIO->DIRSET = (1 << DBG_HFCLK_DISABLED_PIN); \ // NRF_GPIO->DIRCLR = (1 << DBG_HFCLK_DISABLED_PIN); \ // NRF_GPIO->OUTCLR = (1 << DBG_HFCLK_DISABLED_PIN); \ //} //#define DBG_PKT_SENT \ //{ \ // NRF_GPIO->OUTSET = (1 << DBG_PKT_SENT_PIN); \ // NRF_GPIO->DIRSET = (1 << DBG_PKT_SENT_PIN); \ // NRF_GPIO->DIRCLR = (1 << DBG_PKT_SENT_PIN); \ // NRF_GPIO->OUTCLR = (1 << DBG_PKT_SENT_PIN); \ //} //#define DBG_WFE_BEGIN \ //{ \ // NRF_GPIO->OUTCLR = (1 << DBG_WFE_BEGIN_PIN); \ // NRF_GPIO->DIRSET = (1 << DBG_WFE_BEGIN_PIN); \ // NRF_GPIO->OUTSET = (1 << DBG_WFE_BEGIN_PIN); \ // for ( int i = 0; i < 0xFF; i++ ) __NOP();\ // NRF_GPIO->OUTCLR = (1 << DBG_WFE_BEGIN_PIN); \ //} //#define DBG_WFE_END \ //{ \ // for ( int i = 0; i < 0xFF; i++ ) __NOP();\ // NRF_GPIO->OUTSET = (1 << DBG_WFE_END_PIN); \ // /*NRF_GPIO->DIRSET = (1 << DBG_WFE_END_PIN);*/ \ //} #ifndef DBG_BEACON_START #define DBG_BEACON_START #endif #ifndef DBG_PKT_SENT #define DBG_PKT_SENT #endif #ifndef DBG_HFCLK_ENABLED #define DBG_HFCLK_ENABLED #endif #ifndef DBG_HFCLK_DISABLED #define DBG_HFCLK_DISABLED #endif #ifndef DBG_WFE_BEGIN #define DBG_WFE_BEGIN #endif #ifndef DBG_WFE_END #define DBG_WFE_END #endif #ifdef PCA20014 static const hal_serial_cfg_t serial_cfg = { .twi0.psel.scl = 27, .twi0.psel.sda = 26, }; #else #ifdef PCA10036 static const hal_serial_cfg_t serial_cfg = { .twi0.psel.scl = 25, .twi0.psel.sda = 23, }; #else static const hal_serial_cfg_t serial_cfg = { .twi0.psel.scl = 29, .twi0.psel.sda = 25, }; #endif #endif static uint8_t M_BEACON_PDU_TYPE = LINKING_SERVICE_TYPE_TEMPERATURE; #define HFCLK_STARTUP_TIME_US (1600) /* The time in microseconds it takes to start up the HF clock*. */ #define INTERVAL_US (1000000) /* The time in microseconds between advertising events. */ #define INITIAL_TIMEOUT (INTERVAL_US) /* The time in microseconds until adverising the first time. */ #define START_OF_INTERVAL_TO_SENSOR_READ_TIME_US (INTERVAL_US / 2) /* The time from the start of the latest advertising event until reading the sensor. */ #define SENSOR_SKIP_READ_COUNT (10) /* The number of advertising events between reading the sensor. */ #if INITIAL_TIMEOUT - HFCLK_STARTUP_TIME_US < 400 #error "Initial timeout too short!" #endif #define BD_ADDR_OFFS (3) /* BLE device address offest of the beacon advertising pdu. */ #define M_BD_ADDR_SIZE (6) /* BLE device address size. */ /* Begin - Definitions for beacons with both temperature and pressure. */ #define SINT16_TEMPERATURE_OFFS (20) /* The offset of the temperature in the beacon advertising pdu */ #define UINT32_PRESSURE_OFFS (26) /* The offset of the pressure in the beacon advertising pdu */ /* End - Definitions for beacons with both temperature and pressure. */ /* Begin - Definitions for beacons with only temperature. */ #define FLOAT32_TEMPERATURE_OFFS (36) /* The offset of the temperature in the beacon advertising pdu */ /* End - Definitions for beacons with only temperature. */ /* The beacon types. */ typedef enum { M_BEACON_PDU_TYPE_TEMP_ONLY = 0, ///< Beacon with only temperature data. M_BEACON_PDU_TYPE_TEMP_PRES, ///< Beacon with both temperature and pressure data. } m_beacon_pdu_type_t; static bool volatile m_radio_isr_called; /* Indicates that the radio ISR has executed. */ static bool volatile m_rtc_isr_called; /* Indicates that the RTC ISR has executed. */ static uint32_t m_time_us; /* Keeps track of the latest scheduled point in time. */ static uint32_t m_skip_read_counter = 0; /* Keeps track on when to read the sensor. */ static uint8_t m_adv_pdu[40]; /* The RAM representation of the advertising PDU. */ /* Initializes the beacon advertising PDU. */ static void m_beacon_pdu_init(uint8_t * p_beacon_pdu) { p_beacon_pdu[0] = 0x42; p_beacon_pdu[1] = 0; p_beacon_pdu[2] = 0; } /* Sets the BLE address field in the sensor beacon PDU. */ static void m_beacon_pdu_bd_addr_default_set(uint8_t * p_beacon_pdu) { if ( ( NRF_FICR->DEVICEADDR[0] != 0xFFFFFFFF) || ((NRF_FICR->DEVICEADDR[1] & 0xFFFF) != 0xFFFF) ) { p_beacon_pdu[BD_ADDR_OFFS ] = (NRF_FICR->DEVICEADDR[0] ) & 0xFF; p_beacon_pdu[BD_ADDR_OFFS + 1] = (NRF_FICR->DEVICEADDR[0] >> 8) & 0xFF; p_beacon_pdu[BD_ADDR_OFFS + 2] = (NRF_FICR->DEVICEADDR[0] >> 16) & 0xFF; p_beacon_pdu[BD_ADDR_OFFS + 3] = (NRF_FICR->DEVICEADDR[0] >> 24) ; p_beacon_pdu[BD_ADDR_OFFS + 4] = (NRF_FICR->DEVICEADDR[1] ) & 0xFF; p_beacon_pdu[BD_ADDR_OFFS + 5] = (NRF_FICR->DEVICEADDR[1] >> 8) & 0xFF; } else { static const uint8_t random_bd_addr[M_BD_ADDR_SIZE] = {0xE2, 0xA3, 0x01, 0xE7, 0x61, 0xF7}; memcpy(&(p_beacon_pdu[3]), &(random_bd_addr[0]), M_BD_ADDR_SIZE); } p_beacon_pdu[1] = (p_beacon_pdu[1] == 0) ? M_BD_ADDR_SIZE : p_beacon_pdu[1]; } /* Resets the sensor data of the sensor beacon PDU. */ static void m_beacon_pdu_sensor_data_reset(uint8_t * p_beacon_pdu) { // 128-bit UUID beacon static const uint8_t beacon_temp_pres[31] = { /* Entry for Flags */ 0x02, 0x01, 0x04, /* Entry for Complete List of 128-bit Service Class UUID of Linking beacon */ 0x11, 0x07, 0xCD, 0xA6, 0x13, 0x5B, 0x83, 0x50, 0x8D, 0x80,0x44, 0x40, 0xD3, 0x50, 0x01, 0x69, 0xB3, 0xB3, /* Entry for Manufacture specific data in Linking spec*/ 0x09, 0xFF, 0xE2, 0x02, // Company ID DoCoMo (0x02E2) 0x0A, 0xB1, 0x23, 0x45, // Version 0x0, VenderID 0xAB, ClassID 0x12345 0x00, 0x00 // Service data }; memcpy(&(p_beacon_pdu[3 + M_BD_ADDR_SIZE]), &(beacon_temp_pres[0]), sizeof(beacon_temp_pres)); p_beacon_pdu[1] = M_BD_ADDR_SIZE + sizeof(beacon_temp_pres); } /* Sets the sensor data of the sensor beacon PDU. */ static void m_beacon_pdu_sensor_data_set(uint8_t * p_beacon_pdu, uint16_t *p_temperature, uint16_t *p_humidity, uint16_t *p_pressure) { p_beacon_pdu[SINT16_SERVICE_DATA_OFFS] = M_BEACON_PDU_TYPE << 4; // ServiceID (4-bit) if ( M_BEACON_PDU_TYPE == LINKING_SERVICE_TYPE_TEMPERATURE) { p_beacon_pdu[SINT16_SERVICE_DATA_OFFS ] = (LINKING_SERVICE_TYPE_TEMPERATURE << 4) & 0xF0; // Up 4-bits, Service ID p_beacon_pdu[SINT16_SERVICE_DATA_OFFS ] |= (*p_temperature >> 8) & 0xF; // Low 4-bits (sign and first 3-bit of exponent) p_beacon_pdu[SINT16_SERVICE_DATA_OFFS + 1] = (*p_temperature >> 0) & 0xFF; // 4th bit of exponent and fraction M_BEACON_PDU_TYPE = LINKING_SERVICE_TYPE_HUMIDITY; // next Humidity } else if (M_BEACON_PDU_TYPE == LINKING_SERVICE_TYPE_HUMIDITY) { p_beacon_pdu[SINT16_SERVICE_DATA_OFFS ] = (LINKING_SERVICE_TYPE_HUMIDITY << 4) & 0xF0; // Up 4-bits, Service ID p_beacon_pdu[SINT16_SERVICE_DATA_OFFS ] |= (*p_humidity >> 8) & 0xF; // Low 4-bits (exponent) p_beacon_pdu[SINT16_SERVICE_DATA_OFFS + 1] = (*p_humidity >> 0) & 0xFF; // fraction M_BEACON_PDU_TYPE = LINKING_SERVICE_TYPE_AIRPRESSURE; // next Air Pressure } else if (M_BEACON_PDU_TYPE == LINKING_SERVICE_TYPE_AIRPRESSURE) { p_beacon_pdu[SINT16_SERVICE_DATA_OFFS ] = (LINKING_SERVICE_TYPE_AIRPRESSURE << 4) & 0xF0; // Up 4-bits, Service ID p_beacon_pdu[SINT16_SERVICE_DATA_OFFS ] |= (*p_pressure >> 8) & 0xF; // Low 4-bits (first 4-bit of exponent) p_beacon_pdu[SINT16_SERVICE_DATA_OFFS + 1] = (*p_pressure >> 0) & 0xFF; // 5th bit of exponent and fraction M_BEACON_PDU_TYPE = LINKING_SERVICE_TYPE_TEMPERATURE; // next Temperature } } /* Waits for the next NVIC event. */ static void __forceinline cpu_wfe(void) { DBG_WFE_BEGIN; __WFE(); __SEV(); __WFE(); DBG_WFE_END; } /* Hook for the access mode feature of the lps25h driver. */ static void cpu_sleep_hook(void) { cpu_wfe(); } /* Powers up the the lps25h device and TWI pull-up resistors. */ static void sensor_chip_powerup(void) { NRF_GPIO->OUTSET = (1 << 5) | (1 << 8); NRF_GPIO->OUTSET = (1 << 7); NRF_GPIO->DIRSET = (1 << 5) | (1 << 8); NRF_GPIO->DIRSET = (1 << 7); } /* Sets up the the lps25h device to measure temperature and pressure. */ static bool sensor_chip_measurement_setup(void) { static const drv_lps25h_cfg_t m_drv_lps25h_cfg = { .twi_id = HAL_TWI_ID_TWI0, .twi_cfg.address = (0x5C << TWI_ADDRESS_ADDRESS_Pos), .twi_cfg.frequency = (TWI_FREQUENCY_FREQUENCY_K400 << TWI_FREQUENCY_FREQUENCY_Pos), .p_sleep_hook = cpu_sleep_hook, }; if ( drv_lps25h_open(&m_drv_lps25h_cfg) == DRV_LPS25H_STATUS_CODE_SUCCESS ) { drv_lps25h_access_mode_set(DRV_LPS25H_ACCESS_MODE_CPU_INACTIVE); drv_lps25h_ctrl_reg_modify((DRV_LSP25H_CTRL_REG_PD_Active << DRV_LSP25H_CTRL_REG_PD_Pos) | (DRV_LSP25H_CTRL_REG_ODR_12HZ5 << DRV_LSP25H_CTRL_REG_ODR_Pos), 0); return ( true ); } else { (void)drv_lps25h_close(); } return ( false ); } /* Ends after measuring temperature and pressure. */ static void sensor_chip_measurement_done(void) { (void)drv_lps25h_close(); } /* Sends an advertising PDU on the given channel index. */ static void send_one_packet(uint8_t channel_index) { uint8_t i; m_radio_isr_called = false; hal_radio_channel_index_set(channel_index); hal_radio_send(m_adv_pdu); while ( !m_radio_isr_called ) { cpu_wfe(); } for ( i = 0; i < 9; i++ ) { __NOP(); } } /* Powers down the the lps25h device and TWI pull-up resistors. */ static void sensor_chip_powerdown(void) { NRF_GPIO->DIRCLR = (1 << 5) | (1 << 7) | (1 << 8); } /* Handles sensor managing. */ static void sensor_handler(uint32_t start_time_us, uint32_t retry_interval_us, uint8_t retry_count) { uint8_t status; if ( sensor_chip_measurement_setup() ) { for ( int i = 0; i < retry_count; i++ ) { m_rtc_isr_called = false; hal_timer_timeout_set(start_time_us + (i * retry_interval_us)); while ( !m_rtc_isr_called ) { cpu_wfe(); } drv_lps25h_status_reg_get(&status); if ( ((status & (DRV_LSP25H_STATUS_REG_T_DA_Available << DRV_LSP25H_STATUS_REG_T_DA_Pos)) != 0) && ((status & (DRV_LSP25H_STATUS_REG_P_DA_Available << DRV_LSP25H_STATUS_REG_P_DA_Pos)) != 0) ) { break; } } if ( ((status & (DRV_LSP25H_STATUS_REG_T_DA_Available << DRV_LSP25H_STATUS_REG_T_DA_Pos)) != 0) && ((status & (DRV_LSP25H_STATUS_REG_P_DA_Available << DRV_LSP25H_STATUS_REG_P_DA_Pos)) != 0) ) { if ( M_BEACON_PDU_TYPE == LINKING_SERVICE_TYPE_TEMPERATURE ) { int32_t temperature_milli_deg; drv_lps25h_temperature_get(&temperature_milli_deg); float f_temperature = temperature_milli_deg*0.001f; uint16_t temperature = IEEE754_Convert_Temperature(f_temperature); m_beacon_pdu_sensor_data_set(&(m_adv_pdu[0]), &temperature, NULL, NULL); } else if ( M_BEACON_PDU_TYPE == LINKING_SERVICE_TYPE_HUMIDITY ) { static float simulated_data_change = 1.0f; simulated_data_change += 1.0f; if (simulated_data_change > 10.0f) { simulated_data_change = 1.0f; } float f_humidity = 155.5f + simulated_data_change; uint16_t humidity = IEEE754_Convert_Humidity(f_humidity); m_beacon_pdu_sensor_data_set(&(m_adv_pdu[0]), NULL, &humidity, NULL); } else if ( M_BEACON_PDU_TYPE == LINKING_SERVICE_TYPE_AIRPRESSURE ) { uint32_t pressure_pa; drv_lps25h_pressure_get(&pressure_pa); float f_pressure = pressure_pa*0.01f; //Pa to hPa uint16_t pressure = IEEE754_Convert_Air_Pressure(f_pressure); m_beacon_pdu_sensor_data_set(&(m_adv_pdu[0]), NULL, NULL, &pressure); } } else { m_beacon_pdu_sensor_data_reset(&(m_adv_pdu[0])); } sensor_chip_measurement_done(); } sensor_chip_powerdown(); } /* Handles beacon managing. */ static void beacon_handler(void) { hal_radio_reset(); hal_timer_start(); m_time_us = INITIAL_TIMEOUT - HFCLK_STARTUP_TIME_US; do { if ( m_skip_read_counter == 0 ) { m_rtc_isr_called = false; hal_timer_timeout_set(m_time_us - START_OF_INTERVAL_TO_SENSOR_READ_TIME_US); while ( !m_rtc_isr_called ) { cpu_wfe(); } sensor_chip_powerup(); m_rtc_isr_called = false; hal_timer_timeout_set(m_time_us - START_OF_INTERVAL_TO_SENSOR_READ_TIME_US + 10000); while ( !m_rtc_isr_called ) { cpu_wfe(); } sensor_handler(m_time_us - START_OF_INTERVAL_TO_SENSOR_READ_TIME_US + 40000, 10000, 10); } m_skip_read_counter = ( (m_skip_read_counter + 1) < SENSOR_SKIP_READ_COUNT ) ? (m_skip_read_counter + 1) : 0; m_rtc_isr_called = false; hal_timer_timeout_set(m_time_us); while ( !m_rtc_isr_called ) { cpu_wfe(); } hal_clock_hfclk_enable(); DBG_HFCLK_ENABLED; m_rtc_isr_called = false; m_time_us += HFCLK_STARTUP_TIME_US; hal_timer_timeout_set(m_time_us); while ( !m_rtc_isr_called ) { cpu_wfe(); } send_one_packet(37); DBG_PKT_SENT; send_one_packet(38); DBG_PKT_SENT; send_one_packet(39); DBG_PKT_SENT; hal_clock_hfclk_disable(); DBG_HFCLK_DISABLED; m_time_us = m_time_us + (INTERVAL_US - HFCLK_STARTUP_TIME_US); } while ( 1 ); } int main(void) { DBG_BEACON_START; NRF_GPIO->OUTCLR = 0xFFFFFFFF; NRF_GPIO->DIRCLR = 0xFFFFFFFF; #ifdef DBG_WFE_BEGIN_PIN NRF_GPIO->OUTSET = (1 << DBG_WFE_BEGIN_PIN); NRF_GPIO->DIRSET = (1 << DBG_WFE_BEGIN_PIN); #endif hal_serial_init(&serial_cfg); hal_twi_init(); drv_lps25h_init(); m_beacon_pdu_init(&(m_adv_pdu[0])); m_beacon_pdu_bd_addr_default_set(&(m_adv_pdu[0])); m_beacon_pdu_sensor_data_reset(&(m_adv_pdu[0])); #ifdef DBG_RADIO_ACTIVE_ENABLE NRF_GPIOTE->CONFIG[0] = (GPIOTE_CONFIG_POLARITY_Toggle << GPIOTE_CONFIG_POLARITY_Pos) | (DBG_RADIO_ACTIVE_PIN << GPIOTE_CONFIG_PSEL_Pos) | (GPIOTE_CONFIG_MODE_Task << GPIOTE_CONFIG_MODE_Pos); NRF_PPI->CH[5].TEP = (uint32_t)&(NRF_GPIOTE->TASKS_OUT[0]); NRF_PPI->CH[5].EEP = (uint32_t)&(NRF_RADIO->EVENTS_READY); NRF_PPI->CH[6].TEP = (uint32_t)&(NRF_GPIOTE->TASKS_OUT[0]); NRF_PPI->CH[6].EEP = (uint32_t)&(NRF_RADIO->EVENTS_DISABLED); NRF_PPI->CHENSET = (PPI_CHEN_CH5_Enabled << PPI_CHEN_CH5_Pos) | (PPI_CHEN_CH6_Enabled << PPI_CHEN_CH6_Pos); #endif for (;;) { beacon_handler(); } } void RADIO_IRQHandler(void) { NRF_RADIO->EVENTS_DISABLED = 0; m_radio_isr_called = true; } void RTC0_IRQHandler(void) { NRF_RTC0->EVTENCLR = (RTC_EVTENCLR_COMPARE0_Enabled << RTC_EVTENCLR_COMPARE0_Pos); NRF_RTC0->INTENCLR = (RTC_INTENCLR_COMPARE0_Enabled << RTC_INTENCLR_COMPARE0_Pos); NRF_RTC0->EVENTS_COMPARE[0] = 0; m_rtc_isr_called = true; } <file_sep>/examples/ble_peripheral/experimental_ble_app_linking_beacon_solar/external/comp_generic/hal/inc/hal_serial.h /* Copyright (c) Nordic Semiconductor ASA * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * 3. Neither the name of Nordic Semiconductor ASA nor the names of other * contributors to this software may be used to endorse or promote products * derived from this software without specific prior written permission. * * 4. This software must only be used in a processor manufactured by Nordic * Semiconductor ASA, or in a processor manufactured by a third party that * is used in combination with a processor manufactured by Nordic Semiconductor. * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef HAL_SERIAL_H__ #define HAL_SERIAL_H__ #if !(defined(SYS_CFG_USE_SPI0) || defined(SYS_CFG_USE_TWI0) || defined(SYS_CFG_USE_SPI1) || defined(SYS_CFG_USE_TWI1)) #include "sys_cfg.h" #endif #include <stdint.h> #include <stdbool.h> #ifdef SYS_CFG_USE_SPI0 void hal_serial_spi0_isr_handler(void); #endif #ifdef SYS_CFG_USE_SPI1 void hal_serial_spi1_isr_handler(void); #endif #ifdef SYS_CFG_USE_TWI0 void hal_serial_twi0_isr_handler(void); #endif #ifdef SYS_CFG_USE_TWI1 void hal_serial_twi1_isr_handler(void); #endif /**@brief The spi pin configuration. */ typedef struct { uint32_t sck : 6; uint32_t mosi : 6; uint32_t miso : 6; } hal_serial_spi_psel_cfg_t; /**@brief The twi pin configuration. */ typedef struct { uint32_t scl : 6; uint32_t sda : 6; } hal_serial_twi_psel_cfg_t; /**@brief The serial configuration. */ typedef struct { #ifdef SYS_CFG_USE_SPI0 struct { hal_serial_spi_psel_cfg_t psel; } spi0; #endif #ifdef SYS_CFG_USE_SPI1 struct { hal_serial_spi_psel_cfg_t psel; } spi1; #endif #ifdef SYS_CFG_USE_TWI0 struct { hal_serial_twi_psel_cfg_t psel; } twi0; #endif #ifdef SYS_CFG_USE_TWI1 struct { hal_serial_twi_psel_cfg_t psel; } twi1; #endif } hal_serial_cfg_t; /**@brief The IDs for the serial peripherals. */ typedef enum { HAL_SERIAL_ID_NONE, #ifdef SYS_CFG_USE_TWI0 HAL_SERIAL_ID_TWI0, #endif #ifdef SYS_CFG_USE_SPI0 HAL_SERIAL_ID_SPI0, #endif #ifdef SYS_CFG_USE_TWI1 HAL_SERIAL_ID_TWI1, #endif #ifdef SYS_CFG_USE_SPI1 HAL_SERIAL_ID_SPI1, #endif } hal_serial_id_t; /**@brief Inits the serial peripheral core. */ void hal_serial_init(hal_serial_cfg_t const * const cfg); /**@brief Acquires a specified peripheral. * * @param{in] id The id of the HW peripheral to acquire. */ bool hal_serial_id_acquire(hal_serial_id_t id); /**@brief Releases a previously acquired peripheral identified by the specified ID. * * @param{in] id The id of the HW peripheral to release. */ bool hal_serial_id_release(hal_serial_id_t id); #endif // HAL_SERIAL0_H__ <file_sep>/examples/ble_peripheral/experimental_ble_app_linking_beacon_solar/inc/drv_lps25h.h /* Copyright (c) Nordic Semiconductor ASA * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * 3. Neither the name of Nordic Semiconductor ASA nor the names of other * contributors to this software may be used to endorse or promote products * derived from this software without specific prior written permission. * * 4. This software must only be used in a processor manufactured by Nordic * Semiconductor ASA, or in a processor manufactured by a third party that * is used in combination with a processor manufactured by Nordic Semiconductor. * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef DRV_LPS25H_H__ #define DRV_LPS25H_H__ #include "hal_twi.h" /**@brief The sx1509b status codes. */ enum { DRV_LPS25H_STATUS_CODE_SUCCESS, ///< Successfull. DRV_LPS25H_STATUS_CODE_DISALLOWED, ///< Disallowed. DRV_LPS25H_STATUS_CODE_INVALID_PARAM, ///< Invalid parameter. }; /**@brief The access modes. */ typedef enum { DRV_LPS25H_ACCESS_MODE_CPU_INACTIVE, ///< The CPU is inactive while waiting for the access to complete. DRV_LPS25H_ACCESS_MODE_CPU_ACTIVE, ///< The CPU is active while waiting for the access to complete. } drv_lps25h_access_mode_t; /**@brief The type of the signal callback conveying signals from the driver. */ typedef void (*drv_lps25h_sleep_hook_t)(void); /**@brief The sx1509b configuration. */ typedef struct { hal_twi_id_t twi_id; ///< The ID of TWI master to be used for transactions. hal_twi_cfg_t twi_cfg; ///< The TWI configuration to use while the driver is opened. drv_lps25h_sleep_hook_t p_sleep_hook; ///< Pointer to a function for CPU power down to be used in the CPU inactive mode. } drv_lps25h_cfg_t; /**@brief Initializes the lps25h interface. */ void drv_lps25h_init(void); /**@brief Opens access to the lps25h driver. * * @param{in] id The id of the HW peripheral to open the driver for. * @param{in] cfg The driver configuration. * * @retval ::DRV_LPS25H_STATUS_CODE_SUCCESS if successful. * @retval ::DRV_LPS25H_STATUS_CODE_DISALLOWED if the driver could not be opened. */ uint32_t drv_lps25h_open(drv_lps25h_cfg_t const * const p_drv_lps25h_cfg); /**@brief Sets the access mode. * * @nore Reading and writing data will be blocking calls if no callback is set. * * @param{in] access_mode The mode to be used while accessing the lps25h chip. * * @return DRV_LPS25H_STATUS_CODE_SUCCESS If the call was successful. * @return DRV_LPS25H_STATUS_CODE_DISALLOWED If the call was not allowed at this time. * @return DRV_LPS25H_STATUS_CODE_INVALID_PARAM If specified mode is not compatible with the configuration. */ uint32_t drv_lps25h_access_mode_set(drv_lps25h_access_mode_t access_mode); /**@brief Gets the status register of the lps25h device. * * @param[in] p_stat_value A pointer to where the status is to be stored. * * @return DRV_LPS25H_STATUS_CODE_SUCCESS If the call was successful. * @return DRV_LPS25H_STATUS_CODE_DISALLOWED If the call was not allowed at this time. */ uint32_t drv_lps25h_status_reg_get(uint8_t *p_stat_value); /**@brief Modifies the control register of the lps25h device. * * @param[in] set_mask A mask specifying what bits to set. * @param[in] clr_mask A mask specifying what bits to clear. * * @return DRV_LPS25H_STATUS_CODE_SUCCESS If the call was successful. * @return DRV_LPS25H_STATUS_CODE_DISALLOWED If the call was not allowed at this time. * @return DRV_LPS25H_STATUS_CODE_INVALID_PARAM If specified masks overlaps. */ uint32_t drv_lps25h_ctrl_reg_modify(uint32_t set_mask, uint32_t clr_mask); /**@brief Gets the temperature in milli degrees Celcius. * * @param[in] p_temperature_milli_deg A pointer to where value of the temperature is to be stored. * * @return DRV_LPS25H_STATUS_CODE_SUCCESS If the call was successful. * @return DRV_LPS25H_STATUS_CODE_DISALLOWED If the call was not allowed at this time. */ uint32_t drv_lps25h_temperature_get(int32_t * p_temperature_milli_deg); /**@brief Gets the pressure in kilo Pascal. * * @param[in] p_pressure_pa A pointer to where value of the pressure is to be stored. * * @return DRV_LPS25H_STATUS_CODE_SUCCESS If the call was successful. * @return DRV_LPS25H_STATUS_CODE_DISALLOWED If the call was not allowed at this time. */ uint32_t drv_lps25h_pressure_get(uint32_t * p_pressure_pa); /**@brief Opens access to the lps25h driver. * * @retval ::DRV_LPS25H_STATUS_CODE_SUCCESS if successful. * @retval ::DRV_LPS25H_STATUS_CODE_DISALLOWED if the driver could not be opened. */ uint32_t drv_lps25h_close(void); #endif // DRV_LPS25H_H__ <file_sep>/README.md nrf5-ble-docomo-linking ======================= This repository contains code examples that show how to implement DoCoMo Linking BLE device on nRF5. For more information about DoCoMo Linking IoT project, please visit https://linkingiot.com/en/. Linking Spec versions --------------------- - Linking Advertise Information Format Specification, v2.0.2, 2016-08-08 - PeripheralDeviceLinkingProfile on BLE Specification, v2.0, 2016-07-25 - PeripheralDevicePropertyInformationService on BLE Specification, v2.0, 2016-07-25 - PeripheralDeviceOperationService on BLE Specification, v2.0, 2016-07-25 - PeripheralDeviceNotificationService on BLE Specification, v2.0, 2016-07-25 - PeripheralDeviceSettingOperationService on BLE Specification, v2.0, 2016-07-25 - PeripheralDeviceSensorInformationService on BLE Specification, v2.0, 2016-07-25 - Device Setting Information Format Specification, v2.0, 2016-07-25 - Operation sequence with periphral devices in use cases, v1.3, 2016-02-17 Requirements ------------ The following toolchains/devices have been used for testing and verification: - ARM: MDK-ARM version 5.18a - GCC: GCC ARM Embedded 4.9 2015q3 - nRF5 SDK version 11.0.0 - nRF52 PCA10040 with S132 v2.0.1 - nRF52 PCA20014 (Solar Beacon) - nRF51 PCA10028 with S130 v2.0.1 To compile it, clone the repository into the \nRF5_SDK_11.0.0_89a8197 folder. If you download the zip, please copy \components\ble\ble_services\experimental_ble_pdlp to "\nRF5_SDK_11.0.0_89a8197\components\ble\ble_services", and \examples\ble_peripheral\<all> to "\nRF5_SDK_11.0.0_89a8197\examples\ble_peripheral". Documentation ------------- References: - For the NTT DoCoMo Linking project device specification, please refer to https://linkingiot.com/en/developer/. - For details about the sample implementation of the Peripheral Device Link Profile (PDLP), please refer to the header file of ble_pdlp.h. About the sample application projects, - experimental_ble_app_linking_button demonstrates the PDLP profile, Property Information Service (PIS) and Operation Service (OS). Tested with DoCoMo LinkIFDemo.apk in Android SDK. - experimental_ble_app_linking_led demonstrates the PDLP profile, Property Information Service (PIS), Notification Service (NS) and Setting Operation Service (SOS). Tested with "天気予報通知" app in Google Play. - experimental_ble_app_linking_temp demonstrates the PDLP profile, Property Information Service (PIS), Sensor Information Service (SIS). Tested with "温湿度アプリ" app in Google Play. - experimental_ble_app_linking_beacon demonstrates Linking beacon with SoC temperature sensor. The implementation is based on Nordic Solar Beacon project (https://github.com/NordicSemiconductor/solar_sensor_beacon), which does not use softdevice and requires no SDK. Tested with DoCoMo LinkIFDemo.apk from Linking Android SDK. - experimental_ble_app_linking_beacon_solar demonstrates Linking beacon with Temperature and Air Pressure data from ST_LPS25H (as on PCA20014). The implementation is also based on Nordic Solar Beacon projectand tested with DoCoMo LinkIFDemo.apk from Linking Android SDK. NOTE the implementation is solely for demo purpose, so it is NOT optimized and does NOT have product quality. The sample project is NOT fully tested, due to lack of test applications on Smart Phones. The test is done with DoCoMo Linking app on Android. The "LinkingIFDemo.apk" app can be found in Linking Android SDK, available on https://linkingiot.com/en/developer/ About this project ------------------ This application is one of several applications that has been built by the support team at Nordic Semiconductor, as a demo of some particular feature or use case. It has not necessarily been thoroughly tested, so there might be unknown issues. It is hence provided as-is, without any warranty. However, in the hope that it still may be useful also for others than the ones we initially wrote it for, we've chosen to distribute it here on GitHub. The application is built to be used with the official nRF5 SDK, that can be downloaded from http://developer.nordicsemi.com/ <file_sep>/examples/ble_peripheral/experimental_ble_app_linking_beacon/deploy/src/hal_timer.c /* Copyright (c) Nordic Semiconductor ASA * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * 3. Neither the name of Nordic Semiconductor ASA nor the names of other * contributors to this software may be used to endorse or promote products * derived from this software without specific prior written permission. * * 4. This software must only be used in a processor manufactured by Nordic * Semiconductor ASA, or in a processor manufactured by a third party that * is used in combination with a processor manufactured by Nordic Semiconductor. * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "hal_timer.h" #include "hal_clock.h" #include "nrf.h" /* Converts the specified microsecond time to the closest prior RTC unit. */ static void m_convert(uint32_t time_us, uint32_t *rtc_units, uint32_t *us_units) { uint32_t u1, u2, t1, t2, t3; t1 = time_us / 15625; u1 = t1 * 512; t2 = time_us - t1 * 15625; u2 = (t2 << 9) / 15625; t3 = (((t2 << 9) - u2 * 15625) + 256) >> 9; *rtc_units = u1 + u2; *us_units = t3; } void hal_timer_start(void) { hal_clock_lfclk_enable(); NVIC_ClearPendingIRQ(RTC0_IRQn); NVIC_EnableIRQ(RTC0_IRQn); NRF_RTC0->TASKS_CLEAR = 1; NRF_RTC0->TASKS_START = 1; } void hal_timer_timeout_set(uint32_t timeout_us) { uint32_t rtc_units; uint32_t us_units; m_convert(timeout_us, &rtc_units, &us_units); (void)us_units; NRF_RTC0->CC[0] = rtc_units; NRF_RTC0->EVTENSET = (RTC_EVTENSET_COMPARE0_Enabled << RTC_EVTENSET_COMPARE0_Pos); NRF_RTC0->INTENSET = (RTC_INTENSET_COMPARE0_Enabled << RTC_INTENSET_COMPARE0_Pos); } <file_sep>/examples/ble_peripheral/experimental_ble_app_linking_beacon_solar/external/comp_generic/hal/src/hal_serial.c /* Copyright (c) Nordic Semiconductor ASA * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * 3. Neither the name of Nordic Semiconductor ASA nor the names of other * contributors to this software may be used to endorse or promote products * derived from this software without specific prior written permission. * * 4. This software must only be used in a processor manufactured by Nordic * Semiconductor ASA, or in a processor manufactured by a third party that * is used in combination with a processor manufactured by Nordic Semiconductor. * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "hal_serial.h" #include "nrf.h" #ifdef NRF51 #define SERIAL0_IRQn SPI0_TWI0_IRQn #define SERIAL0_IRQHandler SPI0_TWI0_IRQHandler #define SERIAL1_IRQn SPI1_TWI1_IRQn #define SERIAL1_IRQHandler SPI1_TWI1_IRQHandler #endif #ifdef NRF52 #define SERIAL0_IRQn SPIM0_SPIS0_TWIM0_TWIS0_SPI0_TWI0_IRQn #define SERIAL0_IRQHandler SPIM0_SPIS0_TWIM0_TWIS0_SPI0_TWI0_IRQHandler #define SERIAL1_IRQn SPIM1_SPIS1_TWIM1_TWIS1_SPI1_TWI1_IRQn #define SERIAL1_IRQHandler SPIM1_SPIS1_TWIM1_TWIS1_SPI1_TWI1_IRQHandler #endif typedef void (*hal_serial_irq_handler_t) (void); struct { hal_serial_cfg_t const * cfg; hal_serial_id_t current_id[2]; hal_serial_irq_handler_t current_handler[2]; } hal_serial; void hal_serial_init(hal_serial_cfg_t const * const cfg) { hal_serial.cfg = cfg; #if defined(SYS_CFG_USE_SPI0) || defined(SYS_CFG_USE_TWI0) NVIC_DisableIRQ(SERIAL0_IRQn); NRF_SPI0->ENABLE = (SPI_ENABLE_ENABLE_Disabled << SPI_ENABLE_ENABLE_Pos); NVIC_SetPriority(SERIAL0_IRQn, SYS_CFG_SERIAL_0_IRQ_PRIORITY); NVIC_ClearPendingIRQ(SERIAL0_IRQn); NVIC_EnableIRQ(SERIAL0_IRQn); #endif #if defined(SYS_CFG_USE_SPI1) || defined(SYS_CFG_USE_TWI1) NVIC_DisableIRQ(SERIAL1_IRQn); NRF_SPI1->ENABLE = (SPI_ENABLE_ENABLE_Disabled << SPI_ENABLE_ENABLE_Pos); NVIC_SetPriority(SERIAL1_IRQn, SYS_CFG_SERIAL_1_IRQ_PRIORITY); NVIC_ClearPendingIRQ(SERIAL1_IRQn); NVIC_EnableIRQ(SERIAL1_IRQn); #endif } bool hal_serial_id_acquire(hal_serial_id_t id) { switch ( id ) { #ifdef SYS_CFG_USE_TWI0 case HAL_SERIAL_ID_TWI0: if ( hal_serial.current_id[0] == HAL_SERIAL_ID_NONE ) { NRF_TWI0->PSELSCL = hal_serial.cfg->twi0.psel.scl; NRF_TWI0->PSELSDA = hal_serial.cfg->twi0.psel.sda; NRF_TWI0->ENABLE = (TWI_ENABLE_ENABLE_Enabled << TWI_ENABLE_ENABLE_Pos); hal_serial.current_id[0] = id; hal_serial.current_handler[0] = hal_serial_twi0_isr_handler; return ( true ); } break; #endif #ifdef SYS_CFG_USE_SPI0 case HAL_SERIAL_ID_SPI0: if ( hal_serial.current_id[0] == HAL_SERIAL_ID_NONE ) { NRF_SPI0->PSELMOSI = hal_serial.cfg->spi0.psel.mosi; NRF_SPI0->PSELMISO = hal_serial.cfg->spi0.psel.miso; NRF_SPI0->PSELSCK = hal_serial.cfg->spi0.psel.sck; NRF_SPI0->ENABLE = (SPI_ENABLE_ENABLE_Enabled << SPI_ENABLE_ENABLE_Pos); hal_serial.current_id[0] = id; hal_serial.current_handler[0] = hal_serial_spi0_isr_handler; return ( true ); } break; #endif #ifdef SYS_CFG_USE_TWI1 case HAL_SERIAL_ID_TWI1: if ( hal_serial.current_id[1] == HAL_SERIAL_ID_NONE ) { NRF_TWI1->PSELSCL = hal_serial.cfg->twi1.psel.scl; NRF_TWI1->PSELSDA = hal_serial.cfg->twi1.psel.sda; NRF_TWI1->ENABLE = (TWI_ENABLE_ENABLE_Enabled << TWI_ENABLE_ENABLE_Pos); hal_serial.current_id[1] = id; hal_serial.current_handler[1] = hal_serial_twi1_isr_handler; return ( true ); } break; #endif #ifdef SYS_CFG_USE_SPI1 case HAL_SERIAL_ID_SPI1: if ( hal_serial.current_id[1] == HAL_SERIAL_ID_NONE ) { NRF_SPI1->PSELMOSI = hal_serial.cfg->spi1.psel.mosi; NRF_SPI1->PSELMISO = hal_serial.cfg->spi1.psel.miso; NRF_SPI1->PSELSCK = hal_serial.cfg->spi1.psel.sck; NRF_SPI1->ENABLE = (SPI_ENABLE_ENABLE_Enabled << SPI_ENABLE_ENABLE_Pos); hal_serial.current_id[1] = id; hal_serial.current_handler[1] = hal_serial_spi1_isr_handler; return ( true ); } break; #endif default: break; } return ( false ); } bool hal_serial_id_release(hal_serial_id_t id) { switch ( id ) { #ifdef SYS_CFG_USE_TWI0 case HAL_SERIAL_ID_TWI0: if ( hal_serial.current_id[0] == id ) { NRF_TWI0->ENABLE = (TWI_ENABLE_ENABLE_Disabled << TWI_ENABLE_ENABLE_Pos); hal_serial.current_id[0] = HAL_SERIAL_ID_NONE; return ( true ); } break; #endif #ifdef SYS_CFG_USE_SPI0 case HAL_SERIAL_ID_SPI0: if ( hal_serial.current_id[0] == id ) { NRF_SPI0->ENABLE = (SPI_ENABLE_ENABLE_Disabled << SPI_ENABLE_ENABLE_Pos); hal_serial.current_id[0] = HAL_SERIAL_ID_NONE; return ( true ); } break; #endif #ifdef SYS_CFG_USE_TWI1 case HAL_SERIAL_ID_TWI1: if ( hal_serial.current_id[1] == id ) { NRF_TWI1->ENABLE = (TWI_ENABLE_ENABLE_Disabled << TWI_ENABLE_ENABLE_Pos); hal_serial.current_id[1] = HAL_SERIAL_ID_NONE; return ( true ); } break; #endif #ifdef SYS_CFG_USE_SPI1 case HAL_SERIAL_ID_SPI1: if ( hal_serial.current_id[1] == id ) { NRF_SPI1->ENABLE = (SPI_ENABLE_ENABLE_Disabled << SPI_ENABLE_ENABLE_Pos); hal_serial.current_id[1] = HAL_SERIAL_ID_NONE; return ( true ); } break; #endif default: break; } return ( false ); } #if defined(SYS_CFG_USE_SPI0) || defined(SYS_CFG_USE_TWI0) void SERIAL0_IRQHandler(void) { hal_serial.current_handler[0](); } #endif #if defined(SYS_CFG_USE_SPI1) || defined(SYS_CFG_USE_TWI1) void SERIAL1_IRQHandler(void) { hal_serial.current_handler[1](); } #endif <file_sep>/components/ble/ble_services/experimental_ble_pdlp/ble_pdlp.c /* Copyright (c) 2016 Nordic Semiconductor. All Rights Reserved. * * The information contained herein is property of Nordic Semiconductor ASA. * Terms and conditions of usage are described in detail in NORDIC * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. * * Licensees are granted free, non-transferable use of the information. NO * WARRANTY of ANY KIND is provided. This heading must NOT be removed from * the file. * */ #include "ble_srv_common.h" #include "sdk_common.h" #include "ble_pdlp.h" #include "nrf_log.h" #define ERROR_CHECK(err_code) \ do \ { \ if ((ble_pdls_result_code_t)err_code != PDLS_RESULT_OK) \ { \ return err_code; \ } \ } while (0) #define PARAM_UINT8_LENGTH 5 #define PARAM_UINT16_LENGTH 6 #define PARAM_UINT32_LENGTH 8 #define MAX_BLE_DATA_PACKET 5 #define MAX_BLE_CMD_PACKET_SIZE (GATT_MTU_SIZE_DEFAULT - 3) //20 #define MAX_BLE_RSP_PACKET_SIZE (GATT_MTU_SIZE_DEFAULT - 3 - 1) //19 static uint8_t m_cmd_buf[MAX_BLE_DATA_PACKET*MAX_BLE_CMD_PACKET_SIZE]; static uint8_t m_rsp_buf[MAX_BLE_DATA_PACKET*MAX_BLE_RSP_PACKET_SIZE]; static uint8_t m_current_packet = 0; static uint8_t *m_data_pos = m_cmd_buf; // Pointer where to save next BLE data packet static uint8_t m_data_size = 0; // Total PDLP data received (excluding header) static uint8_t m_pdns_param_id = PDNS_PARAM_INVALID; // PDNS current parameter id for detail fetching /**@brief PDLS service type. */ static enum { PDLS_STATE_IDLE, PDLS_STATE_WRITING, PDLS_STATE_INDICATING} m_transmit_state = PDLS_STATE_IDLE; static bool m_indication_confirmed = false; static ble_pdls_init_t m_pdlp_service; // Forward declaration static void service_reset(void); static uint32_t handle_transmit_written(ble_pdls_t * p_pdls); static ble_pdls_result_code_t PDPIS_service_handler(uint16_t msgid, uint16_t *rsp_len); static ble_pdls_result_code_t PDSIS_service_handler(ble_pdls_t * p_pdls, uint16_t msgid, uint8_t param_num, uint16_t *rsp_len); static ble_pdls_result_code_t PDNS_service_handler(ble_pdls_t * p_pdls, uint16_t msgid, uint8_t param_num, uint16_t *rsp_len); static ble_pdls_result_code_t PDSOS_service_handler(ble_pdls_t * p_pdls, uint16_t msgid, uint8_t param_num, uint16_t *rsp_len); /**@brief Function to send an Error or Cancel message to PDLP Client. * * @param[in] p_pdls PDLP Service structure. * @param[in] error_or_cancelled PDLP Error or cancel result code * @param[in] service PDLP service type * @param[in] msgid Message ID in above PDLP service * * @retval NRF_SUCCESS If BLE indication is sent successfully. Otherwise, an error code is returned. */ #define MSG_LENGTH_NACK_INDICATION 10 static uint32_t indicate_nack(ble_pdls_t * p_pdls, uint8_t error_or_cancelled, ble_pdls_service_type_t service, uint8_t msgid) { ble_gatts_hvx_params_t params; uint8_t header; uint8_t data[MSG_LENGTH_NACK_INDICATION]; uint16_t len = MSG_LENGTH_NACK_INDICATION; header = 1<<PDLS_HEADER_SOURCE_Pos; // Server indication header |= (error_or_cancelled == PDLS_RESULT_CANCEL)<<PDLS_HEADER_CANCEL_Pos; // Cancel or not header |= 0<<PDLS_HEADER_SEQNUM_Pos; // First packet header |= 1<<PDLS_HEADER_EXECUTE_Pos;// One packet only memset(&params, 0, sizeof(params)); params.type = BLE_GATT_HVX_INDICATION; params.handle = p_pdls->ind_char_handles.value_handle; data[0] = header; // service header data[1] = (uint8_t)service; data[2] = msgid & 0xFF; data[3] = msgid >> 8; data[4] = 0x01; // result data[5] = PDSOS_PARAM_RESULTCODE; data[6] = 0x01; data[7] = 0x00; data[8] = 0x00; data[9] = error_or_cancelled; params.p_data = data; params.p_len = &len; m_indication_confirmed = false; m_data_size = MSG_LENGTH_NACK_INDICATION; // To make sure service is reset after confirmation return sd_ble_gatts_hvx(p_pdls->conn_handle, &params); } /**@brief Function to send a normal message (prepared in global data structure) to PDLP Client. * * @param[in] p_pdls PDLP Service structure. * * @retval NRF_SUCCESS If BLE indication is sent successfully. Otherwise, an error code is returned. */ static uint32_t indicate_ack(ble_pdls_t * p_pdls) { ble_gatts_hvx_params_t params; uint16_t len; uint8_t data[MAX_BLE_CMD_PACKET_SIZE]; if (m_data_size > MAX_BLE_RSP_PACKET_SIZE) { // insert header data[0] = 1<<PDLS_HEADER_SOURCE_Pos; // Server indication data[0] |= 0<<PDLS_HEADER_CANCEL_Pos; // No cancel data[0] |= m_current_packet<<PDLS_HEADER_SEQNUM_Pos; data[0] |= 0<<PDLS_HEADER_EXECUTE_Pos;// Multiple packet len = MAX_BLE_RSP_PACKET_SIZE + 1; m_transmit_state = PDLS_STATE_INDICATING; } else { // insert header data[0] = 1<<PDLS_HEADER_SOURCE_Pos; // Server indication data[0] |= 0<<PDLS_HEADER_CANCEL_Pos; // No cancel data[0] |= m_current_packet<<PDLS_HEADER_SEQNUM_Pos; data[0] |= 1<<PDLS_HEADER_EXECUTE_Pos;// Last packet len = m_data_size + 1; } memset(&params, 0, sizeof(params)); params.type = BLE_GATT_HVX_INDICATION; params.handle = p_pdls->ind_char_handles.value_handle; memcpy(&data[1], m_data_pos, len-1); params.p_data = data; params.p_len = &len; m_indication_confirmed = false; return sd_ble_gatts_hvx(p_pdls->conn_handle, &params); } /**@brief Function for handling the Connect event. * * @param[in] p_pdls LED Button Service structure. * @param[in] p_ble_evt Event received from the BLE stack. */ static void on_connect(ble_pdls_t * p_pdls, ble_evt_t * p_ble_evt) { p_pdls->conn_handle = p_ble_evt->evt.gap_evt.conn_handle; } /**@brief Function for handling the Disconnect event. * * @param[in] p_pdls PDLP Service structure. * @param[in] p_ble_evt Event received from the BLE stack. */ static void on_disconnect(ble_pdls_t * p_pdls, ble_evt_t * p_ble_evt) { UNUSED_PARAMETER(p_ble_evt); p_pdls->conn_handle = BLE_CONN_HANDLE_INVALID; } /**@brief Function for handling the Indication Confirmation event. * * @param[in] p_pdls PDLP Service structure. * @param[in] p_ble_evt Event received from the BLE stack. */ static void on_confirm(ble_pdls_t * p_pdls, ble_evt_t * p_ble_evt) { if (p_pdls->conn_handle == p_ble_evt->evt.gatts_evt.conn_handle) { m_indication_confirmed = true; if (m_data_size > MAX_BLE_RSP_PACKET_SIZE) { // send next indication m_data_size -= MAX_BLE_RSP_PACKET_SIZE; m_data_pos += MAX_BLE_RSP_PACKET_SIZE; m_current_packet++; // send next indication indicate_ack(p_pdls); } else { // Either NACK or last Indication m_transmit_state = PDLS_STATE_IDLE; service_reset(); } } } /**@brief Function for handling the Indication timeout event. * * @param[in] p_pdls PDLP Service structure. * @param[in] p_ble_evt Event received from the BLE stack. */ static void on_timeout(ble_pdls_t * p_pdls, ble_evt_t * p_ble_evt) { //To-Do } /**@brief Function for handling the BLE ATT Write event. * * @param[in] p_pdls PDLP Service structure. * @param[in] p_ble_evt Event received from the BLE stack. */ static void on_write(ble_pdls_t * p_pdls, ble_evt_t * p_ble_evt) { ble_gatts_evt_write_t * p_evt_write = &p_ble_evt->evt.gatts_evt.params.write; if ((p_evt_write->handle == p_pdls->write_char_handles.value_handle) && (p_evt_write->len > 1)) { uint8_t header = p_evt_write->data[0]; if (((header>>PDLS_HEADER_SOURCE_Pos)&0x01) == 1) { indicate_nack(p_pdls, PDLS_RESULT_ERROR_NOT_SUPPORT, (ble_pdls_service_type_t)p_evt_write->data[1], p_evt_write->data[2]); return; // Wrong message, should be 0 i.e. from Client } if (((header>>PDLS_HEADER_CANCEL_Pos)&0x01) == 1) { if (m_transmit_state == PDLS_STATE_WRITING || m_transmit_state == PDLS_STATE_INDICATING) { indicate_nack(p_pdls, PDLS_RESULT_CANCEL, (ble_pdls_service_type_t)p_evt_write->data[1], p_evt_write->data[2]); } } if (((header>>PDLS_HEADER_EXECUTE_Pos)&0x01) == 0) { m_current_packet = ((header>>PDLS_HEADER_SEQNUM_Pos)&0x01F); m_transmit_state = PDLS_STATE_WRITING; // allow cancel // copy PDLP data, exclude the header memcpy(m_data_pos, p_evt_write->data + 1, p_evt_write->len - 1); m_data_pos += p_evt_write->len - 1; // pointer m_data_size += p_evt_write->len - 1; // size } else { m_current_packet = 0; // copy PDLP data, exclude the header memcpy(m_data_pos, p_evt_write->data + 1, p_evt_write->len - 1); m_data_size += p_evt_write->len - 1; handle_transmit_written(p_pdls); } } } /**@brief Function for PDLP service reset after one request/respone transaction * */ static void service_reset() { memset(m_cmd_buf, 0x00, MAX_BLE_DATA_PACKET*MAX_BLE_CMD_PACKET_SIZE); memset(m_rsp_buf, 0x00, MAX_BLE_DATA_PACKET*MAX_BLE_RSP_PACKET_SIZE); m_current_packet = 0; m_data_pos = m_cmd_buf; m_data_size = 0; m_transmit_state = PDLS_STATE_IDLE; } /**@brief Function for handling the PDLP Write done, i.e. after all messages received. * * @param[in] p_pdls PDLP Service structure. * * @retval PDLS_RESULT_OK If the message is handled successfully. Otherwise, an error code is returned. */ static uint32_t handle_transmit_written(ble_pdls_t * p_pdls) { ble_pdls_result_code_t result; ble_pdls_service_type_t service; uint16_t msgid; uint8_t param_num; uint16_t len = 0; // check service header if (m_data_size < 4) { return indicate_nack(p_pdls, (uint8_t)PDLS_RESULT_ERROR_NO_DATA, (ble_pdls_service_type_t)m_cmd_buf[0], m_cmd_buf[1]); } else { service = (ble_pdls_service_type_t)m_cmd_buf[0]; msgid = (*(m_cmd_buf+1) | *(m_cmd_buf+2)<<8); param_num = *(m_cmd_buf+3); m_data_pos = m_cmd_buf+4; // start of params buffer } // service dispatch switch (service) { case PDLS_SERVICE_PIS: result = PDPIS_service_handler(msgid, &len); break; case PDLS_SERVICE_NS: result = PDNS_service_handler(p_pdls, msgid, param_num, &len); break; case PDLS_SERVICE_SOS: result = PDSOS_service_handler(p_pdls, msgid, param_num, &len); break; case PDLS_SERVICE_SIS: result = PDSIS_service_handler(p_pdls, msgid, param_num, &len); break; case PDLS_SERVICE_OS: default: result = PDLS_RESULT_ERROR_NOT_SUPPORT; } // send ACK or NACK if (PDLS_RESULT_OK != result) { return indicate_nack(p_pdls, (uint8_t)result, (ble_pdls_service_type_t)m_cmd_buf[0], m_cmd_buf[1]); } else if (len > 0) { m_data_pos = m_rsp_buf; m_data_size = len; m_current_packet = 0; return indicate_ack(p_pdls); } return result; } /**@brief Function for adding the Write Message Characteristic. * * @param[in] p_pdls PDLP Service structure. * @param[in] p_pdls_init PDLP Service initialization structure. * * @retval NRF_SUCCESS on success, else an error value from the SoftDevice */ static uint32_t write_char_add(ble_pdls_t * p_pdls, const ble_pdls_init_t * p_pdls_init) { ble_gatts_char_md_t char_md; ble_gatts_attr_t attr_char_value; ble_uuid_t ble_uuid; ble_gatts_attr_md_t attr_md; memset(&char_md, 0, sizeof(char_md)); char_md.char_props.write = 1; char_md.p_char_user_desc = NULL; char_md.p_char_pf = NULL; char_md.p_user_desc_md = NULL; char_md.p_cccd_md = NULL; char_md.p_sccd_md = NULL; ble_uuid.type = p_pdls->uuid_type; ble_uuid.uuid = PDLS_UUID_WRITE_CHAR; memset(&attr_md, 0, sizeof(attr_md)); BLE_GAP_CONN_SEC_MODE_SET_OPEN(&attr_md.write_perm); attr_md.vloc = BLE_GATTS_VLOC_STACK; attr_md.rd_auth = 0; attr_md.wr_auth = 0; attr_md.vlen = 1; memset(&attr_char_value, 0, sizeof(attr_char_value)); attr_char_value.p_uuid = &ble_uuid; attr_char_value.p_attr_md = &attr_md; attr_char_value.init_len = sizeof(uint8_t); attr_char_value.init_offs = 0; attr_char_value.max_len = MAX_BLE_CMD_PACKET_SIZE; attr_char_value.p_value = NULL; return sd_ble_gatts_characteristic_add(p_pdls->service_handle, &char_md, &attr_char_value, &p_pdls->write_char_handles); } /**@brief Function for adding the Indicate Message Characteristic. * * @param[in] p_pdls PDLP Service structure. * @param[in] p_pdls_init PDLP Service initialization structure. * * @retval NRF_SUCCESS on success, else an error value from the SoftDevice */ static uint32_t ind_char_add(ble_pdls_t * p_pdls, const ble_pdls_init_t * p_pdls_init) { ble_gatts_char_md_t char_md; ble_gatts_attr_md_t cccd_md; ble_gatts_attr_t attr_char_value; ble_uuid_t ble_uuid; ble_gatts_attr_md_t attr_md; memset(&cccd_md, 0, sizeof(cccd_md)); BLE_GAP_CONN_SEC_MODE_SET_OPEN(&cccd_md.read_perm); BLE_GAP_CONN_SEC_MODE_SET_OPEN(&cccd_md.write_perm); cccd_md.vloc = BLE_GATTS_VLOC_STACK; memset(&char_md, 0, sizeof(char_md)); char_md.char_props.indicate = 1; char_md.p_char_user_desc = NULL; char_md.p_char_pf = NULL; char_md.p_user_desc_md = NULL; char_md.p_cccd_md = &cccd_md; char_md.p_sccd_md = NULL; ble_uuid.type = p_pdls->uuid_type; ble_uuid.uuid = PDLS_UUID_IND_CHAR; memset(&attr_md, 0, sizeof(attr_md)); BLE_GAP_CONN_SEC_MODE_SET_OPEN(&attr_md.read_perm); BLE_GAP_CONN_SEC_MODE_SET_NO_ACCESS(&attr_md.write_perm); attr_md.vloc = BLE_GATTS_VLOC_STACK; attr_md.rd_auth = 0; attr_md.wr_auth = 0; attr_md.vlen = 1; memset(&attr_char_value, 0, sizeof(attr_char_value)); attr_char_value.p_uuid = &ble_uuid; attr_char_value.p_attr_md = &attr_md; attr_char_value.init_len = sizeof(uint8_t); attr_char_value.init_offs = 0; attr_char_value.max_len = MAX_BLE_CMD_PACKET_SIZE; attr_char_value.p_value = NULL; return sd_ble_gatts_characteristic_add(p_pdls->service_handle, &char_md, &attr_char_value, &p_pdls->ind_char_handles); } /**@brief Function for handling a PDPIS request. * * @param[in] msgid PDPIS message ID. * @param[out] rsp_len Prepared response message length. * * @retval PDLS_RESULT_OK on success, else an error value */ static ble_pdls_result_code_t PDPIS_service_handler(uint16_t msgid, uint16_t *rsp_len) { // check msgid if (msgid != PDPIS_GET_DEVICE_INFORMATION) { return PDLS_RESULT_ERROR_NOT_SUPPORT; } m_data_pos = m_rsp_buf; // Prepare response, first service header m_data_pos += pdls_encode_service_header(m_data_pos, PDLS_SERVICE_PIS, PDPIS_GET_DEVICE_INFORMATION_RESP, 5); // param #1 Reult code m_data_pos += pdls_encode_param_uint8(m_data_pos, PDPIS_PARAM_RESULTCODE, PDLS_RESULT_OK); // param #2 Service List m_data_pos += pdls_encode_param_uint8(m_data_pos, PDPIS_PARAM_SERVICELIST, m_pdlp_service.servicelist); // param #3 Device ID m_data_pos += pdls_encode_param_uint16(m_data_pos, PDPIS_PARAM_DEVICEID, m_pdlp_service.deviceid); // param #4 Device Uid m_data_pos += pdls_encode_param_uint32(m_data_pos, PDPIS_PARAM_DEVICEUID, m_pdlp_service.deviceuid); // param #5 Device Capability m_data_pos += pdls_encode_param_uint8(m_data_pos, PDPIS_PARAM_DEVICECAPABILITY, m_pdlp_service.devicecapability); *rsp_len = m_data_pos - m_rsp_buf; return PDLS_RESULT_OK; } /**@brief Function for handling a PDSIS request. * * @param[in] p_pdls PDLP Service structure. * @param[in] msgid PDSIS message ID. * @param[in] param_num Number of parameters in this PDSIS message * @param[out] rsp_len Prepared response message length. * * @retval PDLS_RESULT_OK on success, else an error value */ static ble_pdls_result_code_t PDSIS_service_handler(ble_pdls_t * p_pdls, uint16_t msgid, uint8_t param_num, uint16_t *rsp_len) { ble_pdsis_event_data_t event_data; ble_pdls_result_code_t result; uint8_t paramindex = 0; // check msgid switch (msgid) { case PDSIS_GET_SENSOR_INFO: { // Check sensor type result = pdls_decode_param_uint8(m_data_pos, PDSIS_PARAM_SENSORTYPE, (uint8_t *)&event_data.type); ERROR_CHECK(result); if ((m_pdlp_service.sensortypes & (0x1<<event_data.type)) == 0) { // Sensor type not supported return PDLS_RESULT_ERROR_NOT_SUPPORT; } // Send the request to App event_data.event = PDSIS_EVT_GET_SENSOR_INFO; result = m_pdlp_service.pdsis_event_handler(p_pdls, &event_data); // Prepare response, first service header m_data_pos = m_rsp_buf; if (result == PDLS_RESULT_OK) { if (event_data.type == PDSIS_SENSOR_TYPE_GYROSCOPE || event_data.type == PDSIS_SENSOR_TYPE_ACCELEROMETER || event_data.type == PDSIS_SENSOR_TYPE_ORIENTATION ) { // Service header m_data_pos += pdls_encode_service_header(m_data_pos, PDLS_SERVICE_SIS, PDSIS_SET_NOTIFY_SENSOR_INFO_RESP, 4); // param #1 Reult code m_data_pos += pdls_encode_param_uint8(m_data_pos, PDSIS_PARAM_RESULTCODE, PDLS_RESULT_OK); // param #2 X-value m_data_pos += pdls_encode_param_uint32(m_data_pos, PDSIS_PARAM_X_VALUE, event_data.data.value.x_value); // param #3 Y-value m_data_pos += pdls_encode_param_uint32(m_data_pos, PDSIS_PARAM_Y_VALUE, event_data.data.value.y_value); // param #4 Z-value m_data_pos += pdls_encode_param_uint32(m_data_pos, PDSIS_PARAM_Z_VALUE, event_data.data.value.z_value); } if (event_data.type == PDSIS_SENSOR_TYPE_BATTERY || event_data.type == PDSIS_SENSOR_TYPE_TEMPERATURE || event_data.type == PDSIS_SENSOR_TYPE_HUMIDITY ) { // Service header m_data_pos += pdls_encode_service_header(m_data_pos, PDLS_SERVICE_SIS, PDSIS_SET_NOTIFY_SENSOR_INFO_RESP, 2); // param #1 Reult code m_data_pos += pdls_encode_param_uint8(m_data_pos, PDSIS_PARAM_RESULTCODE, PDLS_RESULT_OK); // param #2 OriginalData m_data_pos += pdls_encode_param_uint16(m_data_pos, PDSIS_PARAM_X_VALUE, event_data.data.u16_originaldata[0]); } } else { // Service header m_data_pos += pdls_encode_service_header(m_data_pos, PDLS_SERVICE_SIS, PDSIS_SET_NOTIFY_SENSOR_INFO_RESP, 1); // param #1 Reult code m_data_pos += pdls_encode_param_uint8(m_data_pos, PDSIS_PARAM_RESULTCODE, result); } *rsp_len = m_data_pos - m_rsp_buf; result = PDLS_RESULT_OK; // allow sending ACK } break; case PDSIS_SET_NOTIFY_SENSOR_INFO: { // Check sensor type result = pdls_decode_param_uint8(m_data_pos, PDSIS_PARAM_SENSORTYPE, (uint8_t *)&event_data.type); ERROR_CHECK(result); if ((m_pdlp_service.sensortypes & (0x1<<event_data.type)) == 0) { // Sensor type not supported return PDLS_RESULT_ERROR_NOT_SUPPORT; } m_data_pos += PARAM_UINT8_LENGTH; paramindex++; // Status event_data.event = PDSIS_EVT_SET_NOTIFY_INFO; result = pdls_decode_param_uint8(m_data_pos, PDSIS_PARAM_STATUS, (uint8_t *)&event_data.status); ERROR_CHECK(result); paramindex++; m_data_pos += PARAM_UINT8_LENGTH; paramindex++; // Threshold or original data switch (event_data.type) { { case PDSIS_SENSOR_TYPE_GYROSCOPE: case PDSIS_SENSOR_TYPE_ACCELEROMETER: case PDSIS_SENSOR_TYPE_ORIENTATION: result = pdls_decode_param_uint32(m_data_pos, PDSIS_PARAM_X_THRESHOLD, (uint32_t *)&event_data.data.threshold.x_threshold); ERROR_CHECK(result); m_data_pos += PARAM_UINT32_LENGTH; result = pdls_decode_param_uint32(m_data_pos, PDSIS_PARAM_Y_THRESHOLD, (uint32_t *)&event_data.data.threshold.y_threshold); ERROR_CHECK(result); m_data_pos += PARAM_UINT32_LENGTH; result = pdls_decode_param_uint32(m_data_pos, PDSIS_PARAM_Z_THRESHOLD, (uint32_t *)&event_data.data.threshold.z_threshold); ERROR_CHECK(result); break; case PDSIS_SENSOR_TYPE_BATTERY: case PDSIS_SENSOR_TYPE_TEMPERATURE: case PDSIS_SENSOR_TYPE_HUMIDITY: // optional data if (paramindex < param_num) { // set the *optional* OriginalData if needed } break; default: break; } } // Send the request to App for handling event_data.event = PDSIS_EVT_SET_NOTIFY_INFO; result = m_pdlp_service.pdsis_event_handler(p_pdls, &event_data); // Prepare response, first service header m_data_pos = m_rsp_buf; m_data_pos += pdls_encode_service_header(m_data_pos, PDLS_SERVICE_SIS, PDSIS_SET_NOTIFY_SENSOR_INFO_RESP, 1); // param #1 Reult code m_data_pos += pdls_encode_param_uint8(m_data_pos, PDSIS_PARAM_RESULTCODE, result); *rsp_len = m_data_pos - m_rsp_buf; result = PDLS_RESULT_OK; // allow sending ACK } break; default: return PDLS_RESULT_ERROR_NOT_SUPPORT; } return result; } /**@brief Function for handling a PDNS request. * * @param[in] p_pdls PDLP Service structure. * @param[in] msgid PDNS message ID. * @param[in] param_num Number of parameters in this PDNS message * @param[out] rsp_len Prepared response message length. * * @retval PDLS_RESULT_OK on success, else an error value */ static ble_pdls_result_code_t PDNS_service_handler(ble_pdls_t * p_pdls, uint16_t msgid, uint8_t param_num, uint16_t *rsp_len) { ble_pdns_event_data_t event_data; ble_pdls_result_code_t result; uint8_t paramindex = 0; pdlp_opaque_t paramdata; // check msgid switch (msgid) { case PDNS_CONFIRM_NOTIFY_CATEGORY: { // Prepare response, first service header m_data_pos = m_rsp_buf; m_data_pos += pdls_encode_service_header(m_data_pos, PDLS_SERVICE_NS, PDNS_CONFIRM_NOTIFY_CATEGORY_RESP, 2); // param #1 Reult code m_data_pos += pdls_encode_param_uint8(m_data_pos, PDNS_PARAM_RESULTCODE, PDLS_RESULT_OK); // param #2 Notify category m_data_pos += pdls_encode_param_uint16(m_data_pos, PDNS_PARAM_NOTIFYCATEGORY, m_pdlp_service.notifycategory); *rsp_len = m_data_pos - m_rsp_buf; result = PDLS_RESULT_OK; } break; case PDNS_NOTIFY_INFORMATION: { // Check notification category result = pdls_decode_param_uint16(m_data_pos, PDNS_PARAM_NOTIFYCATEGORY, (uint16_t *)&event_data.data.notifyinfo.notifycategory); ERROR_CHECK(result); if ((m_pdlp_service.notifycategory != PDNS_NOTIFY_CATEGORY_ALL) && ((m_pdlp_service.notifycategory & event_data.data.notifyinfo.notifycategory)==0)) { // Notify category not supported return PDLS_RESULT_ERROR_NOT_SUPPORT; } m_data_pos += PARAM_UINT16_LENGTH; paramindex++; // Unique ID result = pdls_decode_param_uint16(m_data_pos, PDNS_PARAM_UNIQUEID, (uint16_t *)&event_data.data.notifyinfo.uniqueid); ERROR_CHECK(result); m_data_pos += PARAM_UINT16_LENGTH; paramindex++; // Parameter ID list result = pdls_decode_param_uint16(m_data_pos, PDNS_PARAM_PARAMETERIDLIST, (uint16_t *)&event_data.data.notifyinfo.parameteridlist); ERROR_CHECK(result); m_data_pos += PARAM_UINT16_LENGTH; paramindex++; // Optional parameters while (paramindex < param_num) { switch (*m_data_pos) { case PDNS_PARAM_RUMBLINGSETTING: result = pdls_decode_param_uint8(m_data_pos, PDNS_PARAM_RUMBLINGSETTING, (uint8_t *)&event_data.data.notifyinfo.rumblingsetting); ERROR_CHECK(result); m_data_pos += PARAM_UINT8_LENGTH; paramindex++; break; case PDNS_PARAM_VABRATIONPATTERN: paramdata.p_val = event_data.data.notifyinfo.vibratiobpattern; result = pdls_decode_param_opaque(m_data_pos, PDNS_PARAM_VABRATIONPATTERN, &paramdata); ERROR_CHECK(result); m_data_pos += paramdata.len; paramindex++; break; case PDNS_PARAM_LEDPATTERN: paramdata.p_val = event_data.data.notifyinfo.ledpattern; result = pdls_decode_param_opaque(m_data_pos, PDNS_PARAM_LEDPATTERN, &paramdata); ERROR_CHECK(result); m_data_pos += paramdata.len; paramindex++; break; case PDNS_PARAM_BEEPPATTERN: paramdata.p_val = event_data.data.notifyinfo.beeppattern; result = pdls_decode_param_opaque(m_data_pos, PDNS_PARAM_BEEPPATTERN, &paramdata); ERROR_CHECK(result); m_data_pos += paramdata.len; paramindex++; break; default: paramindex++; break; } } // Send the request to App for handling event_data.event = PDNS_EVT_NOTIFY_INFO; result = m_pdlp_service.pdns_event_handler(p_pdls, &event_data); // No need of response if App return OK if ( result == PDLS_RESULT_OK) { *rsp_len = 0; } } break; case PDNS_GET_PD_NOTIFY_DETAIL_DATA_RESP: { // Check notification category if (m_pdns_param_id == PDNS_PARAM_INVALID) { // Wrong status return PDLS_RESULT_ERROR_NO_DATA; } // Result code result = pdls_decode_param_uint8(m_data_pos, PDNS_PARAM_RESULTCODE, (uint8_t *)&event_data.data.notifydetail.result); ERROR_CHECK(result); m_data_pos += PARAM_UINT8_LENGTH; // Unique ID result = pdls_decode_param_uint16(m_data_pos, PDNS_PARAM_UNIQUEID, (uint16_t *)&event_data.data.notifydetail.uniqueid); ERROR_CHECK(result); m_data_pos += PARAM_UINT16_LENGTH; if (event_data.data.notifydetail.result == PDLS_RESULT_OK) { // Parameter data //paramdata.p_val = event_data.data.notifydetail.parameterdata; result = pdls_decode_param_opaque(m_data_pos, m_pdns_param_id, &event_data.data.notifydetail.data); ERROR_CHECK(result); } // Send the response to App event_data.event = PDNS_EVT_GET_PD_NOTIFY_DETAIL_DATA_RESP; result = m_pdlp_service.pdns_event_handler(p_pdls, &event_data); // No need of response if App return OK if ( result == PDLS_RESULT_OK) { *rsp_len = 0; } // Transaction comleted service_reset(); // Parameter details fetched m_pdns_param_id = PDNS_PARAM_INVALID; } break; case PDNS_START_PD_APPLICATION_RESP: { // Result code result = pdls_decode_param_uint8(m_data_pos, PDNS_PARAM_RESULTCODE, (uint8_t *)&event_data.data.startappresult.result); ERROR_CHECK(result); m_data_pos += PARAM_UINT8_LENGTH; // Send the response to App event_data.event = PDNS_EVT_START_PD_APP_RESP; result = m_pdlp_service.pdns_event_handler(p_pdls, &event_data); // No need of response if App return OK if ( result == PDLS_RESULT_OK) { *rsp_len = 0; } // Transaction comleted service_reset(); } break; default: return PDLS_RESULT_ERROR_NOT_SUPPORT; } return result; } /**@brief Function for handling a PDSOS request. * * @param[in] p_pdls PDLP Service structure. * @param[in] msgid PDSOS message ID. * @param[in] param_num Number of parameters in this PDSOS message * @param[out] rsp_len Prepared response message length. * * @retval PDLS_RESULT_OK on success, else an error value */ static ble_pdls_result_code_t PDSOS_service_handler(ble_pdls_t * p_pdls, uint16_t msgid, uint8_t param_num, uint16_t *rsp_len) { ble_pdsos_event_data_t event_data; ble_pdls_result_code_t result; uint8_t paramindex = 0; // check msgid switch (msgid) { case PDSOS_GET_SETTING_INFORMATION: { // Send the request to App for handling event_data.event = PDSOS_EVT_GET_SETTING_INFO; result = m_pdlp_service.pdsos_event_handler(p_pdls, &event_data); // No need of response if App return OK if ( result == PDLS_RESULT_OK) { *rsp_len = 0; } } break; case PDSOS_GET_SETTING_NAME: { // Setting Name Type result = pdls_decode_param_uint8(m_data_pos, PDSOS_PARAM_SETTINGNAMETYPE, (uint8_t *)&event_data.data.setting_name_type); ERROR_CHECK(result); m_data_pos += PARAM_UINT8_LENGTH; paramindex++; // Send the request to App for handling event_data.event = PDSOS_EVT_GET_SETTING_NAME; result = m_pdlp_service.pdsos_event_handler(p_pdls, &event_data); // No need of response if App return OK if ( result == PDLS_RESULT_OK) { *rsp_len = 0; } } break; case PDSOS_SELECT_SETTING_INFORMATION: { // Setting Information Request result = pdls_decode_param_uint8(m_data_pos, PDSOS_PARAM_SETTINGINFORMATIONREQUEST, (uint8_t *)&event_data.data.setting_info_request); ERROR_CHECK(result); if (PDSOS_SETTING_REQ_ID_SETTING == event_data.data.setting_info_request) { pdlp_opaque_t setting_info; result = pdls_decode_param_opaque(m_data_pos, PDSOS_PARAM_SETTINGINFORMATIONDATA, &setting_info); ERROR_CHECK(result); event_data.data.setting_info.setting_id = *(setting_info.p_val + 0); if (event_data.data.setting_info.setting_id == PDSOS_SETTING_VALUE_ID_LED) { event_data.data.setting_info.setting.led_setting.color_num = *(setting_info.p_val + 1); event_data.data.setting_info.setting.led_setting.color_selected = *(setting_info.p_val + 2); event_data.data.setting_info.setting.led_setting.pattern_num = *(setting_info.p_val + 3); event_data.data.setting_info.setting.led_setting.pattern_selected = *(setting_info.p_val + 4); event_data.data.setting_info.notify_time = *(setting_info.p_val + 5); } else if (event_data.data.setting_info.setting_id == PDSOS_SETTING_VALUE_ID_VIBRATOR) { event_data.data.setting_info.setting.vibrator_setting.pattern_num = *(setting_info.p_val + 1); event_data.data.setting_info.setting.vibrator_setting.pattern_selected = *(setting_info.p_val + 2); event_data.data.setting_info.notify_time = *(setting_info.p_val + 3); } } // Send the request to App for handling event_data.event = PDSOS_EVT_SELECT_SETTING_INFO; result = m_pdlp_service.pdsos_event_handler(p_pdls, &event_data); // No need of response if App return OK if ( result == PDLS_RESULT_OK) { *rsp_len = 0; } } case PDSOS_GET_APP_VERSION: case PDSOS_CONFIRM_INSTALL_APP: default: result = PDLS_RESULT_ERROR_NOT_SUPPORT; } return result; } // // API of PDLP services // /**@brief Function for handling the application's BLE stack events. * * @details This function handles all events from the BLE stack that are of interest to the PDLP Service. * * @param[in] p_pdlp PDLP Service structure. * @param[in] p_ble_evt Event received from the BLE stack. */ uint32_t ble_pdls_init(ble_pdls_t * p_pdls, const ble_pdls_init_t * p_pdls_init) { uint32_t err_code; ble_uuid_t ble_uuid; // Initialize service structure. p_pdls->conn_handle = BLE_CONN_HANDLE_INVALID; // Add service. ble_uuid128_t base_uuid = {PDLS_UUID_BASE}; err_code = sd_ble_uuid_vs_add(&base_uuid, &p_pdls->uuid_type); VERIFY_SUCCESS(err_code); ble_uuid.type = p_pdls->uuid_type; ble_uuid.uuid = PDLS_UUID_SERVICE; err_code = sd_ble_gatts_service_add(BLE_GATTS_SRVC_TYPE_PRIMARY, &ble_uuid, &p_pdls->service_handle); VERIFY_SUCCESS(err_code); // Add characteristics. err_code = write_char_add(p_pdls, p_pdls_init); VERIFY_SUCCESS(err_code); err_code = ind_char_add(p_pdls, p_pdls_init); VERIFY_SUCCESS(err_code); m_pdlp_service = *p_pdls_init; return NRF_SUCCESS; } void ble_pdls_on_ble_evt(ble_pdls_t * p_pdls, ble_evt_t * p_ble_evt) { switch (p_ble_evt->header.evt_id) { case BLE_GAP_EVT_CONNECTED: on_connect(p_pdls, p_ble_evt); break; case BLE_GAP_EVT_DISCONNECTED: on_disconnect(p_pdls, p_ble_evt); break; case BLE_GATTS_EVT_WRITE: on_write(p_pdls, p_ble_evt); break; case BLE_GATTS_EVT_HVC: on_confirm(p_pdls, p_ble_evt); break; case BLE_GATTS_EVT_TIMEOUT: on_timeout(p_pdls, p_ble_evt); default: // No implementation needed. break; } } uint32_t ble_pdls_pdos_notify(ble_pdls_t * p_pdls, ble_pdos_button_id_t button_id) { // check state if (m_transmit_state != PDLS_STATE_IDLE || !m_indication_confirmed) { return NRF_ERROR_INVALID_STATE; } // Prepare PDOS indication m_data_pos = m_rsp_buf; // Service header m_data_pos += pdls_encode_service_header(m_data_pos, PDLS_SERVICE_OS, PDOS_NOTIFY_PD_OPERATION, 1); // param #1 Button ID m_data_pos += pdls_encode_param_uint8(m_data_pos, PDOS_PARAM_BUTTONID, button_id); // Start indicating m_data_size = m_data_pos - m_rsp_buf; m_data_pos = m_rsp_buf; m_current_packet = 0; return indicate_ack(p_pdls); } uint32_t ble_pdls_pdsis_notify(ble_pdls_t * p_pdls, ble_pdsis_sensor_type_t sensor_type, ble_pdsis_notify_value_t *p_notify_value) { // check state if (m_transmit_state != PDLS_STATE_IDLE || !m_indication_confirmed) { return NRF_ERROR_INVALID_STATE; } // Prepare PDOS indication m_data_pos = m_rsp_buf; switch (sensor_type) { case PDSIS_SENSOR_TYPE_GYROSCOPE: case PDSIS_SENSOR_TYPE_ACCELEROMETER: case PDSIS_SENSOR_TYPE_ORIENTATION: // Service header m_data_pos += pdls_encode_service_header(m_data_pos, PDLS_SERVICE_SIS, PDSIS_NOTIFY_PD_SENSOR_INFO, 4); // param #1 sensor type m_data_pos += pdls_encode_param_uint8(m_data_pos, PDSIS_PARAM_SENSORTYPE, (uint8_t)sensor_type); // param #2 X-value m_data_pos += pdls_encode_param_uint32(m_data_pos, PDSIS_PARAM_X_VALUE, p_notify_value->value.x_value); // param #3 Y-value m_data_pos += pdls_encode_param_uint32(m_data_pos, PDSIS_PARAM_Y_VALUE, p_notify_value->value.y_value); // param #4 Z-value m_data_pos += pdls_encode_param_uint32(m_data_pos, PDSIS_PARAM_Z_VALUE, p_notify_value->value.z_value); break; case PDSIS_SENSOR_TYPE_BATTERY: case PDSIS_SENSOR_TYPE_TEMPERATURE: case PDSIS_SENSOR_TYPE_HUMIDITY: // Service header m_data_pos += pdls_encode_service_header(m_data_pos, PDLS_SERVICE_SIS, PDSIS_NOTIFY_PD_SENSOR_INFO, 2); // param #1 sensor type m_data_pos += pdls_encode_param_uint8(m_data_pos, PDSIS_PARAM_SENSORTYPE, (uint8_t)sensor_type); // param #2 OriginalData in DoCoMo foramt (12-bit) m_data_pos += pdls_encode_param_uint16(m_data_pos, PDSIS_PARAM_ORIGINALDATA, p_notify_value->u16_originaldata[0]); break; default: return NRF_ERROR_INVALID_DATA; } // Start indicating m_data_size = m_data_pos - m_rsp_buf; m_data_pos = m_rsp_buf; m_current_packet = 0; return indicate_ack(p_pdls); } uint32_t ble_pdls_pdns_get_pd_notify_detail_data(ble_pdls_t * p_pdls, uint16_t unique_id, uint8_t param_id, uint32_t param_len) { // Prepare PDNS indication m_data_pos = m_rsp_buf; // Service header m_data_pos += pdls_encode_service_header(m_data_pos, PDLS_SERVICE_NS, PDNS_GET_PD_NOTIFY_DETAIL_DATA, 3); // param #1 UniqueID m_data_pos += pdls_encode_param_uint16(m_data_pos, PDNS_PARAM_UNIQUEID, unique_id); // param #2 GetParameterID m_data_pos += pdls_encode_param_uint8(m_data_pos, PDNS_PARAM_GETPARAMETERID, param_id); m_pdns_param_id = param_id; // param #3 GetParameterLength m_data_pos += pdls_encode_param_uint32(m_data_pos, PDNS_PARAM_GETPARAMETERLENGTH, param_len); // Start indicating m_data_size = m_data_pos - m_rsp_buf; m_data_pos = m_rsp_buf; m_current_packet = 0; return indicate_ack(p_pdls); } uint32_t ble_pdls_pdns_start_pd_app(ble_pdls_t *p_pdls, pdlp_opaque_t *p_package, pdlp_opaque_t *p_notifyapp, pdlp_opaque_t *p_class, pdlp_opaque_t *p_sharing_info) { // Prepare PDNS indication m_data_pos = m_rsp_buf; // Service header if (p_sharing_info != NULL) { m_data_pos += pdls_encode_service_header(m_data_pos, PDLS_SERVICE_NS, PDNS_GET_PD_NOTIFY_DETAIL_DATA, 4); } else { m_data_pos += pdls_encode_service_header(m_data_pos, PDLS_SERVICE_NS, PDNS_GET_PD_NOTIFY_DETAIL_DATA, 3); } // param #1 package m_data_pos += pdls_encode_param_opaque(m_data_pos, PDNS_PARAM_PACKAGE, p_package); // param #2 NotifyApp m_data_pos += pdls_encode_param_opaque(m_data_pos, PDNS_PARAM_NOTIFYAPP, p_package); // param #3 Class m_data_pos += pdls_encode_param_opaque(m_data_pos, PDNS_PARAM_CLASS, p_class); if (p_sharing_info != NULL) { // param #4 SharingInformation m_data_pos += pdls_encode_param_opaque(m_data_pos, PDNS_PARAM_SHARINGINFORMATION, p_sharing_info); } // Start indicating m_data_size = m_data_pos - m_rsp_buf; m_data_pos = m_rsp_buf; m_current_packet = 0; return indicate_ack(p_pdls); } uint32_t ble_pdls_pdsos_get_setting_info_resp(ble_pdls_t * p_pdls, ble_pdls_result_code_t result, ble_pdsos_setting_info* p_setting_info) { // Prepare response, first service header m_data_pos = m_rsp_buf; m_data_pos += pdls_encode_service_header(m_data_pos, PDLS_SERVICE_SOS, PDSOS_GET_SETTING_INFORMATION_RESP, 2); // param #1 Reult code m_data_pos += pdls_encode_param_uint8(m_data_pos, PDSOS_PARAM_RESULTCODE, result); if (result == PDLS_RESULT_OK) { // param #2 Setting Information Data pdlp_opaque_t setting_info; if (p_setting_info->setting_id == PDSOS_SETTING_VALUE_ID_LED) { uint8_t led_setting[6]; led_setting[0] = PDSOS_SETTING_VALUE_ID_LED; led_setting[1] = p_setting_info->setting.led_setting.color_num; led_setting[2] = p_setting_info->setting.led_setting.color_selected; led_setting[3] = p_setting_info->setting.led_setting.pattern_num; led_setting[4] = p_setting_info->setting.led_setting.pattern_selected; led_setting[5] = p_setting_info->notify_time; setting_info.len = 6; setting_info.p_val = led_setting; } else if (p_setting_info->setting_id == PDSOS_SETTING_VALUE_ID_VIBRATOR) { uint8_t vib_setting[4]; vib_setting[0] = PDSOS_SETTING_VALUE_ID_VIBRATOR; vib_setting[1] = p_setting_info->setting.vibrator_setting.pattern_num; vib_setting[2] = p_setting_info->setting.vibrator_setting.pattern_selected; vib_setting[3] = p_setting_info->notify_time; setting_info.len = 4; setting_info.p_val = vib_setting; } m_data_pos += pdls_encode_param_opaque(m_data_pos, PDSOS_PARAM_SETTINGINFORMATIONDATA, &setting_info); } // Start indicating m_data_size = m_data_pos - m_rsp_buf; m_data_pos = m_rsp_buf; m_current_packet = 0; return indicate_ack(p_pdls); } uint32_t ble_pdls_pdsos_get_setting_name_resp(ble_pdls_t * p_pdls, ble_pdls_result_code_t result, ble_pdsos_setting_name* p_setting_name) { // Prepare response, first service header m_data_pos = m_rsp_buf; m_data_pos += pdls_encode_service_header(m_data_pos, PDLS_SERVICE_SOS, PDSOS_GET_SETTING_NAME_RESP, 2); // param #1 Reult code m_data_pos += pdls_encode_param_uint8(m_data_pos, PDSOS_PARAM_RESULTCODE, result); if (result == PDLS_RESULT_OK) { // param #2 Setting Name Data m_data_pos += pdls_encode_param_opaque(m_data_pos, PDSOS_PARAM_SETTINGNAMEDATA, &p_setting_name->setting); } // Start indicating m_data_size = m_data_pos - m_rsp_buf; m_data_pos = m_rsp_buf; m_current_packet = 0; return indicate_ack(p_pdls); } uint32_t ble_pdls_pdsos_select_setting_info_resp(ble_pdls_t * p_pdls, ble_pdls_result_code_t result) { // Prepare response, first service header m_data_pos = m_rsp_buf; m_data_pos += pdls_encode_service_header(m_data_pos, PDLS_SERVICE_SOS, PDSOS_SELECT_SETTING_INFORMATION_RESP, 1); // param #1 Reult code m_data_pos += pdls_encode_param_uint8(m_data_pos, PDSOS_PARAM_RESULTCODE, result); // Start indicating m_data_size = m_data_pos - m_rsp_buf; m_data_pos = m_rsp_buf; m_current_packet = 0; return indicate_ack(p_pdls); } <file_sep>/components/ble/ble_services/experimental_ble_pdlp/ble_pdlp_common.h /* Copyright (c) 2016 Nordic Semiconductor. All Rights Reserved. * * The information contained herein is property of Nordic Semiconductor ASA. * Terms and conditions of usage are described in detail in NORDIC * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. * * Licensees are granted free, non-transferable use of the information. NO * WARRANTY of ANY KIND is provided. This heading must NOT be removed from * the file. * */ #ifndef BLE_PDLP_COMMON_H__ #define BLE_PDLP_COMMON_H__ #include <stdint.h> #include <string.h> /**@brief PDLS result code */ typedef enum { PDLS_RESULT_OK, PDLS_RESULT_CANCEL, PDLS_RESULT_ERROR_FAILED, PDLS_RESULT_ERROR_UNKNOWN, PDLS_RESULT_ERROR_NO_DATA, PDLS_RESULT_ERROR_NOT_SUPPORT, PDLS_RESULT_MAX } ble_pdls_result_code_t; /**@brief PDLS cancel reason code */ typedef enum { PDLS_CANCEL_USER_CANCEL, PDLS_CANCEL_MAX } ble_pdls_cancel_t; /**@brief PDLP opaque type. */ typedef struct { uint8_t * p_val; /**< Pointer to the value of the opaque data. */ uint32_t len; /**< Length of p_val. */ } pdlp_opaque_t; uint32_t pdls_encode_service_header(uint8_t *p_buf, uint8_t service_id, uint16_t message_id, uint8_t number_of_param); uint32_t pdls_encode_param_uint8 (uint8_t *p_buf, uint8_t param_id, uint8_t param_data); uint32_t pdls_encode_param_uint16(uint8_t *p_buf, uint8_t param_id, uint16_t param_data); uint32_t pdls_encode_param_uint32(uint8_t *p_buf, uint8_t param_id, uint32_t param_data); uint32_t pdls_encode_param_opaque(uint8_t *p_buf, uint8_t param_id, pdlp_opaque_t *p_param_data); ble_pdls_result_code_t pdls_decode_param_uint8(uint8_t *p_buf, uint8_t param_id, uint8_t *param_data); ble_pdls_result_code_t pdls_decode_param_uint16(uint8_t *p_buf, uint8_t param_id, uint16_t *param_data); ble_pdls_result_code_t pdls_decode_param_uint32(uint8_t *p_buf, uint8_t param_id, uint32_t *param_data); ble_pdls_result_code_t pdls_decode_param_opaque(uint8_t *p_buf, uint8_t param_id, pdlp_opaque_t *p_param_data); uint16_t IEEE754_Convert_Temperature(float f_value); uint16_t IEEE754_Convert_Humidity(float f_value); uint16_t IEEE754_Convert_Air_Pressure(float f_value); #endif // BLE_PDLP_COMMON_H__ /** @} */ <file_sep>/examples/ble_peripheral/experimental_ble_app_linking_beacon/deploy/src/sensor_beacon.c /* Copyright (c) Nordic Semiconductor ASA * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * 3. Neither the name of Nordic Semiconductor ASA nor the names of other * contributors to this software may be used to endorse or promote products * derived from this software without specific prior written permission. * * 4. This software must only be used in a processor manufactured by Nordic * Semiconductor ASA, or in a processor manufactured by a third party that * is used in combination with a processor manufactured by Nordic Semiconductor. * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "hal_radio.h" #include "hal_timer.h" #include "hal_clock.h" #include "nrf.h" #include "nrf_temp.h" #include "ble_pdlp_beacon.h" #include "ble_pdlp_common.h" #include <string.h> #include <stdlib.h> //#define DBG_RADIO_ACTIVE_ENABLE //#define DBG_BEACON_START_PIN (16) //#define DBG_HFCLK_ENABLED_PIN (27) //#define DBG_HFCLK_DISABLED_PIN (26) //#define DBG_PKT_SENT_PIN (9) //#define DBG_CALCULATE_BEGIN_PIN (15) //#define DBG_CALCULATE_END_PIN (15) //#define DBG_RADIO_ACTIVE_PIN (24) //#define DBG_WFE_BEGIN_PIN (25) //#define DBG_WFE_END_PIN (25) //#define DBG_BEACON_START \ //{ \ // NRF_GPIO->OUTSET = (1 << DBG_BEACON_START_PIN); \ // NRF_GPIO->DIRSET = (1 << DBG_BEACON_START_PIN); \ // NRF_GPIO->DIRCLR = (1 << DBG_BEACON_START_PIN); \ // NRF_GPIO->OUTCLR = (1 << DBG_BEACON_START_PIN); \ //} //#define DBG_HFCLK_ENABLED \ //{ \ // NRF_GPIO->OUTSET = (1 << DBG_HFCLK_ENABLED_PIN); \ // NRF_GPIO->DIRSET = (1 << DBG_HFCLK_ENABLED_PIN); \ // NRF_GPIO->DIRCLR = (1 << DBG_HFCLK_ENABLED_PIN); \ // NRF_GPIO->OUTCLR = (1 << DBG_HFCLK_ENABLED_PIN); \ //} //#define DBG_HFCLK_DISABLED \ //{ \ // NRF_GPIO->OUTSET = (1 << DBG_HFCLK_DISABLED_PIN); \ // NRF_GPIO->DIRSET = (1 << DBG_HFCLK_DISABLED_PIN); \ // NRF_GPIO->DIRCLR = (1 << DBG_HFCLK_DISABLED_PIN); \ // NRF_GPIO->OUTCLR = (1 << DBG_HFCLK_DISABLED_PIN); \ //} //#define DBG_PKT_SENT \ //{ \ // NRF_GPIO->OUTSET = (1 << DBG_PKT_SENT_PIN); \ // NRF_GPIO->DIRSET = (1 << DBG_PKT_SENT_PIN); \ // NRF_GPIO->DIRCLR = (1 << DBG_PKT_SENT_PIN); \ // NRF_GPIO->OUTCLR = (1 << DBG_PKT_SENT_PIN); \ //} //#define DBG_WFE_BEGIN \ //{ \ // NRF_GPIO->OUTCLR = (1 << DBG_WFE_BEGIN_PIN); \ // NRF_GPIO->DIRSET = (1 << DBG_WFE_BEGIN_PIN); \ // NRF_GPIO->OUTSET = (1 << DBG_WFE_BEGIN_PIN); \ // for ( int i = 0; i < 0xFF; i++ ) __NOP();\ // NRF_GPIO->OUTCLR = (1 << DBG_WFE_BEGIN_PIN); \ //} //#define DBG_WFE_END \ //{ \ // for ( int i = 0; i < 0xFF; i++ ) __NOP();\ // NRF_GPIO->OUTSET = (1 << DBG_WFE_END_PIN); \ // /*NRF_GPIO->DIRSET = (1 << DBG_WFE_END_PIN);*/ \ //} #ifndef DBG_BEACON_START #define DBG_BEACON_START #endif #ifndef DBG_PKT_SENT #define DBG_PKT_SENT #endif #ifndef DBG_HFCLK_ENABLED #define DBG_HFCLK_ENABLED #endif #ifndef DBG_HFCLK_DISABLED #define DBG_HFCLK_DISABLED #endif #ifndef DBG_WFE_BEGIN #define DBG_WFE_BEGIN #endif #ifndef DBG_WFE_END #define DBG_WFE_END #endif #ifdef NRF52 #define FPU_EXCEPTION_MASK 0x0000009F //!< FPU exception mask used to clear exceptions in FPSCR register. #define FPU_FPSCR_REG_STACK_OFF 0x40 //!< Offset of FPSCR register stacked during interrupt handling in FPU part stack. #endif #define HFCLK_STARTUP_TIME_US (1600) /* The time in microseconds it takes to start up the HF clock*. */ #define INTERVAL_US (300000) /* The time in microseconds between advertising events. */ #define INITIAL_TIMEOUT (INTERVAL_US) /* The time in microseconds until adverising the first time. */ #define START_OF_INTERVAL_TO_SENSOR_READ_TIME_US (INTERVAL_US / 2) /* The time from the start of the latest advertising event until reading the sensor. */ #define SENSOR_SKIP_READ_COUNT (10) /* The number of advertising events between reading the sensor. */ #if INITIAL_TIMEOUT - HFCLK_STARTUP_TIME_US < 400 #error "Initial timeout too short!" #endif // Configuration Linking Beacon service type static uint32_t m_service_type = LINKING_SERVICE_TYPE_TEMPERATURE; /* loop Temperature/Humidity/Air pressure */ static bool volatile m_radio_isr_called; /* Indicates that the radio ISR has executed. */ static bool volatile m_rtc_isr_called; /* Indicates that the RTC ISR has executed. */ static uint32_t m_time_us; /* Keeps track of the latest scheduled point in time. */ static uint32_t m_skip_read_counter = 0; /* Keeps track on when to read the sensor. */ static uint8_t m_adv_pdu[40]; /* The RAM representation of the advertising PDU. */ /* Initializes the beacon advertising PDU. */ static void m_beacon_pdu_init(uint8_t * p_beacon_pdu) { p_beacon_pdu[0] = 0x42; p_beacon_pdu[1] = 0; p_beacon_pdu[2] = 0; } /* Sets the BLE address field in the sensor beacon PDU. */ static void m_beacon_pdu_bd_addr_default_set(uint8_t * p_beacon_pdu) { if ( ( NRF_FICR->DEVICEADDR[0] != 0xFFFFFFFF) || ((NRF_FICR->DEVICEADDR[1] & 0xFFFF) != 0xFFFF) ) { p_beacon_pdu[BD_ADDR_OFFS ] = (NRF_FICR->DEVICEADDR[0] ) & 0xFF; p_beacon_pdu[BD_ADDR_OFFS + 1] = (NRF_FICR->DEVICEADDR[0] >> 8) & 0xFF; p_beacon_pdu[BD_ADDR_OFFS + 2] = (NRF_FICR->DEVICEADDR[0] >> 16) & 0xFF; p_beacon_pdu[BD_ADDR_OFFS + 3] = (NRF_FICR->DEVICEADDR[0] >> 24) ; p_beacon_pdu[BD_ADDR_OFFS + 4] = (NRF_FICR->DEVICEADDR[1] ) & 0xFF; p_beacon_pdu[BD_ADDR_OFFS + 5] = (NRF_FICR->DEVICEADDR[1] >> 8) & 0xFF; } else { static const uint8_t random_bd_addr[M_BD_ADDR_SIZE] = {0xE2, 0xA3, 0x01, 0xE7, 0x61, 0xF7}; memcpy(&(p_beacon_pdu[3]), &(random_bd_addr[0]), M_BD_ADDR_SIZE); } p_beacon_pdu[1] = (p_beacon_pdu[1] == 0) ? M_BD_ADDR_SIZE : p_beacon_pdu[1]; } /* Resets the sensor data of the sensor beacon PDU. */ static void m_beacon_pdu_sensor_data_reset(uint8_t * p_beacon_pdu) { // 128-bit UUID beacon static const uint8_t beacon_temp_pres[31] = { /* Entry for Flags */ 0x02, 0x01, 0x04, /* Entry for Complete List of 128-bit Service Class UUID of Linking beacon */ 0x11, 0x07, 0xCD, 0xA6, 0x13, 0x5B, 0x83, 0x50, 0x8D, 0x80,0x44, 0x40, 0xD3, 0x50, 0x01, 0x69, 0xB3, 0xB3, /* Entry for Manufacture specific data in Linking spec*/ 0x09, 0xFF, 0xE2, 0x02, // Company ID DoCoMo (0x02E2) 0x0A, 0xB1, 0x23, 0x45, // Version 0x0, VenderID 0xAB, ClassID 0x12345 0x00, 0x00 // Service data }; memcpy(&(p_beacon_pdu[3 + M_BD_ADDR_SIZE]), &(beacon_temp_pres[0]), sizeof(beacon_temp_pres)); p_beacon_pdu[1] = M_BD_ADDR_SIZE + sizeof(beacon_temp_pres); } static float m_beacon_read_soc_temp(void) { // This function contains workaround for PAN_028 rev2.0A anomalies 28, 29,30 and 31. int32_t volatile temp; nrf_temp_init(); NRF_TEMP->TASKS_START = 1; /** Start the temperature measurement. */ /* Busy wait while temperature measurement is not finished, you can skip waiting if you enable interrupt for DATARDY event and read the result in the interrupt. */ /*lint -e{845} // A zero has been given as right argument to operator '|'" */ while (NRF_TEMP->EVENTS_DATARDY == 0) { // Do nothing. } NRF_TEMP->EVENTS_DATARDY = 0; /**@note Workaround for PAN_028 rev2.0A anomaly 29 - TEMP: Stop task clears the TEMP register. */ temp = nrf_temp_read(); /**@note Workaround for PAN_028 rev2.0A anomaly 30 - TEMP: Temp module analog front end does not power down when DATARDY event occurs. */ NRF_TEMP->TASKS_STOP = 1; /** Stop the temperature measurement. */ return (float)temp*0.25f; } /* Sets the sensor data of the sensor beacon PDU. */ static void m_beacon_pdu_sensor_data_set(uint8_t * p_beacon_pdu) { static float simulated_data_change = 1.0f; simulated_data_change += 1.0f; if (simulated_data_change > 10.0f) { simulated_data_change = 1.0f; } p_beacon_pdu[SINT16_SERVICE_DATA_OFFS] = m_service_type << 4; // ServiceID (4-bit) if ( m_service_type == LINKING_SERVICE_TYPE_TEMPERATURE) { float f_temp = m_beacon_read_soc_temp(); uint16_t u_temp = IEEE754_Convert_Temperature(f_temp); p_beacon_pdu[SINT16_SERVICE_DATA_OFFS ] = (LINKING_SERVICE_TYPE_TEMPERATURE << 4) & 0xF0; // Up 4-bits, Service ID p_beacon_pdu[SINT16_SERVICE_DATA_OFFS ] |= (u_temp >> 8) & 0xF; // Low 4-bits (sign and first 3-bit of exponent) p_beacon_pdu[SINT16_SERVICE_DATA_OFFS + 1] = (u_temp >> 0) & 0xFF; // 4th bit of exponent and fraction m_service_type = LINKING_SERVICE_TYPE_HUMIDITY; // next Humidity } else if (m_service_type == LINKING_SERVICE_TYPE_HUMIDITY) { float f_humidity = 155.5f + simulated_data_change; uint16_t u_humidity = IEEE754_Convert_Humidity(f_humidity); p_beacon_pdu[SINT16_SERVICE_DATA_OFFS ] = (LINKING_SERVICE_TYPE_HUMIDITY << 4) & 0xF0; // Up 4-bits, Service ID p_beacon_pdu[SINT16_SERVICE_DATA_OFFS ] |= (u_humidity >> 8) & 0xF; // Low 4-bits (exponent) p_beacon_pdu[SINT16_SERVICE_DATA_OFFS + 1] = (u_humidity >> 0) & 0xFF; // fraction m_service_type = LINKING_SERVICE_TYPE_AIRPRESSURE; // next Air Pressure } else if (m_service_type == LINKING_SERVICE_TYPE_AIRPRESSURE) { float f_pressure = 34567.0f + simulated_data_change*10; uint16_t u_perssure = IEEE754_Convert_Air_Pressure(f_pressure); p_beacon_pdu[SINT16_SERVICE_DATA_OFFS ] = (LINKING_SERVICE_TYPE_AIRPRESSURE << 4) & 0xF0; // Up 4-bits, Service ID p_beacon_pdu[SINT16_SERVICE_DATA_OFFS ] |= (u_perssure >> 8) & 0xF; // Low 4-bits (first 4-bit of exponent) p_beacon_pdu[SINT16_SERVICE_DATA_OFFS + 1] = (u_perssure >> 0) & 0xFF; // 5th bit of exponent and fraction m_service_type = LINKING_SERVICE_TYPE_TEMPERATURE; // next Temperature } // Below service types are NOT included int testing else if (m_service_type == LINKING_SERVICE_TYPE_BATTERY) { linking_battery_info_t info; info.service_id = LINKING_SERVICE_TYPE_BATTERY; info.charge_needed = true; info.battery_level = 53; // 53%, needs to convert from float to int (when spec ready) memcpy(&(p_beacon_pdu[SINT16_SERVICE_DATA_OFFS]), &info, sizeof(linking_battery_info_t)); } else if (m_service_type == LINKING_SERVICE_TYPE_BUTTON) { linking_button_info_t info; info.service_id = LINKING_SERVICE_TYPE_BUTTON; info.button_id = 0x02; // ENTER, see PDNS sec memcpy(&(p_beacon_pdu[SINT16_SERVICE_DATA_OFFS]), &info, sizeof(linking_button_info_t)); } else if (m_service_type == LINKING_SERVICE_TYPE_OPEN_CLOSE_SENSE) { linking_openclose_sensor_info_t info; info.service_id = LINKING_SERVICE_TYPE_OPEN_CLOSE_SENSE; info.open_close_flag = 0; // Open info.open_count = 100; memcpy(&(p_beacon_pdu[SINT16_SERVICE_DATA_OFFS]), &info, sizeof(linking_openclose_sensor_info_t)); } else if (m_service_type == LINKING_SERVICE_TYPE_HUMAN_SENSE) { linking_human_sensor_info_t info; info.service_id = LINKING_SERVICE_TYPE_HUMAN_SENSE; info.human_sensed = true; memcpy(&(p_beacon_pdu[SINT16_SERVICE_DATA_OFFS]), &info, sizeof(linking_human_sensor_info_t)); } else if (m_service_type == LINKING_SERVICE_TYPE_VIBRATION_SENSE) { linking_vibration_sensor_info_t info; info.service_id = LINKING_SERVICE_TYPE_VIBRATION_SENSE; info.vibration_sensed = true; memcpy(&(p_beacon_pdu[SINT16_SERVICE_DATA_OFFS]), &info, sizeof(linking_vibration_sensor_info_t)); } } /* Waits for the next NVIC event. */ static void __forceinline cpu_wfe(void) { DBG_WFE_BEGIN; __WFE(); __SEV(); __WFE(); DBG_WFE_END; } /* Sends an advertising PDU on the given channel index. */ static void send_one_packet(uint8_t channel_index) { uint8_t i; m_radio_isr_called = false; hal_radio_channel_index_set(channel_index); hal_radio_send(m_adv_pdu); while ( !m_radio_isr_called ) { cpu_wfe(); } for ( i = 0; i < 9; i++ ) { __NOP(); } } /* Handles beacon managing. */ static void beacon_handler(void) { hal_radio_reset(); hal_timer_start(); m_time_us = INITIAL_TIMEOUT - HFCLK_STARTUP_TIME_US; do { if ( m_skip_read_counter == 0 ) { m_rtc_isr_called = false; hal_timer_timeout_set(m_time_us - START_OF_INTERVAL_TO_SENSOR_READ_TIME_US); while ( !m_rtc_isr_called ) { cpu_wfe(); } m_rtc_isr_called = false; hal_timer_timeout_set(m_time_us - START_OF_INTERVAL_TO_SENSOR_READ_TIME_US + 10000); while ( !m_rtc_isr_called ) { cpu_wfe(); } } m_skip_read_counter = ( (m_skip_read_counter + 1) < SENSOR_SKIP_READ_COUNT ) ? (m_skip_read_counter + 1) : 0; m_rtc_isr_called = false; hal_timer_timeout_set(m_time_us); while ( !m_rtc_isr_called ) { cpu_wfe(); } hal_clock_hfclk_enable(); DBG_HFCLK_ENABLED; m_rtc_isr_called = false; m_time_us += HFCLK_STARTUP_TIME_US; hal_timer_timeout_set(m_time_us); while ( !m_rtc_isr_called ) { cpu_wfe(); } m_beacon_pdu_sensor_data_set(&(m_adv_pdu[0])); send_one_packet(37); DBG_PKT_SENT; send_one_packet(38); DBG_PKT_SENT; send_one_packet(39); DBG_PKT_SENT; hal_clock_hfclk_disable(); DBG_HFCLK_DISABLED; m_time_us = m_time_us + (INTERVAL_US - HFCLK_STARTUP_TIME_US); } while ( 1 ); } int main(void) { DBG_BEACON_START; NRF_GPIO->OUTCLR = 0xFFFFFFFF; NRF_GPIO->DIRCLR = 0xFFFFFFFF; #ifdef FPU_INTERRUPT_MODE // Enable FPU interrupt NVIC_SetPriority(FPU_IRQn, 6); // nRF52 _PRIO_APP_LOW = 6 NVIC_ClearPendingIRQ(FPU_IRQn); NVIC_EnableIRQ(FPU_IRQn); #endif #ifdef DBG_WFE_BEGIN_PIN NRF_GPIO->OUTSET = (1 << DBG_WFE_BEGIN_PIN); NRF_GPIO->DIRSET = (1 << DBG_WFE_BEGIN_PIN); #endif m_beacon_pdu_init(&(m_adv_pdu[0])); m_beacon_pdu_bd_addr_default_set(&(m_adv_pdu[0])); m_beacon_pdu_sensor_data_reset(&(m_adv_pdu[0])); #ifdef DBG_RADIO_ACTIVE_ENABLE NRF_GPIOTE->CONFIG[0] = (GPIOTE_CONFIG_POLARITY_Toggle << GPIOTE_CONFIG_POLARITY_Pos) | (DBG_RADIO_ACTIVE_PIN << GPIOTE_CONFIG_PSEL_Pos) | (GPIOTE_CONFIG_MODE_Task << GPIOTE_CONFIG_MODE_Pos); NRF_PPI->CH[5].TEP = (uint32_t)&(NRF_GPIOTE->TASKS_OUT[0]); NRF_PPI->CH[5].EEP = (uint32_t)&(NRF_RADIO->EVENTS_READY); NRF_PPI->CH[6].TEP = (uint32_t)&(NRF_GPIOTE->TASKS_OUT[0]); NRF_PPI->CH[6].EEP = (uint32_t)&(NRF_RADIO->EVENTS_DISABLED); NRF_PPI->CHENSET = (PPI_CHEN_CH5_Enabled << PPI_CHEN_CH5_Pos) | (PPI_CHEN_CH6_Enabled << PPI_CHEN_CH6_Pos); #endif #ifdef FPU_INTERRUPT_MODE /* Clear FPSCR register and clear pending FPU interrupts. This code is base on * nRF5x_release_notes.txt in documentation folder. It is necessary part of code when * application using power saving mode and after handling FPU errors in polling mode. */ __set_FPSCR(__get_FPSCR() & ~(FPU_EXCEPTION_MASK)); (void) __get_FPSCR(); NVIC_ClearPendingIRQ(FPU_IRQn); #endif for (;;) { beacon_handler(); } } void RADIO_IRQHandler(void) { NRF_RADIO->EVENTS_DISABLED = 0; m_radio_isr_called = true; } void RTC0_IRQHandler(void) { NRF_RTC0->EVTENCLR = (RTC_EVTENCLR_COMPARE0_Enabled << RTC_EVTENCLR_COMPARE0_Pos); NRF_RTC0->INTENCLR = (RTC_INTENCLR_COMPARE0_Enabled << RTC_INTENCLR_COMPARE0_Pos); NRF_RTC0->EVENTS_COMPARE[0] = 0; m_rtc_isr_called = true; } #ifdef FPU_INTERRUPT_MODE /** * @brief FPU Interrupt handler. Clearing exception flag at the stack. * * Function clears exception flag in FPSCR register and at the stack. During interrupt handler * execution FPU registers might be copied to the stack (see lazy stacking option) and * it is necessary to clear data at the stack which will be recovered in the return from * interrupt handling. */ void FPU_IRQHandler(void) { // Prepare pointer to stack address with pushed FPSCR register uint32_t * fpscr = (uint32_t * )(FPU->FPCAR + FPU_FPSCR_REG_STACK_OFF); // Execute FPU instruction to activate lazy stacking (void)__get_FPSCR(); // Clear flags in stacked FPSCR register *fpscr = *fpscr & ~(FPU_EXCEPTION_MASK); } #endif <file_sep>/examples/ble_peripheral/experimental_ble_app_linking_beacon_solar/inc/drv_lps25h_bitfields.h /* Copyright (c) Nordic Semiconductor ASA * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * 3. Neither the name of Nordic Semiconductor ASA nor the names of other * contributors to this software may be used to endorse or promote products * derived from this software without specific prior written permission. * * 4. This software must only be used in a processor manufactured by Nordic * Semiconductor ASA, or in a processor manufactured by a third party that * is used in combination with a processor manufactured by Nordic Semiconductor. * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef DRV_LSP25H_BITFIELDS_H__ #define DRV_LSP25H_BITFIELDS_H__ /* Register: CTRL_REG. */ /* Description: Control register. */ /* Field PD: Power down control. */ #define DRV_LSP25H_CTRL_REG_PD_Pos (7) #define DRV_LSP25H_CTRL_REG_PD_Msk (0x1 << DRV_LSP25H_CTRL_REG_PD_Pos) #define DRV_LSP25H_CTRL_REG_PD_PowerDown (0) /*!< Power-down mode */ #define DRV_LSP25H_CTRL_REG_PD_Active (1) /*!< Active mode */ /* Field ODR: Output data rate selection. */ #define DRV_LSP25H_CTRL_REG_ODR_Pos (4) #define DRV_LSP25H_CTRL_REG_ODR_Msk (0x7 << DRV_LSP25H_CTRL_REG_ODR_Pos) #define DRV_LSP25H_CTRL_REG_ODR_OneShot (0) /*!< One shot */ #define DRV_LSP25H_CTRL_REG_ODR_1HZ0 (1) /*!< 'Pressure 1.0 Hz, Temperatur 1.0 Hz */ #define DRV_LSP25H_CTRL_REG_ODR_7HZ0 (2) /*!< 'Pressure 7.0 Hz, Temperatur 7.0 Hz */ #define DRV_LSP25H_CTRL_REG_ODR_12HZ5 (3) /*!< 'Pressure 12.5 Hz, Temperatur 12.5 Hz */ #define DRV_LSP25H_CTRL_REG_ODR_25HZ0 (4) /*!< 'Pressure 25.0 Hz, Temperatur 25.0 Hz */ /* Register: STATUS_REG. */ /* Description: Status register. */ /* Field T_DA: Indicates whether temperature data is available (automatically cleared when temperature is read).. */ #define DRV_LSP25H_STATUS_REG_T_DA_Pos (0) #define DRV_LSP25H_STATUS_REG_T_DA_Msk (0x1 << DRV_LSP25H_STATUS_REG_T_DA_Pos) #define DRV_LSP25H_STATUS_REG_T_DA_Unavailable (0) /*!< Temperature data is not available */ #define DRV_LSP25H_STATUS_REG_T_DA_Available (1) /*!< Temperature data is available */ /* Field P_DA: Indicates whether pressure data is available (automatically cleared when pressure is read).. */ #define DRV_LSP25H_STATUS_REG_P_DA_Pos (1) #define DRV_LSP25H_STATUS_REG_P_DA_Msk (0x1 << DRV_LSP25H_STATUS_REG_P_DA_Pos) #define DRV_LSP25H_STATUS_REG_P_DA_Unavailable (0) /*!< Pressure data is not available */ #define DRV_LSP25H_STATUS_REG_P_DA_Available (1) /*!< Pressure data is available */ /* Register: PRESS_OUT. */ /* Description: Contains the pressure output value. */ /* Field POUT: Contains the pressure output value. */ #define DRV_LSP25H_PRESS_OUT_POUT_Pos (0) #define DRV_LSP25H_PRESS_OUT_POUT_Msk (0xffffff << DRV_LSP25H_PRESS_OUT_POUT_Pos) /* Register: TEMP_OUT. */ /* Description: Contains the temperature output value. */ /* Field TOUT: Contains the temperature output value. */ #define DRV_LSP25H_TEMP_OUT_TOUT_Pos (0) #define DRV_LSP25H_TEMP_OUT_TOUT_Msk (0xffff << DRV_LSP25H_TEMP_OUT_TOUT_Pos) #endif // DRV_LSP25H_BITFIELDS_H__ <file_sep>/examples/ble_peripheral/experimental_ble_app_linking_beacon_solar/src/drv_lps25h.c /* Copyright (c) Nordic Semiconductor ASA * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * 3. Neither the name of Nordic Semiconductor ASA nor the names of other * contributors to this software may be used to endorse or promote products * derived from this software without specific prior written permission. * * 4. This software must only be used in a processor manufactured by Nordic * Semiconductor ASA, or in a processor manufactured by a third party that * is used in combination with a processor manufactured by Nordic Semiconductor. * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "drv_lps25h.h" #include "drv_lps25h_bitfields.h" #include <stdlib.h> /* Register addresses of the lps25h device. */ #define M_REGSTATUS (0x27) #define M_REGCTRL1 (0x20) #define M_REGCTRL2 (0x21) #define M_REGCTRL3 (0x22) #define M_REGCTRL4 (0x23) #define M_REGPRESSOUTXL (0x28) #define M_REGPRESSOUTL (0x29) #define M_REGPRESSOUTH (0x2A) #define M_REGTEMPOUTL (0x2B) #define M_REGTEMPOUTH (0x2C) /* Driver properties. */ static struct { drv_lps25h_cfg_t const * p_drv_lps25h_cfg; ///< Pointer to the device configuration. drv_lps25h_access_mode_t current_access_mode; ///< The currently used access mode. volatile bool twi_sig_callback_called;///< Indicates whether the signal callback was called. } m_drv_lps25h; /* Gets the value of the specified register. */ static bool reg_get(uint8_t reg_addr, uint8_t *p_value) { if ( m_drv_lps25h.p_drv_lps25h_cfg != NULL ) { hal_twi_id_t twi_id = m_drv_lps25h.p_drv_lps25h_cfg->twi_id; hal_twi_stop_mode_set(twi_id, HAL_TWI_STOP_MODE_STOP_ON_RX_BUF_END); m_drv_lps25h.twi_sig_callback_called = false; if ( hal_twi_write(twi_id, 1, &reg_addr)== HAL_TWI_STATUS_CODE_SUCCESS ) { while ( (m_drv_lps25h.current_access_mode == DRV_LPS25H_ACCESS_MODE_CPU_INACTIVE) && (!m_drv_lps25h.twi_sig_callback_called) ) { m_drv_lps25h.p_drv_lps25h_cfg->p_sleep_hook(); } m_drv_lps25h.twi_sig_callback_called = false; if ( hal_twi_read(twi_id, 1, p_value) == HAL_TWI_STATUS_CODE_SUCCESS ) { while ( (m_drv_lps25h.current_access_mode == DRV_LPS25H_ACCESS_MODE_CPU_INACTIVE) && (!m_drv_lps25h.twi_sig_callback_called) ) { m_drv_lps25h.p_drv_lps25h_cfg->p_sleep_hook(); } return ( true ); } } } return ( false ); } /* Gets the value of the registers from left to right and stores them at the specified location. */ static bool two_registers_get(uint8_t reg_a, uint8_t reg_b, uint16_t *value) { uint8_t tmp_u8; uint16_t tmp_u16; if ( (m_drv_lps25h.p_drv_lps25h_cfg != NULL) && (reg_get(reg_b, &tmp_u8)) ) { tmp_u16 = tmp_u8; if ( reg_get(reg_a, &tmp_u8) ) { *value = (tmp_u16 << 8) | tmp_u8; return ( true ); } } return ( false ); } /* Gets the value of the registers from left to right and stores them at the specified location. */ static bool three_registers_get(uint8_t reg_a, uint8_t reg_b, uint8_t reg_c, uint32_t *value) { uint8_t tmp_u8; uint32_t tmp_u32; if ( (m_drv_lps25h.p_drv_lps25h_cfg != NULL) && (reg_get(reg_c, &tmp_u8)) ) { tmp_u32 = tmp_u8; if ( reg_get(reg_b, &tmp_u8) ) { tmp_u32 <<= 8; if ( reg_get(reg_a, &tmp_u8) ) { *value = (tmp_u32 << 8) | tmp_u8; return ( true ); } } } return ( false ); } /* Sets the specified register to the specified value. */ static bool reg_set(uint8_t reg_addr, uint8_t value) { if ( m_drv_lps25h.p_drv_lps25h_cfg != NULL ) { hal_twi_id_t twi_id = m_drv_lps25h.p_drv_lps25h_cfg->twi_id; uint8_t tx_buffer[2] = {reg_addr, value}; hal_twi_stop_mode_set(twi_id, HAL_TWI_STOP_MODE_STOP_ON_TX_BUF_END); m_drv_lps25h.twi_sig_callback_called = false; if ( hal_twi_write(twi_id, 2, &(tx_buffer[0])) == HAL_TWI_STATUS_CODE_SUCCESS ) { while ( (m_drv_lps25h.current_access_mode == DRV_LPS25H_ACCESS_MODE_CPU_INACTIVE) && (!m_drv_lps25h.twi_sig_callback_called) ) { m_drv_lps25h.p_drv_lps25h_cfg->p_sleep_hook(); } return ( true ); } } return ( false ); } /* Modifies the specified register according to the specified set and clear masks. */ static bool register_bits_modify(uint8_t reg, uint8_t set_mask, uint8_t clear_mask) { uint8_t tmp_u8; if ( ((set_mask & clear_mask) == 0) && (m_drv_lps25h.p_drv_lps25h_cfg != NULL) && (reg_get(reg, &tmp_u8)) ) { tmp_u8 |= set_mask; tmp_u8 &= ~(clear_mask); return ( reg_set(reg, tmp_u8) ); } return ( false ); } /* Handles the signals from the TWI driver. */ static void hal_twi_sig_callback(hal_twi_signal_type_t hal_twi_signal_type) { (void)hal_twi_signal_type; m_drv_lps25h.twi_sig_callback_called = true; } void drv_lps25h_init(void) { m_drv_lps25h.p_drv_lps25h_cfg = NULL; } uint32_t drv_lps25h_open(drv_lps25h_cfg_t const * const p_drv_lps25h_cfg) { if ( hal_twi_open(p_drv_lps25h_cfg->twi_id, &(p_drv_lps25h_cfg->twi_cfg)) == HAL_TWI_STATUS_CODE_SUCCESS ) { m_drv_lps25h.p_drv_lps25h_cfg = p_drv_lps25h_cfg; m_drv_lps25h.current_access_mode = DRV_LPS25H_ACCESS_MODE_CPU_ACTIVE; return ( DRV_LPS25H_STATUS_CODE_SUCCESS ); } return ( DRV_LPS25H_STATUS_CODE_DISALLOWED ); } uint32_t drv_lps25h_access_mode_set(drv_lps25h_access_mode_t access_mode) { if ( m_drv_lps25h.p_drv_lps25h_cfg == NULL ) { return ( DRV_LPS25H_STATUS_CODE_DISALLOWED ); } if ( access_mode == DRV_LPS25H_ACCESS_MODE_CPU_ACTIVE ) { m_drv_lps25h.current_access_mode = DRV_LPS25H_ACCESS_MODE_CPU_ACTIVE; hal_twi_callback_set(m_drv_lps25h.p_drv_lps25h_cfg->twi_id, NULL); } else if ( (access_mode == DRV_LPS25H_ACCESS_MODE_CPU_INACTIVE) && (m_drv_lps25h.p_drv_lps25h_cfg->p_sleep_hook != NULL) ) { m_drv_lps25h.current_access_mode = DRV_LPS25H_ACCESS_MODE_CPU_INACTIVE; hal_twi_callback_set(m_drv_lps25h.p_drv_lps25h_cfg->twi_id, hal_twi_sig_callback); } else { return ( DRV_LPS25H_STATUS_CODE_INVALID_PARAM ); } return ( DRV_LPS25H_STATUS_CODE_SUCCESS ); } uint32_t drv_lps25h_status_reg_get(uint8_t *p_stat_value) { uint8_t tmp_u8; if ( reg_get(M_REGSTATUS, &tmp_u8) ) { *p_stat_value = tmp_u8; return ( DRV_LPS25H_STATUS_CODE_SUCCESS ); } return ( DRV_LPS25H_STATUS_CODE_DISALLOWED ); } uint32_t drv_lps25h_ctrl_reg_modify(uint32_t set_mask, uint32_t clr_mask) { uint8_t set_mask_u8; uint8_t clr_mask_u8; if ( (set_mask & clr_mask) != 0 ) { return ( DRV_LPS25H_STATUS_CODE_INVALID_PARAM ); } set_mask_u8 = set_mask & 0xFF; clr_mask_u8 = clr_mask & 0xFF; if ( ((set_mask_u8 | clr_mask_u8) != 0) && (!register_bits_modify(M_REGCTRL1, set_mask_u8, clr_mask_u8)) ) { return ( DRV_LPS25H_STATUS_CODE_DISALLOWED ); } set_mask_u8 = (set_mask >> 8) & 0xFF; clr_mask_u8 = (clr_mask >> 8) & 0xFF; if ( ((set_mask_u8 | clr_mask_u8) != 0) && (!register_bits_modify(M_REGCTRL2, set_mask_u8, clr_mask_u8)) ) { return ( DRV_LPS25H_STATUS_CODE_DISALLOWED ); } set_mask_u8 = (set_mask >> 16) & 0xFF; clr_mask_u8 = (clr_mask >> 16) & 0xFF; if ( ((set_mask_u8 | clr_mask_u8) != 0) && (!register_bits_modify(M_REGCTRL3, set_mask_u8, clr_mask_u8)) ) { return ( DRV_LPS25H_STATUS_CODE_DISALLOWED ); } set_mask_u8 = (set_mask >> 24) & 0xFF; clr_mask_u8 = (clr_mask >> 24) & 0xFF; if ( ((set_mask_u8 | clr_mask_u8) != 0) && (!register_bits_modify(M_REGCTRL4, set_mask_u8, clr_mask_u8)) ) { return ( DRV_LPS25H_STATUS_CODE_DISALLOWED ); } return ( DRV_LPS25H_STATUS_CODE_SUCCESS ); } uint32_t drv_lps25h_temperature_get(int32_t * p_temperature_milli_deg) { int16_t tmp_16; if ( two_registers_get(M_REGTEMPOUTL, M_REGTEMPOUTH, (uint16_t *)(&tmp_16)) ) { //T(milli °C) = 42.5 + (TEMP_OUT / 480) * 1000 *p_temperature_milli_deg = (425 + ((int32_t)tmp_16 / 48)) * 100; return ( DRV_LPS25H_STATUS_CODE_SUCCESS ); } return ( DRV_LPS25H_STATUS_CODE_DISALLOWED ); } uint32_t drv_lps25h_pressure_get(uint32_t * p_pressure_pa) { uint32_t tmp_u32; if ( three_registers_get(M_REGPRESSOUTXL, M_REGPRESSOUTL, M_REGPRESSOUTH, &tmp_u32) ) { // Pout(Pa) = (PRESS_OUT * 100) / 4096 *p_pressure_pa = (tmp_u32 * 100) / 4096; return ( DRV_LPS25H_STATUS_CODE_SUCCESS ); } return ( DRV_LPS25H_STATUS_CODE_DISALLOWED ); } uint32_t drv_lps25h_close(void) { if ( hal_twi_close(m_drv_lps25h.p_drv_lps25h_cfg->twi_id) == HAL_TWI_STATUS_CODE_SUCCESS ) { m_drv_lps25h.p_drv_lps25h_cfg = NULL; return ( DRV_LPS25H_STATUS_CODE_SUCCESS ); } return ( DRV_LPS25H_STATUS_CODE_DISALLOWED ); } <file_sep>/examples/ble_peripheral/experimental_ble_app_linking_beacon_solar/src/sensor_beacon_org.c /* Copyright (c) Nordic Semiconductor ASA * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * 3. Neither the name of Nordic Semiconductor ASA nor the names of other * contributors to this software may be used to endorse or promote products * derived from this software without specific prior written permission. * * 4. This software must only be used in a processor manufactured by Nordic * Semiconductor ASA, or in a processor manufactured by a third party that * is used in combination with a processor manufactured by Nordic Semiconductor. * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "hal_radio.h" #include "hal_timer.h" #include "hal_clock.h" #include "drv_lps25h.h" #include "drv_lps25h_bitfields.h" #include "hal_serial.h" #include "hal_twi.h" #include "nrf.h" #include <stdint.h> #include <stdbool.h> #include <string.h> #include <stdlib.h> //#define DBG_RADIO_ACTIVE_ENABLE //#define DBG_BEACON_START_PIN (16) //#define DBG_HFCLK_ENABLED_PIN (27) //#define DBG_HFCLK_DISABLED_PIN (26) //#define DBG_PKT_SENT_PIN (9) //#define DBG_CALCULATE_BEGIN_PIN (15) //#define DBG_CALCULATE_END_PIN (15) //#define DBG_RADIO_ACTIVE_PIN (24) //#define DBG_WFE_BEGIN_PIN (25) //#define DBG_WFE_END_PIN (25) //#define DBG_BEACON_START \ //{ \ // NRF_GPIO->OUTSET = (1 << DBG_BEACON_START_PIN); \ // NRF_GPIO->DIRSET = (1 << DBG_BEACON_START_PIN); \ // NRF_GPIO->DIRCLR = (1 << DBG_BEACON_START_PIN); \ // NRF_GPIO->OUTCLR = (1 << DBG_BEACON_START_PIN); \ //} //#define DBG_HFCLK_ENABLED \ //{ \ // NRF_GPIO->OUTSET = (1 << DBG_HFCLK_ENABLED_PIN); \ // NRF_GPIO->DIRSET = (1 << DBG_HFCLK_ENABLED_PIN); \ // NRF_GPIO->DIRCLR = (1 << DBG_HFCLK_ENABLED_PIN); \ // NRF_GPIO->OUTCLR = (1 << DBG_HFCLK_ENABLED_PIN); \ //} //#define DBG_HFCLK_DISABLED \ //{ \ // NRF_GPIO->OUTSET = (1 << DBG_HFCLK_DISABLED_PIN); \ // NRF_GPIO->DIRSET = (1 << DBG_HFCLK_DISABLED_PIN); \ // NRF_GPIO->DIRCLR = (1 << DBG_HFCLK_DISABLED_PIN); \ // NRF_GPIO->OUTCLR = (1 << DBG_HFCLK_DISABLED_PIN); \ //} //#define DBG_PKT_SENT \ //{ \ // NRF_GPIO->OUTSET = (1 << DBG_PKT_SENT_PIN); \ // NRF_GPIO->DIRSET = (1 << DBG_PKT_SENT_PIN); \ // NRF_GPIO->DIRCLR = (1 << DBG_PKT_SENT_PIN); \ // NRF_GPIO->OUTCLR = (1 << DBG_PKT_SENT_PIN); \ //} //#define DBG_WFE_BEGIN \ //{ \ // NRF_GPIO->OUTCLR = (1 << DBG_WFE_BEGIN_PIN); \ // NRF_GPIO->DIRSET = (1 << DBG_WFE_BEGIN_PIN); \ // NRF_GPIO->OUTSET = (1 << DBG_WFE_BEGIN_PIN); \ // for ( int i = 0; i < 0xFF; i++ ) __NOP();\ // NRF_GPIO->OUTCLR = (1 << DBG_WFE_BEGIN_PIN); \ //} //#define DBG_WFE_END \ //{ \ // for ( int i = 0; i < 0xFF; i++ ) __NOP();\ // NRF_GPIO->OUTSET = (1 << DBG_WFE_END_PIN); \ // /*NRF_GPIO->DIRSET = (1 << DBG_WFE_END_PIN);*/ \ //} #ifndef DBG_BEACON_START #define DBG_BEACON_START #endif #ifndef DBG_PKT_SENT #define DBG_PKT_SENT #endif #ifndef DBG_HFCLK_ENABLED #define DBG_HFCLK_ENABLED #endif #ifndef DBG_HFCLK_DISABLED #define DBG_HFCLK_DISABLED #endif #ifndef DBG_WFE_BEGIN #define DBG_WFE_BEGIN #endif #ifndef DBG_WFE_END #define DBG_WFE_END #endif #ifdef PCA20014 static const hal_serial_cfg_t serial_cfg = { .twi0.psel.scl = 27, .twi0.psel.sda = 26, }; #else #ifdef PCA10036 static const hal_serial_cfg_t serial_cfg = { .twi0.psel.scl = 25, .twi0.psel.sda = 23, }; #else static const hal_serial_cfg_t serial_cfg = { .twi0.psel.scl = 29, .twi0.psel.sda = 25, }; #endif #endif #ifdef TEMPERATURE_AND_PRESSURE_BEACON #define M_BEACON_PDU_TYPE M_BEACON_PDU_TYPE_TEMP_PRES #endif #ifdef TEMPERATURE_ONLY_BEACON #define M_BEACON_PDU_TYPE M_BEACON_PDU_TYPE_TEMP_ONLY #endif #define HFCLK_STARTUP_TIME_US (1600) /* The time in microseconds it takes to start up the HF clock*. */ #define INTERVAL_US (1000000) /* The time in microseconds between advertising events. */ #define INITIAL_TIMEOUT (INTERVAL_US) /* The time in microseconds until adverising the first time. */ #define START_OF_INTERVAL_TO_SENSOR_READ_TIME_US (INTERVAL_US / 2) /* The time from the start of the latest advertising event until reading the sensor. */ #define SENSOR_SKIP_READ_COUNT (10) /* The number of advertising events between reading the sensor. */ #if INITIAL_TIMEOUT - HFCLK_STARTUP_TIME_US < 400 #error "Initial timeout too short!" #endif #define BD_ADDR_OFFS (3) /* BLE device address offest of the beacon advertising pdu. */ #define M_BD_ADDR_SIZE (6) /* BLE device address size. */ /* Begin - Definitions for beacons with both temperature and pressure. */ #define SINT16_TEMPERATURE_OFFS (20) /* The offset of the temperature in the beacon advertising pdu */ #define UINT32_PRESSURE_OFFS (26) /* The offset of the pressure in the beacon advertising pdu */ /* End - Definitions for beacons with both temperature and pressure. */ /* Begin - Definitions for beacons with only temperature. */ #define FLOAT32_TEMPERATURE_OFFS (36) /* The offset of the temperature in the beacon advertising pdu */ /* End - Definitions for beacons with only temperature. */ /* The beacon types. */ typedef enum { M_BEACON_PDU_TYPE_TEMP_ONLY = 0, ///< Beacon with only temperature data. M_BEACON_PDU_TYPE_TEMP_PRES, ///< Beacon with both temperature and pressure data. } m_beacon_pdu_type_t; static bool volatile m_radio_isr_called; /* Indicates that the radio ISR has executed. */ static bool volatile m_rtc_isr_called; /* Indicates that the RTC ISR has executed. */ static uint32_t m_time_us; /* Keeps track of the latest scheduled point in time. */ static uint32_t m_skip_read_counter = 0; /* Keeps track on when to read the sensor. */ static uint8_t m_adv_pdu[40]; /* The RAM representation of the advertising PDU. */ /* Initializes the beacon advertising PDU. */ static void m_beacon_pdu_init(uint8_t * p_beacon_pdu) { p_beacon_pdu[0] = 0x42; p_beacon_pdu[1] = 0; p_beacon_pdu[2] = 0; } /* Sets the BLE address field in the sensor beacon PDU. */ static void m_beacon_pdu_bd_addr_default_set(uint8_t * p_beacon_pdu) { if ( ( NRF_FICR->DEVICEADDR[0] != 0xFFFFFFFF) || ((NRF_FICR->DEVICEADDR[1] & 0xFFFF) != 0xFFFF) ) { p_beacon_pdu[BD_ADDR_OFFS ] = (NRF_FICR->DEVICEADDR[0] ) & 0xFF; p_beacon_pdu[BD_ADDR_OFFS + 1] = (NRF_FICR->DEVICEADDR[0] >> 8) & 0xFF; p_beacon_pdu[BD_ADDR_OFFS + 2] = (NRF_FICR->DEVICEADDR[0] >> 16) & 0xFF; p_beacon_pdu[BD_ADDR_OFFS + 3] = (NRF_FICR->DEVICEADDR[0] >> 24) ; p_beacon_pdu[BD_ADDR_OFFS + 4] = (NRF_FICR->DEVICEADDR[1] ) & 0xFF; p_beacon_pdu[BD_ADDR_OFFS + 5] = (NRF_FICR->DEVICEADDR[1] >> 8) & 0xFF; } else { static const uint8_t random_bd_addr[M_BD_ADDR_SIZE] = {0xE2, 0xA3, 0x01, 0xE7, 0x61, 0xF7}; memcpy(&(p_beacon_pdu[3]), &(random_bd_addr[0]), M_BD_ADDR_SIZE); } p_beacon_pdu[1] = (p_beacon_pdu[1] == 0) ? M_BD_ADDR_SIZE : p_beacon_pdu[1]; } /* Resets the sensor data of the sensor beacon PDU. */ static void m_beacon_pdu_sensor_data_reset(uint8_t * p_beacon_pdu, m_beacon_pdu_type_t beacon_pdu_type) { switch ( beacon_pdu_type ) { case M_BEACON_PDU_TYPE_TEMP_ONLY: { static const uint8_t beacon_temp_only[31] = { 0x02, 0x01, 0x04, 0x03, 0x19, 0x00, 0x03, 0x07, 0x09, 0x54, 0x65, 0x6D, 0x70, 0x6F, 0x20, 0x07, 0x03, 0x02, 0x18, 0x09, 0x18, 0x0A, 0x18, 0x07, 0x16, 0x09, 0x18, 0xA3, 0x70, 0x45, 0x41, }; memcpy(&(p_beacon_pdu[3 + M_BD_ADDR_SIZE]), &(beacon_temp_only[0]), sizeof(beacon_temp_only)); p_beacon_pdu[1] = M_BD_ADDR_SIZE + sizeof(beacon_temp_only); } break; case M_BEACON_PDU_TYPE_TEMP_PRES: { static const uint8_t beacon_temp_pres[21] = { 0x02, 0x01, 0x04, 0x03, 0x03, 0xE5, 0xFE, /* Entry for temperature characteristics. Ref: sint16, https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.temperature.xml */ 0x05, 0x16, 0x6E, 0x2A, 0x00, 0x00, /* Entry for pressure characteristics. Ref: uint32, https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.pressure.xml */ 0x07, 0x16, 0x6D, 0x2A, 0x00, 0x00, 0x00, 0x00, }; memcpy(&(p_beacon_pdu[3 + M_BD_ADDR_SIZE]), &(beacon_temp_pres[0]), sizeof(beacon_temp_pres)); p_beacon_pdu[1] = M_BD_ADDR_SIZE + sizeof(beacon_temp_pres); } break; default: break; } } /* Sets the sensor data of the sensor beacon PDU. */ static void m_beacon_pdu_sensor_data_set(uint8_t * p_beacon_pdu, int32_t *p_temperature, uint32_t *p_pressure) { if ( (p_pressure != NULL)&& (p_temperature != NULL) ) { /* Pressure (Bluetooth standard) is in Pascal with one decimal, so multiplying the value by 10. */ p_beacon_pdu[UINT32_PRESSURE_OFFS ] = ((*p_pressure * 10) ) & 0xFF; p_beacon_pdu[UINT32_PRESSURE_OFFS + 1] = ((*p_pressure * 10) >> 8) & 0xFF; p_beacon_pdu[UINT32_PRESSURE_OFFS + 2] = ((*p_pressure * 10) >> 16) & 0xFF; /* The temperature (Bluetooth standard) is in Celsius with two decimals, so deviding the value by an additional 10. */ p_beacon_pdu[SINT16_TEMPERATURE_OFFS ] = ((*p_temperature / 10) ) & 0xFF; p_beacon_pdu[SINT16_TEMPERATURE_OFFS + 1] = ((*p_temperature / 10) >> 8) & 0xFF; } else if ( p_temperature != NULL ) { /* The temperature is in Celsius with one decimal, so deviding the value by an additional 100. */ p_beacon_pdu[FLOAT32_TEMPERATURE_OFFS ] = ((*p_temperature / 100) ) & 0xFF; p_beacon_pdu[FLOAT32_TEMPERATURE_OFFS + 1] = ((*p_temperature / 100) >> 8) & 0xFF; p_beacon_pdu[FLOAT32_TEMPERATURE_OFFS + 2] = 0x00; p_beacon_pdu[FLOAT32_TEMPERATURE_OFFS + 3] = 0xFF; } } /* Waits for the next NVIC event. */ static void __forceinline cpu_wfe(void) { DBG_WFE_BEGIN; __WFE(); __SEV(); __WFE(); DBG_WFE_END; } /* Hook for the access mode feature of the lps25h driver. */ static void cpu_sleep_hook(void) { cpu_wfe(); } /* Powers up the the lps25h device and TWI pull-up resistors. */ static void sensor_chip_powerup(void) { NRF_GPIO->OUTSET = (1 << 5) | (1 << 8); NRF_GPIO->OUTSET = (1 << 7); NRF_GPIO->DIRSET = (1 << 5) | (1 << 8); NRF_GPIO->DIRSET = (1 << 7); } /* Sets up the the lps25h device to measure temperature and pressure. */ static bool sensor_chip_measurement_setup(void) { static const drv_lps25h_cfg_t m_drv_lps25h_cfg = { .twi_id = HAL_TWI_ID_TWI0, .twi_cfg.address = (0x5C << TWI_ADDRESS_ADDRESS_Pos), .twi_cfg.frequency = (TWI_FREQUENCY_FREQUENCY_K400 << TWI_FREQUENCY_FREQUENCY_Pos), .p_sleep_hook = cpu_sleep_hook, }; if ( drv_lps25h_open(&m_drv_lps25h_cfg) == DRV_LPS25H_STATUS_CODE_SUCCESS ) { drv_lps25h_access_mode_set(DRV_LPS25H_ACCESS_MODE_CPU_INACTIVE); drv_lps25h_ctrl_reg_modify((DRV_LSP25H_CTRL_REG_PD_Active << DRV_LSP25H_CTRL_REG_PD_Pos) | (DRV_LSP25H_CTRL_REG_ODR_12HZ5 << DRV_LSP25H_CTRL_REG_ODR_Pos), 0); return ( true ); } else { (void)drv_lps25h_close(); } return ( false ); } /* Ends after measuring temperature and pressure. */ static void sensor_chip_measurement_done(void) { (void)drv_lps25h_close(); } /* Sends an advertising PDU on the given channel index. */ static void send_one_packet(uint8_t channel_index) { uint8_t i; m_radio_isr_called = false; hal_radio_channel_index_set(channel_index); hal_radio_send(m_adv_pdu); while ( !m_radio_isr_called ) { cpu_wfe(); } for ( i = 0; i < 9; i++ ) { __NOP(); } } /* Powers down the the lps25h device and TWI pull-up resistors. */ static void sensor_chip_powerdown(void) { NRF_GPIO->DIRCLR = (1 << 5) | (1 << 7) | (1 << 8); } /* Handles sensor managing. */ static void sensor_handler(uint32_t start_time_us, uint32_t retry_interval_us, uint8_t retry_count) { uint8_t status; int32_t temperature; uint32_t pressure; if ( sensor_chip_measurement_setup() ) { for ( int i = 0; i < retry_count; i++ ) { m_rtc_isr_called = false; hal_timer_timeout_set(start_time_us + (i * retry_interval_us)); while ( !m_rtc_isr_called ) { cpu_wfe(); } drv_lps25h_status_reg_get(&status); if ( ((status & (DRV_LSP25H_STATUS_REG_T_DA_Available << DRV_LSP25H_STATUS_REG_T_DA_Pos)) != 0) && ((status & (DRV_LSP25H_STATUS_REG_P_DA_Available << DRV_LSP25H_STATUS_REG_P_DA_Pos)) != 0) ) { break; } } if ( ((status & (DRV_LSP25H_STATUS_REG_T_DA_Available << DRV_LSP25H_STATUS_REG_T_DA_Pos)) != 0) && ((status & (DRV_LSP25H_STATUS_REG_P_DA_Available << DRV_LSP25H_STATUS_REG_P_DA_Pos)) != 0) ) { if ( M_BEACON_PDU_TYPE == M_BEACON_PDU_TYPE_TEMP_ONLY ) { drv_lps25h_temperature_get(&temperature); m_beacon_pdu_sensor_data_set(&(m_adv_pdu[0]), &temperature, NULL); } else if ( M_BEACON_PDU_TYPE == M_BEACON_PDU_TYPE_TEMP_PRES ) { drv_lps25h_pressure_get(&pressure); drv_lps25h_temperature_get(&temperature); m_beacon_pdu_sensor_data_set(&(m_adv_pdu[0]), &temperature, &pressure); } } else { m_beacon_pdu_sensor_data_reset(&(m_adv_pdu[0]), M_BEACON_PDU_TYPE); } sensor_chip_measurement_done(); } sensor_chip_powerdown(); } /* Handles beacon managing. */ static void beacon_handler(void) { hal_radio_reset(); hal_timer_start(); m_time_us = INITIAL_TIMEOUT - HFCLK_STARTUP_TIME_US; do { if ( m_skip_read_counter == 0 ) { m_rtc_isr_called = false; hal_timer_timeout_set(m_time_us - START_OF_INTERVAL_TO_SENSOR_READ_TIME_US); while ( !m_rtc_isr_called ) { cpu_wfe(); } sensor_chip_powerup(); m_rtc_isr_called = false; hal_timer_timeout_set(m_time_us - START_OF_INTERVAL_TO_SENSOR_READ_TIME_US + 10000); while ( !m_rtc_isr_called ) { cpu_wfe(); } sensor_handler(m_time_us - START_OF_INTERVAL_TO_SENSOR_READ_TIME_US + 40000, 10000, 10); } m_skip_read_counter = ( (m_skip_read_counter + 1) < SENSOR_SKIP_READ_COUNT ) ? (m_skip_read_counter + 1) : 0; m_rtc_isr_called = false; hal_timer_timeout_set(m_time_us); while ( !m_rtc_isr_called ) { cpu_wfe(); } hal_clock_hfclk_enable(); DBG_HFCLK_ENABLED; m_rtc_isr_called = false; m_time_us += HFCLK_STARTUP_TIME_US; hal_timer_timeout_set(m_time_us); while ( !m_rtc_isr_called ) { cpu_wfe(); } send_one_packet(37); DBG_PKT_SENT; send_one_packet(38); DBG_PKT_SENT; send_one_packet(39); DBG_PKT_SENT; hal_clock_hfclk_disable(); DBG_HFCLK_DISABLED; m_time_us = m_time_us + (INTERVAL_US - HFCLK_STARTUP_TIME_US); } while ( 1 ); } int main(void) { DBG_BEACON_START; NRF_GPIO->OUTCLR = 0xFFFFFFFF; NRF_GPIO->DIRCLR = 0xFFFFFFFF; #ifdef DBG_WFE_BEGIN_PIN NRF_GPIO->OUTSET = (1 << DBG_WFE_BEGIN_PIN); NRF_GPIO->DIRSET = (1 << DBG_WFE_BEGIN_PIN); #endif hal_serial_init(&serial_cfg); hal_twi_init(); drv_lps25h_init(); m_beacon_pdu_init(&(m_adv_pdu[0])); m_beacon_pdu_bd_addr_default_set(&(m_adv_pdu[0])); m_beacon_pdu_sensor_data_reset(&(m_adv_pdu[0]), M_BEACON_PDU_TYPE); #ifdef DBG_RADIO_ACTIVE_ENABLE NRF_GPIOTE->CONFIG[0] = (GPIOTE_CONFIG_POLARITY_Toggle << GPIOTE_CONFIG_POLARITY_Pos) | (DBG_RADIO_ACTIVE_PIN << GPIOTE_CONFIG_PSEL_Pos) | (GPIOTE_CONFIG_MODE_Task << GPIOTE_CONFIG_MODE_Pos); NRF_PPI->CH[5].TEP = (uint32_t)&(NRF_GPIOTE->TASKS_OUT[0]); NRF_PPI->CH[5].EEP = (uint32_t)&(NRF_RADIO->EVENTS_READY); NRF_PPI->CH[6].TEP = (uint32_t)&(NRF_GPIOTE->TASKS_OUT[0]); NRF_PPI->CH[6].EEP = (uint32_t)&(NRF_RADIO->EVENTS_DISABLED); NRF_PPI->CHENSET = (PPI_CHEN_CH5_Enabled << PPI_CHEN_CH5_Pos) | (PPI_CHEN_CH6_Enabled << PPI_CHEN_CH6_Pos); #endif for (;;) { beacon_handler(); } } void RADIO_IRQHandler(void) { NRF_RADIO->EVENTS_DISABLED = 0; m_radio_isr_called = true; } void RTC0_IRQHandler(void) { NRF_RTC0->EVTENCLR = (RTC_EVTENCLR_COMPARE0_Enabled << RTC_EVTENCLR_COMPARE0_Pos); NRF_RTC0->INTENCLR = (RTC_INTENCLR_COMPARE0_Enabled << RTC_INTENCLR_COMPARE0_Pos); NRF_RTC0->EVENTS_COMPARE[0] = 0; m_rtc_isr_called = true; } <file_sep>/components/ble/ble_services/experimental_ble_pdlp/ble_pdlp_common.c /* Copyright (c) 2016 Nordic Semiconductor. All Rights Reserved. * * The information contained herein is property of Nordic Semiconductor ASA. * Terms and conditions of usage are described in detail in NORDIC * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. * * Licensees are granted free, non-transferable use of the information. NO * WARRANTY of ANY KIND is provided. This heading must NOT be removed from * the file. * */ #include "ble_pdlp_common.h" //Single precision (float) gives 23 bits of significand, 8 bits of exponent, and 1 sign bit. //Double precision (double) gives 52 bits of significand, 11 bits of exponent, and 1 sign bit. // After IEEE754 conversion by the union structure // The sign is stored in bit 32. // The exponent can be computed from bits 24-31 by subtracting 127. // The mantissa (also known as significand or fraction) is stored in bits 1-23 // Reference http://www.h-schmidt.net/FloatConverter/IEEE754.html union IEEE754_Converter{ float f_val; union { signed int s_val; unsigned int u_val; } i_val; }; // Convert a float to 12-bit IEEE754 format (ID1) as described by Linking spec) // bit 11 sign // bit 7-10 exponent // bit 0-6 fraction uint16_t IEEE754_Convert_Temperature(float f_value) { union IEEE754_Converter value; value.f_val = f_value; int8_t sign = ( value.i_val.s_val >> 31) & 0x1; int8_t exponent = (((value.i_val.s_val >> 23) & 0xFF) - 127 + 7); // 4-bit, with DoCoMo adjustment int16_t fraction = (( value.i_val.s_val & 0x7FFFFF) >> 16); // 7-bit if (f_value == 0.0f) { // Zero return (sign<<11); } else if (exponent == 0) { // Non-normalization return (sign<<11) | ((fraction&0x7F) + 0x1); // Rounding (due to double precision) } else if (exponent == 0xF) { // Maximal return ((sign<<11) | (exponent<<8)); } else { // Normalization return (sign<<11) | (exponent<<7) | (fraction&0x7F); } } // Convert a float to 12-bit IEEE754 format (ID2) as described by Linking spec) // bit 8-11 exponent // bit 0-7 fraction uint16_t IEEE754_Convert_Humidity(float f_value) { union IEEE754_Converter value; value.f_val = f_value; uint16_t exponent = ((value.i_val.u_val >> 23) & 0xFF) - 127 + 7; // 4-bit, with DoCoMo adjustment uint16_t fraction = ((value.i_val.u_val & 0x7FFFFF) >> 15); // 8-bit if (f_value == 0.0f) { // Zero return 0x0000; } else if (exponent == 0) { // Non-normalization return (fraction&0xFF) + 0x1; // Rounding (due to double precision) } else if (exponent == 0xF) { // Maximal return (exponent<<8); } else { // Normalization return (exponent<<8) | (fraction&0xFF); } } // Convert a float to 12-bit IEEE754 format (ID3) as described by Linking spec) // bit 7-11 exponent // bit 0-6 fraction uint16_t IEEE754_Convert_Air_Pressure(float f_value) { union IEEE754_Converter value; value.f_val = f_value; uint16_t exponent = ((value.i_val.u_val >> 23) & 0xFF) - 127 + 15; // 4-bit, with DoCoMo adjustment uint16_t fraction = ((value.i_val.u_val & 0x7FFFFF) >> 16); // 7-bit if (f_value == 0.0f) { // Zero return 0x0000; } else if (exponent == 0) { // Non-normalization return (fraction&0x7F) + 0x1; // Rounding (due to double precision) } else if (exponent == 0x1F) { // Maximal return (exponent<<7); } else { // Normalization return (exponent<<7) | (fraction&0x7F); } } // Little-endian encoding uint32_t pdls_encode_service_header(uint8_t *p_buf, uint8_t service_id, uint16_t message_id, uint8_t number_of_param) { *(p_buf+0) = service_id; *(p_buf+1) = (message_id >> 0) & 0xFF; *(p_buf+2) = (message_id >> 8) & 0xFF;; *(p_buf+3) = number_of_param; return 4; } uint32_t pdls_encode_param_uint8(uint8_t *p_buf, uint8_t param_id, uint8_t param_data) { *(p_buf+0) = param_id; *(p_buf+1) = 1; *(p_buf+2) = 0; *(p_buf+3) = 0; *(p_buf+4) = param_data; return 5; } uint32_t pdls_encode_param_uint16(uint8_t *p_buf, uint8_t param_id, uint16_t param_data) { *(p_buf+0) = param_id; *(p_buf+1) = 2; *(p_buf+2) = 0; *(p_buf+3) = 0; *(p_buf+4) = (param_data >> 0) & 0xFF; *(p_buf+5) = (param_data >> 8) & 0xFF; return 6; } uint32_t pdls_encode_param_uint32(uint8_t *p_buf, uint8_t param_id, uint32_t param_data) { *(p_buf+0) = param_id; *(p_buf+1) = 4; *(p_buf+2) = 0; *(p_buf+3) = 0; *(p_buf+4) = (param_data >> 0) & 0xFF; *(p_buf+5) = (param_data >> 8) & 0xFF; *(p_buf+6) = (param_data >> 16) & 0xFF; *(p_buf+7) = (param_data >> 24) & 0xFF; return 8; } uint32_t pdls_encode_param_opaque(uint8_t *p_buf, uint8_t param_id, pdlp_opaque_t *p_param_data) { *(p_buf+0) = param_id; *(p_buf+1) = (p_param_data->len >>0) & 0xFF; *(p_buf+2) = (p_param_data->len >>8) & 0xFF; *(p_buf+3) = (p_param_data->len >>16) & 0xFF; for (int i=0; i<p_param_data->len; i++) { *(p_buf+4+i) = *(p_param_data->p_val+i); } return 4+p_param_data->len; } ble_pdls_result_code_t pdls_decode_param_uint8(uint8_t *p_buf, uint8_t param_id, uint8_t *p_param_data) { uint32_t len; if (*(p_buf+0) != param_id) { return PDLS_RESULT_ERROR_NO_DATA; } len = *(p_buf+1) | *(p_buf+2)<<8 | *(p_buf+3) <<16; if (len != 0x01) { return PDLS_RESULT_ERROR_NO_DATA; } *p_param_data = *(p_buf+4); return PDLS_RESULT_OK; } ble_pdls_result_code_t pdls_decode_param_uint16(uint8_t *p_buf, uint8_t param_id, uint16_t *p_param_data) { uint32_t len; if (*(p_buf+0) != param_id) { return PDLS_RESULT_ERROR_NO_DATA; } len = *(p_buf+1) | *(p_buf+2)<<8 | *(p_buf+3) <<16; if (len != 0x02) { return PDLS_RESULT_ERROR_NO_DATA; } *p_param_data = *(p_buf+4) | *(p_buf+5)<<8; return PDLS_RESULT_OK; } ble_pdls_result_code_t pdls_decode_param_uint32(uint8_t *p_buf, uint8_t param_id, uint32_t *p_param_data) { uint32_t len; if (*(p_buf+0) != param_id) { return PDLS_RESULT_ERROR_NO_DATA; } len = *(p_buf+1) | *(p_buf+2)<<8 | *(p_buf+3) <<16; if (len != 0x04) { return PDLS_RESULT_ERROR_NO_DATA; } *p_param_data = *(p_buf+4) | *(p_buf+5)<<8 | *(p_buf+6)<<16 | *(p_buf+7)<<24; return PDLS_RESULT_OK; } ble_pdls_result_code_t pdls_decode_param_opaque(uint8_t *p_buf, uint8_t param_id, pdlp_opaque_t *p_param_data) { if (*(p_buf+0) != param_id) { return PDLS_RESULT_ERROR_NO_DATA; } p_param_data->len = *(p_buf+1) | *(p_buf+2)<<8 | *(p_buf+3) <<16; p_param_data->p_val = p_buf+4; return PDLS_RESULT_OK; } <file_sep>/components/ble/ble_services/experimental_ble_pdlp/ble_pdlp_beacon.h /* Copyright (c) 2016 Nordic Semiconductor. All Rights Reserved. * * The information contained herein is property of Nordic Semiconductor ASA. * Terms and conditions of usage are described in detail in NORDIC * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. * * Licensees are granted free, non-transferable use of the information. NO * WARRANTY of ANY KIND is provided. This heading must NOT be removed from * the file. * */ #ifndef BLE_PDLP_BEACON_H__ #define BLE_PDLP_BEACON_H__ #include <stdint.h> #include <stdbool.h> /* Raw radio packets definition */ #define BD_ADDR_OFFS (3) /* BLE device address offest of the beacon advertising pdu. */ #define M_BD_ADDR_SIZE (6) /* BLE device address size. */ #define SINT16_SERVICE_DATA_OFFS (38) /* The offset of the temperature in the beacon advertising pdu */ /* The linking beacon service types based on DoCoMo spec v2.0.2 (2016-08-08) */ enum { LINKING_SERVICE_TYPE_NONE = 0, LINKING_SERVICE_TYPE_TEMPERATURE, LINKING_SERVICE_TYPE_HUMIDITY, LINKING_SERVICE_TYPE_AIRPRESSURE, LINKING_SERVICE_TYPE_BATTERY, LINKING_SERVICE_TYPE_BUTTON, LINKING_SERVICE_TYPE_OPEN_CLOSE_SENSE, LINKING_SERVICE_TYPE_HUMAN_SENSE, LINKING_SERVICE_TYPE_VIBRATION_SENSE, LINKING_SERVICE_TYPE_GENERAL = 15 }; typedef struct { uint16_t service_id:4; uint16_t charge_needed:1; /* 0: not needed; 1: needed */ uint16_t battery_level:11; /* 0.0% ~ 100.0%, no details on float coding yet */ } linking_battery_info_t; #define LINKING_BUTTON_ID_MIN 0 #define LINKING_BUTTON_ID_MAX 4095 typedef struct { uint16_t service_id:4; uint16_t button_id:12; /* 0 ~ 4095 */ } linking_button_info_t; #define LINKING_OPEN_COUNT_MAX 2047 typedef struct { uint16_t service_id:4; uint16_t open_close_flag:1; /* 0: open; 1: close */ uint16_t open_count:11; /* 0 ~ 2047 */ } linking_openclose_sensor_info_t; typedef struct { uint16_t service_id:4; uint16_t human_sensed:1; /* 0: not sensed; 1: sensed */ uint16_t dummy:11; } linking_human_sensor_info_t; typedef struct { uint16_t service_id:4; uint16_t vibration_sensed:1; /* 0: not sensed; 1: sensed */ uint16_t dummy:11; } linking_vibration_sensor_info_t; #endif // BLE_PDLP_BEACON_H__ /** @} */ <file_sep>/examples/ble_peripheral/experimental_ble_app_linking_beacon_solar/external/comp_generic/hal/inc/hal_twi.h /* Copyright (c) Nordic Semiconductor ASA * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * 3. Neither the name of Nordic Semiconductor ASA nor the names of other * contributors to this software may be used to endorse or promote products * derived from this software without specific prior written permission. * * 4. This software must only be used in a processor manufactured by Nordic * Semiconductor ASA, or in a processor manufactured by a third party that * is used in combination with a processor manufactured by Nordic Semiconductor. * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef HAL_TWI_H__ #define HAL_TWI_H__ #include <stdbool.h> #include <stdint.h> /**@brief The bit IDs. */ typedef enum { HAL_TWI_ID_TWI0, HAL_TWI_ID_TWI1, HAL_TWI_ID_NONE, } hal_twi_id_t; /**@brief The twi configuration. */ typedef struct { uint32_t frequency; uint8_t address; } hal_twi_cfg_t; /**@brief The callback signals of the driver. */ typedef enum { HAL_TWI_SIGNAL_TYPE_TX_COMPLETE, ///< Sent when the specified TX buffer has been sent. HAL_TWI_SIGNAL_TYPE_RX_COMPLETE, ///< Sent when the specified number of bytes have been received. HAL_TWI_SIGNAL_TYPE_TX_ERROR, ///< Sent when failed to send the specified buffer. HAL_TWI_SIGNAL_TYPE_RX_ERROR, ///< Sent when failed to receive the specified number of bytes. } hal_twi_signal_type_t; /**@brief The modes for generating stop conditions on the bus. */ typedef enum { HAL_TWI_STOP_MODE_NONE, ///< Do not genarate stop conditions. HAL_TWI_STOP_MODE_STOP_ON_TX_BUF_END, ///< Genarate stop conditions whenever a buffer has been transmitted. HAL_TWI_STOP_MODE_STOP_ON_RX_BUF_END, ///< Genarate stop conditions whenever a buffer has been received. HAL_TWI_STOP_MODE_STOP_ON_ANY, ///< Genarate stop conditions whenever a buffer has been transmitted or received. } hal_twi_stop_mode_t; /**@brief The TWI status codes. */ enum { HAL_TWI_STATUS_CODE_SUCCESS, ///< Successfull. HAL_TWI_STATUS_CODE_WRITE_ERROR, ///< Write failed. HAL_TWI_STATUS_CODE_READ_ERROR, ///< Read failed. HAL_TWI_STATUS_CODE_DISALLOWED, ///< Disallowed. }; /**@brief The type of the signal callback conveying signals from the driver. */ typedef void (*hal_twi_sig_callback_t) (hal_twi_signal_type_t hal_twi_signal_type); /**@brief Initializes the twi interface. */ void hal_twi_init(void); /**@brief Opens the driver to access the specified HW peripheral. * * @param{in] id The id of the HW peripheral to open the driver for. * @param{in] cfg The driver configuration. * * @retval ::HAL_TWI_STATUS_CODE_SUCCESS if successful. * @retval ::HAL_TWI_STATUS_CODE_DISALLOWED if the driver could not be opened. */ uint32_t hal_twi_open(hal_twi_id_t id, hal_twi_cfg_t const * const cfg); /**@brief Sets the callback function. * * @nore Reading and writing data will be blocking calls if no callback is set. * * @param{in] id The id of the HW peripheral to open the driver for. * @param{in] hal_twi_sig_callback The signal callback function, or NULL if not used. */ void hal_twi_callback_set(hal_twi_id_t id, hal_twi_sig_callback_t hal_twi_sig_callback); /**@brief Sets device address. * * @param{in] id The id of the HW peripheral to set the device address for. * @param{in] dev_addr The device address. */ void hal_twi_address_set(hal_twi_id_t id, uint8_t dev_addr); /**@brief Sets stop mode (i.e. when to generate the stop condition on the bus). * * @param{in] id The id of the HW peripheral to set the stop mode for. * @param{in] stop_mode The stop mode. */ void hal_twi_stop_mode_set(hal_twi_id_t id, hal_twi_stop_mode_t stop_mode); /**@brief Writes bytes to a device. * * @note The transmit buffer shall be available to the driver until all bytes * have been sent. * * @param{in] id The id of the HW peripheral to write through. * @param[in] length The number of bytes to transmit from the buffer. * @param{ut] tx_buffer The transmit buffer to use. * * @retval ::HAL_TWI_STATUS_CODE_SUCCESS if successful. * @retval ::HAL_TWI_STATUS_CODE_WRITE_ERROR if the bytes could not be written. */ uint32_t hal_twi_write(hal_twi_id_t id, uint32_t length, uint8_t * tx_buffer); /**@brief Reads bytes from a device. * * @note The receive buffer shall be available to the driver until all bytes * have been received. * * @param{in] id The id of the HW peripheral to read through. * @param{in] length The number of bytes to read from the buffer. * @param{[out] rx_buffer The receive buffer to use. * * @retval ::HAL_TWI_STATUS_CODE_SUCCESS if successful. * @retval ::HAL_TWI_STATUS_CODE_READ_ERROR if the bytes could not be read. */ uint32_t hal_twi_read(hal_twi_id_t id, uint32_t length, uint8_t * rx_buffer); /**@brief Closes the specified driver. * * @param{in] id The id of the HW peripheral to close the driver for. * * @retval ::HAL_TWI_STATUS_CODE_SUCCESS if successful. * @retval ::HAL_TWI_STATUS_CODE_DISALLOWED if the driver could not be closed. */ uint32_t hal_twi_close(hal_twi_id_t id); #endif // HAL_TWI_H__ <file_sep>/examples/ble_peripheral/experimental_ble_app_linking_beacon/deploy/README.adoc = Sensor Beacon Bluetooth Low Energy based beacon implementation with sensors for the nRF52. Works with the nRF52 (tested), but is likely to work for the nRF51 as well (not tested). Power performance is, however, not expected to be as good for the nRF51. == About This project demonstrates the good power performance of the nRF5x Series and the nRF52 Series in particular. The project is not a part of the official Nordic Semiconductor SDK. Developers are anyway welcome to contribute and provide feedback. == Usage The project file for the sensor beacon firmware is located in the sensor_beacon/pca20014/arm4 directory, and is used to generate the firmware so that it can be loaded into the nRF52 of the sensor beacon hardware. The nRF Master Control Panel is available from Google Play and can be used to observe the beacon (temperature and pressure) once the firmware has been loaded and the solar panel is facing light at about 500 LUX. == Getting started To run the beacon, just compile the project located in the sensor_beacon/pca20014/arm4 directory and use the debugger to load the firmware by pressing the load button in the Keil uVision IDE. == Firmware After the initial setup, the firmware will continuously repeat the following steps: * Every 10th advertising event and also before the very first advertising event: ** Power up the sensor and the two-wire interface (TWI). ** Read the sensors. ** Power down the sensor and the TWI. * Switch on the external crystal. * Send beacon packets (once for each advertising channel index (37, 38 & 39)) * Switch off the external crystal. === Initial Setup The initial setup contains the following steps: * Standard Nordic MDK system startup for nRF52 Series. * Initialize drivers for accessing the sensor chip. * Initialize the beacon PDU (Protocol Data Unit). * Set the advertiser address of the PDU. * Reset the sensor data fields of the PDU. * Reset the radio hardware configuration to operate in BLE DD (Bluetooth Low Energy Device Discovery) mode. * Start the RTC (Real Time Counter) peripheral. === Power Management The sensor beacon saves power by putting the CPU to sleep between every step in the firmware sequence above. It also saves power by switching off the crystal oscillator and the power to the sensor chip and the TWI. == Forum http://devzone.nordicsemi.com/[Nordic Developer Zone] == Resources http://www.nordicsemi.com[Nordic Semiconductor Homepage] https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.temperature.xml[Bluetooth temperature characteristics] https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.pressure.xml[Bluetooth pressure characteristics] <file_sep>/examples/ble_peripheral/experimental_ble_app_linking_beacon_solar/external/comp_generic/hal/src/hal_twi.c /* Copyright (c) Nordic Semiconductor ASA * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * 3. Neither the name of Nordic Semiconductor ASA nor the names of other * contributors to this software may be used to endorse or promote products * derived from this software without specific prior written permission. * * 4. This software must only be used in a processor manufactured by Nordic * Semiconductor ASA, or in a processor manufactured by a third party that * is used in combination with a processor manufactured by Nordic Semiconductor. * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "hal_twi.h" #include "hal_serial.h" #include "nrf.h" #include <stdlib.h> #include <stdbool.h> typedef struct { hal_twi_sig_callback_t current_sig_callback; struct { uint8_t * tx; uint8_t * rx; uint8_t tx_index; uint8_t tx_length; uint8_t rx_index; uint8_t rx_length; } current_buffer; enum { STATE_IDLE, STATE_TX, STATE_RX, STATE_TX_ERROR, STATE_RX_ERROR, } state; uint8_t current_address; hal_twi_stop_mode_t current_stop_mode; } hal_twi_t; #ifdef SYS_CFG_USE_TWI0 static hal_twi_t hal_twi0; #endif #ifdef SYS_CFG_USE_TWI1 static hal_twi_t hal_twi1; #endif static void hal_twi_isr_handler(NRF_TWI_Type * twi, hal_twi_t * context); static void hal_twi_stop_check_and_handle(NRF_TWI_Type * twi) { if ( (twi->SHORTS & (TWI_SHORTS_BB_STOP_Enabled << TWI_SHORTS_BB_STOP_Pos)) != 0 ) { while ( twi->EVENTS_STOPPED == 0 ); } } static void hal_twi_tx_shorts_setup(NRF_TWI_Type * twi, hal_twi_t * context) { twi->SHORTS = 0; if ( context->current_buffer.tx_index + 1 < context->current_buffer.tx_length ) { twi->SHORTS = (TWI_SHORTS_BB_SUSPEND_Enabled << TWI_SHORTS_BB_SUSPEND_Pos); } else { if ( (context->current_stop_mode == HAL_TWI_STOP_MODE_STOP_ON_ANY) || (context->current_stop_mode == HAL_TWI_STOP_MODE_STOP_ON_TX_BUF_END) ) { twi->EVENTS_STOPPED = 0; twi->SHORTS = (TWI_SHORTS_BB_STOP_Enabled << TWI_SHORTS_BB_STOP_Pos); } } } static void hal_twi_rx_shorts_setup(NRF_TWI_Type * twi, hal_twi_t * context) { twi->SHORTS = 0; if ( context->current_buffer.rx_index + 1 < context->current_buffer.rx_length ) { twi->SHORTS = (TWI_SHORTS_BB_SUSPEND_Enabled << TWI_SHORTS_BB_SUSPEND_Pos); } else { if ( (context->current_stop_mode == HAL_TWI_STOP_MODE_STOP_ON_ANY) || (context->current_stop_mode == HAL_TWI_STOP_MODE_STOP_ON_RX_BUF_END) ) { twi->EVENTS_STOPPED = 0; twi->SHORTS = (TWI_SHORTS_BB_STOP_Enabled << TWI_SHORTS_BB_STOP_Pos); } } } void hal_twi_init(void) { #ifdef SYS_CFG_USE_TWI0 hal_twi0.current_sig_callback = NULL; hal_twi0.current_stop_mode = HAL_TWI_STOP_MODE_NONE; hal_twi0.current_address = 0; hal_twi0.state = STATE_IDLE; hal_twi0.current_sig_callback = NULL; #endif #ifdef SYS_CFG_USE_TWI1 hal_twi1.current_sig_callback = NULL; hal_twi1.current_stop_mode = HAL_TWI_STOP_MODE_NONE; hal_twi1.current_address = 0; hal_twi1.state = STATE_IDLE; hal_twi1.current_sig_callback = NULL; #endif } uint32_t hal_twi_open(hal_twi_id_t id, hal_twi_cfg_t const * const cfg) { switch ( id ) { #ifdef SYS_CFG_USE_TWI0 case HAL_TWI_ID_TWI0: if ( hal_serial_id_acquire(HAL_SERIAL_ID_TWI0) ) { NRF_TWI0->ADDRESS = cfg->address; NRF_TWI0->FREQUENCY = cfg->frequency; return ( HAL_TWI_STATUS_CODE_SUCCESS ); } break; #endif #ifdef SYS_CFG_USE_TWI1 case HAL_TWI_ID_TWI1: if ( hal_serial_id_acquire(HAL_SERIAL_ID_TWI1) ) { NRF_TWI1->ADDRESS = cfg->address; NRF_TWI1->FREQUENCY = cfg->frequency; return ( HAL_TWI_STATUS_CODE_SUCCESS ); } break; #endif default: break; } return ( HAL_TWI_STATUS_CODE_DISALLOWED ); } uint32_t hal_twi_close(hal_twi_id_t id) { switch ( id ) { #ifdef SYS_CFG_USE_TWI0 case HAL_TWI_ID_TWI0: return ( (hal_serial_id_release(HAL_SERIAL_ID_TWI0)) ? HAL_TWI_STATUS_CODE_SUCCESS : HAL_TWI_STATUS_CODE_DISALLOWED ); #endif #ifdef SYS_CFG_USE_TWI1 case HAL_TWI_ID_TWI1: return ( (hal_serial_id_release(HAL_SERIAL_ID_TWI1)) ? HAL_TWI_STATUS_CODE_SUCCESS : HAL_TWI_STATUS_CODE_DISALLOWED ); #endif default: break; } return ( HAL_TWI_STATUS_CODE_DISALLOWED ); } void hal_twi_callback_set(hal_twi_id_t id, hal_twi_sig_callback_t hal_twi_sig_callback) { switch ( id ) { #ifdef SYS_CFG_USE_TWI0 case HAL_TWI_ID_TWI0: hal_twi0.current_sig_callback = hal_twi_sig_callback; NRF_TWI0->INTENCLR = 0xFFFFFFFF; NRF_TWI0->EVENTS_ERROR = 0; break; #endif #ifdef SYS_CFG_USE_TWI1 case HAL_TWI_ID_TWI1: hal_twi1.current_sig_callback = hal_twi_sig_callback; NRF_TWI1->INTENCLR = 0xFFFFFFFF; NRF_TWI1->EVENTS_ERROR = 0; break; #endif default: break; } } void hal_twi_address_set(hal_twi_id_t id, uint8_t dev_addr) { switch ( id ) { #ifdef SYS_CFG_USE_TWI0 case HAL_TWI_ID_TWI0: hal_twi0.current_address = dev_addr & 0x7F; NRF_TWI0->ADDRESS = (hal_twi0.current_address << TWI_ADDRESS_ADDRESS_Pos); break; #endif #ifdef SYS_CFG_USE_TWI1 case HAL_TWI_ID_TWI1: hal_twi1.current_address = dev_addr & 0x7F; NRF_TWI1->ADDRESS = (hal_twi1.current_address << TWI_ADDRESS_ADDRESS_Pos); break; #endif default: break; } } void hal_twi_stop_mode_set(hal_twi_id_t id, hal_twi_stop_mode_t stop_mode) { switch ( id ) { #ifdef SYS_CFG_USE_TWI0 case HAL_TWI_ID_TWI0: hal_twi0.current_stop_mode = stop_mode; break; #endif #ifdef SYS_CFG_USE_TWI1 case HAL_TWI_ID_TWI1: hal_twi1.current_stop_mode = stop_mode; break; #endif default: break; } } static uint32_t write_start(NRF_TWI_Type * twi, hal_twi_t * context, uint32_t length, uint8_t * tx_buffer) { if ( (context->state == STATE_TX) || (context->state == STATE_RX) ) { return ( HAL_TWI_STATUS_CODE_DISALLOWED ); } else { if ( context->state != STATE_TX_ERROR ) { context->current_buffer.tx_index = 0; } context->state = STATE_TX; context->current_buffer.tx = tx_buffer; context->current_buffer.tx_length = length; } twi->INTENCLR = ( (TWI_INTENCLR_ERROR_Clear << TWI_INTENSET_ERROR_Pos) | (TWI_INTENCLR_TXDSENT_Clear << TWI_INTENCLR_TXDSENT_Pos) | (TWI_INTENCLR_RXDREADY_Clear << TWI_INTENCLR_RXDREADY_Pos) ); twi->EVENTS_ERROR = 0; twi->EVENTS_TXDSENT = 0; twi->EVENTS_RXDREADY = 0; hal_twi_tx_shorts_setup(twi, context); twi->TXD = context->current_buffer.tx[context->current_buffer.tx_index]; if ( context->current_sig_callback == NULL ) { twi->TASKS_STARTTX = 1; hal_twi_isr_handler(twi, context); } else { twi->INTENSET = (TWI_INTENSET_TXDSENT_Enabled << TWI_INTENSET_TXDSENT_Pos) | (TWI_INTENSET_ERROR_Enabled << TWI_INTENSET_ERROR_Pos); twi->TASKS_STARTTX = 1; } return ( (context->state == STATE_TX_ERROR) ? HAL_TWI_STATUS_CODE_WRITE_ERROR : HAL_TWI_STATUS_CODE_SUCCESS ); } uint32_t hal_twi_write(hal_twi_id_t id, uint32_t length, uint8_t * tx_buffer) { switch ( id ) { #ifdef SYS_CFG_USE_TWI0 case HAL_TWI_ID_TWI0: return ( write_start(NRF_TWI0, &hal_twi0, length, tx_buffer) ); #endif #ifdef SYS_CFG_USE_TWI1 case HAL_TWI_ID_TWI1: return ( write_start(NRF_TWI1, &hal_twi1, length, tx_buffer) ); #endif default: return ( HAL_TWI_STATUS_CODE_WRITE_ERROR ); } } static uint32_t read_start(NRF_TWI_Type * twi, hal_twi_t * context, uint32_t length, uint8_t * rx_buffer) { if ( (context->state == STATE_TX) || (context->state == STATE_RX) ) { return ( HAL_TWI_STATUS_CODE_DISALLOWED ); } else { if ( context->state != STATE_RX_ERROR ) { context->current_buffer.rx_index = 0; } context->state = STATE_RX; context->current_buffer.rx = rx_buffer; context->current_buffer.rx_length = length; } twi->INTENCLR = ( (TWI_INTENCLR_ERROR_Clear << TWI_INTENSET_ERROR_Pos) | (TWI_INTENCLR_TXDSENT_Clear << TWI_INTENCLR_TXDSENT_Pos) | (TWI_INTENCLR_RXDREADY_Clear << TWI_INTENCLR_RXDREADY_Pos) ); twi->EVENTS_ERROR = 0; twi->EVENTS_TXDSENT = 0; twi->EVENTS_RXDREADY = 0; hal_twi_rx_shorts_setup(twi, context); if ( context->current_sig_callback == NULL ) { twi->TASKS_STARTRX = 1; hal_twi_isr_handler(twi, context); } else { twi->INTENSET = (TWI_INTENSET_RXDREADY_Enabled << TWI_INTENSET_RXDREADY_Pos) | (TWI_INTENSET_ERROR_Enabled << TWI_INTENSET_ERROR_Pos); twi->TASKS_STARTRX = 1; } return ( (context->state == STATE_RX_ERROR) ? HAL_TWI_STATUS_CODE_READ_ERROR : HAL_TWI_STATUS_CODE_SUCCESS ); } uint32_t hal_twi_read(hal_twi_id_t id, uint32_t length, uint8_t * rx_buffer) { switch ( id ) { #ifdef SYS_CFG_USE_TWI0 case HAL_TWI_ID_TWI0: return ( read_start(NRF_TWI0, &hal_twi0, length, rx_buffer) ); #endif #ifdef SYS_CFG_USE_TWI1 case HAL_TWI_ID_TWI1: return ( read_start(NRF_TWI1, &hal_twi1, length, rx_buffer) ); #endif default: return ( HAL_TWI_STATUS_CODE_READ_ERROR ); } } static void hal_twi_isr_handler(NRF_TWI_Type * twi, hal_twi_t * context) { bool done = (context->current_sig_callback != NULL); do { if ( context->state == STATE_TX ) { if ( twi->EVENTS_TXDSENT != 0 ) { twi->EVENTS_TXDSENT = 0; ++context->current_buffer.tx_index; if ( context->current_buffer.tx_index < context->current_buffer.tx_length ) { hal_twi_tx_shorts_setup(twi, context); twi->TXD = context->current_buffer.tx[context->current_buffer.tx_index]; twi->TASKS_RESUME = 1; } else { twi->INTENCLR = (TWI_INTENCLR_TXDSENT_Clear << TWI_INTENCLR_TXDSENT_Pos) | (TWI_INTENCLR_ERROR_Clear << TWI_INTENSET_ERROR_Pos); hal_twi_stop_check_and_handle(twi); context->state = STATE_IDLE; if ( context->current_sig_callback != NULL ) { context->current_sig_callback(HAL_TWI_SIGNAL_TYPE_TX_COMPLETE); } done = true; } } else if ( twi->EVENTS_ERROR != 0 ) { twi->EVENTS_ERROR = 0; twi->INTENCLR = (TWI_INTENCLR_TXDSENT_Clear << TWI_INTENCLR_TXDSENT_Pos) | (TWI_INTENCLR_ERROR_Clear << TWI_INTENSET_ERROR_Pos); //hal_twi_stop_check_and_handle(twi); context->state = STATE_TX_ERROR; if ( context->current_sig_callback != NULL ) { context->current_sig_callback(HAL_TWI_SIGNAL_TYPE_TX_ERROR); } done = true; } } else if ( context->state == STATE_RX ) { if ( twi->EVENTS_RXDREADY != 0 ) { twi->EVENTS_RXDREADY = 0; context->current_buffer.rx[context->current_buffer.rx_index] = twi->RXD; ++context->current_buffer.rx_index; if ( context->current_buffer.rx_index < context->current_buffer.rx_length ) { hal_twi_rx_shorts_setup(twi, context); twi->TASKS_RESUME = 1; } else { twi->INTENCLR = (TWI_INTENCLR_RXDREADY_Clear << TWI_INTENCLR_RXDREADY_Pos) | (TWI_INTENCLR_ERROR_Clear << TWI_INTENSET_ERROR_Pos); hal_twi_stop_check_and_handle(twi); context->state = STATE_IDLE; if ( context->current_sig_callback != NULL ) { context->current_sig_callback(HAL_TWI_SIGNAL_TYPE_RX_COMPLETE); } done = true; } } else if ( twi->EVENTS_ERROR != 0 ) { twi->EVENTS_ERROR = 0; twi->INTENCLR = (TWI_INTENCLR_RXDREADY_Clear << TWI_INTENCLR_RXDREADY_Pos) | (TWI_INTENCLR_ERROR_Clear << TWI_INTENSET_ERROR_Pos); //hal_twi_stop_check_and_handle(twi); context->state = STATE_RX_ERROR; if ( context->current_sig_callback != NULL ) { context->current_sig_callback(HAL_TWI_SIGNAL_TYPE_RX_ERROR); } done = true; } } } while ( !done ); } #ifdef SYS_CFG_USE_TWI0 void hal_serial_twi0_isr_handler(void) { hal_twi_isr_handler(NRF_TWI0, &hal_twi0); } #endif #ifdef SYS_CFG_USE_TWI1 void hal_serial_twi1_isr_handler(void) { hal_twi_isr_handler(NRF_TWI1, &hal_twi1); } #endif <file_sep>/components/ble/ble_services/experimental_ble_pdlp/ble_pdlp.h /* Copyright (c) 2016 Nordic Semiconductor. All Rights Reserved. * * The information contained herein is property of Nordic Semiconductor ASA. * Terms and conditions of usage are described in detail in NORDIC * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. * * Licensees are granted free, non-transferable use of the information. NO * WARRANTY of ANY KIND is provided. This heading must NOT be removed from * the file. * */ /** @file * * @defgroup ble_sdk_srv_pdlp PDLP Service Server * @{ * @ingroup ble_sdk_srv * * @brief PDLP Service Server module. * * @details This module implements a custom PDLP Service. * During initialization, the module adds the PDLP Service and Characteristics * to the BLE stack database. * * @note The application must propagate BLE stack events to the PDLP Service * module by calling ble_pdls_on_ble_evt() from the @ref softdevice_handler callback. */ #ifndef BLE_PDLP_H__ #define BLE_PDLP_H__ #include <stdint.h> #include <stdbool.h> #include "ble.h" #include "ble_srv_common.h" #include "ble_pdlp_common.h" // // PeripheralDeviceLinkProfile (PDLP) // #define PDLS_UUID_BASE {0xCD, 0xA6, 0x13, 0x5B, 0x83, 0x50, 0x8D, 0x80, \ 0x44, 0x40, 0xD3, 0x50, 0x00, 0x00, 0xB3, 0xB3} #define PDLS_UUID_SERVICE 0x6901 /**< Peripheral Device Link Service */ #define PDLS_UUID_WRITE_CHAR 0x9101 /**< Write Message characteristic */ #define PDLS_UUID_IND_CHAR 0x9102 /**< Indicate Message characteristic */ #define PDLS_HEADER_SOURCE_Pos 7 #define PDLS_HEADER_CANCEL_Pos 6 #define PDLS_HEADER_SEQNUM_Pos 1 #define PDLS_HEADER_EXECUTE_Pos 0 /**@brief PDLS service type. */ typedef enum { PDLS_SERVICE_PIS, /**< 0x00 Peripheral Device Property Information Service. */ PDLS_SERVICE_NS, /**< 0x01 Peripheral Device Notification Service. */ PDLS_SERVICE_OS, /**< 0x02 Peripheral Device Operation Service. */ PDLS_SERVICE_SIS, /**< 0x03 Peripheral Device Sensor Information Service. */ PDLS_SERVICE_SOS, /**< 0x04 Peripheral Device Setting Operation Service. */ PDLS_SERVICE_MAX } ble_pdls_service_type_t; /**@brief PDLP Service structure. This structure contains various status information for the service. */ typedef struct ble_pdls_s { uint16_t service_handle; /**< Handle of PDLP Service (as provided by the BLE stack). */ ble_gatts_char_handles_t write_char_handles; /**< Handles related to the Write Message Characteristic. */ ble_gatts_char_handles_t ind_char_handles; /**< Handles related to the Inidicate Message Characteristic. */ uint8_t uuid_type; /**< UUID type for the PDLP Service. */ uint16_t conn_handle; /**< Handle of the current connection (as provided by the BLE stack). BLE_CONN_HANDLE_INVALID if not in a connection. */ } ble_pdls_t; // // PeripheralDevicePropertyInformation (PDPIS) // #define PDPIS_SERVICE_BITMASK_NONE 0x00 #define PDPIS_SERVICE_BITMASK_PIS 0x01 #define PDPIS_SERVICE_BITMASK_NS 0x02 #define PDPIS_SERVICE_BITMASK_OS 0x04 #define PDPIS_SERVICE_BITMASK_SIS 0x08 #define PDPIS_SERVICE_BITMASK_SOS 0x10 #define PDPIS_CAPABILITY_BITMASK_NONE 0x01 #define PDPIS_CAPABILITY_BITMASK_GYROSCOPE 0x02 #define PDPIS_CAPABILITY_BITMASK_ACCELERATOR 0x04 #define PDPIS_CAPABILITY_BITMASK_ORIENTATION 0x08 #define PDPIS_CAPABILITY_BITMASK_BATTERY 0x10 #define PDPIS_CAPABILITY_BITMASK_TEMPERATURE 0x20 #define PDPIS_CAPABILITY_BITMASK_HUMIDITY 0x40 #define PDPIS_CAPABILITY_BITMASK_RESERVED 0x80 #define PDPIS_GET_DEVICE_INFORMATION 0x0000 #define PDPIS_GET_DEVICE_INFORMATION_RESP 0x0001 /**@brief PDPIS parameters. */ typedef enum { PDPIS_PARAM_RESULTCODE, PDPIS_PARAM_CANCEL, PDPIS_PARAM_SERVICELIST, PDPIS_PARAM_DEVICEID, PDPIS_PARAM_DEVICEUID, PDPIS_PARAM_DEVICECAPABILITY, PDPIS_PARAM_ORIGINAL_INFO, PDPIS_PARAM_EX_SENSROR, PDPIS_PARAM_MAX } ble_pdpis_params_type_t; // // PeripheralDeviceOperationService (PDOS) // #define PDOS_NOTIFY_PD_OPERATION 0x0000 /**@brief PDOS parameters. */ typedef enum { PDOS_PARAM_RESULTCODE, PDOS_PARAM_CANCEL, PDOS_PARAM_BUTTONID, PDOS_PARAM_MAX } ble_pdos_params_type_t; /**@brief PDOS Button ID */ typedef enum { PDOS_BUTTON_ID_POWER, PDOS_BUTTON_ID_RETURN, PDOS_BUTTON_ID_ENTER, PDOS_BUTTON_ID_HOME, PDOS_BUTTON_ID_MENU, PDOS_BUTTON_ID_VOLUMEUP, PDOS_BUTTON_ID_VOLUMEDOWN, PDOS_BUTTON_ID_PLAY, PDOS_BUTTON_ID_PAUSE, PDOS_BUTTON_ID_STOP, PDOS_BUTTON_ID_FASTFORWARD, PDOS_BUTTON_ID_REWIND, PDOS_BUTTON_ID_SHUTTER, PDOS_BUTTON_ID_UP, PDOS_BUTTON_ID_DOWN, PDOS_BUTTON_ID_LEFT, PDOS_BUTTON_ID_RIGHT, PDOS_NOTIFY_CATEGORY_MAX } ble_pdos_button_id_t; // // PeripheralDeviceSensorInformatioService (PDSIS) // #define PDSIS_GET_SENSOR_INFO 0x0000 #define PDSIS_GET_SENSOR_INFO_RESP 0x0001 #define PDSIS_SET_NOTIFY_SENSOR_INFO 0x0002 #define PDSIS_SET_NOTIFY_SENSOR_INFO_RESP 0x0003 #define PDSIS_NOTIFY_PD_SENSOR_INFO 0x0004 #define PDSIS_SENSOR_BITMASK_NONE 0x00 #define PDSIS_SENSOR_BITMASK_GYROSCOPE 0x01 #define PDSIS_SENSOR_BITMASK_ACCELEROMETER 0x02 #define PDSIS_SENSOR_BITMASK_ORIENTATION 0x04 #define PDSIS_SENSOR_BITMASK_BATTERY 0x08 #define PDSIS_SENSOR_BITMASK_TEMPERATURE 0x10 #define PDSIS_SENSOR_BITMASK_HUMIDITY 0x20 /**@brief PDSIS parameters. */ typedef enum { PDSIS_PARAM_RESULTCODE, PDSIS_PARAM_CANCEL, PDSIS_PARAM_SENSORTYPE, PDSIS_PARAM_STATUS, PDSIS_PARAM_X_VALUE, PDSIS_PARAM_Y_VALUE, PDSIS_PARAM_Z_VALUE, PDSIS_PARAM_X_THRESHOLD, PDSIS_PARAM_Y_THRESHOLD, PDSIS_PARAM_Z_THRESHOLD, PDSIS_PARAM_ORIGINALDATA, PDSIS_PARAM_MAX } ble_pdsis_params_type_t; /**@brief PDSIS Sensor Type */ typedef enum { PDSIS_SENSOR_TYPE_GYROSCOPE, PDSIS_SENSOR_TYPE_ACCELEROMETER, PDSIS_SENSOR_TYPE_ORIENTATION, PDSIS_SENSOR_TYPE_BATTERY, PDSIS_SENSOR_TYPE_TEMPERATURE, PDSIS_SENSOR_TYPE_HUMIDITY, PDSIS_SETTING_MAX } ble_pdsis_sensor_type_t; /**@brief PDSIS Status */ typedef enum { PDSIS_STATUS_OFF, PDSIS_STATUS_ON, PDSIS_STATUS_MAX } ble_pdsis_status_t; /**@brief PDSIS Notify value or threshold*/ typedef union { struct value_s { uint32_t x_value; uint32_t y_value; uint32_t z_value; } value; struct { uint32_t x_threshold; uint32_t y_threshold; uint32_t z_threshold; } threshold; int8_t s8_originaldata[12]; uint8_t u8_originaldata[12]; int16_t s16_originaldata[6]; uint16_t u16_originaldata[6]; int32_t s32_originaldata[3]; uint32_t u32_originaldata[3]; } ble_pdsis_notify_value_t; /**@brief PDSIS events */ typedef enum { PDSIS_EVT_SET_NOTIFY_INFO, PDSIS_EVT_GET_SENSOR_INFO } ble_pdsis_event_t; /**@brief PDSIS Event data structure */ typedef struct { ble_pdsis_event_t event; ble_pdsis_sensor_type_t type; // below are either data to or from app ble_pdsis_status_t status; ble_pdsis_notify_value_t data; } ble_pdsis_event_data_t; typedef ble_pdls_result_code_t (*ble_pdsis_event_handler_t) (ble_pdls_t * p_pdls, ble_pdsis_event_data_t *p_pdsis_event); // // PeripheralDeviceNotificationService (PDNS) // #define PDNS_CONFIRM_NOTIFY_CATEGORY 0x0000 #define PDNS_CONFIRM_NOTIFY_CATEGORY_RESP 0x0001 #define PDNS_NOTIFY_INFORMATION 0x0002 #define PDNS_GET_PD_NOTIFY_DETAIL_DATA 0x0003 #define PDNS_GET_PD_NOTIFY_DETAIL_DATA_RESP 0x0004 #define PDNS_NOTIFY_PD_GENERAL_INFORMATION 0x0005 #define PDNS_START_PD_APPLICATION 0x0006 #define PDNS_START_PD_APPLICATION_RESP 0x0007 #define PDNS_NOTIFY_CATEGORY_NOTNOTIFY 0x0001 #define PDNS_NOTIFY_CATEGORY_ALL 0x0002 #define PDNS_NOTIFY_CATEGORY_PHONEINCOMINGCALL 0x0004 #define PDNS_NOTIFY_CATEGORY_PHONEINCALL 0x0008 #define PDNS_NOTIFY_CATEGORY_PHONEIDLE 0x0010 #define PDNS_NOTIFY_CATEGORY_MAIL 0x0020 #define PDNS_NOTIFY_CATEGORY_SCHEDULE 0x0040 #define PDNS_NOTIFY_CATEGORY_GENERAL 0x0080 #define PDNS_NOTIFY_CATEGORY_ETC 0x0100 #define PDNS_PARAMID_PHONEINCOMINGCALL_NOTIFYID 0x0001 #define PDNS_PARAMID_PHONEINCOMINGCALL_NOTIFYCATEGORY 0x0002 #define PDNS_PARAMID_PHONEINCALL_NOTIFYID 0x0001 #define PDNS_PARAMID_PHONEINCALL_NOTIFYCATEGORY 0x0002 #define PDNS_PARAMID_PHONEIDLE_NOTIFYID 0x0001 #define PDNS_PARAMID_PHONEIDLE_NOTIFYCATEGORY 0x0002 #define PDNS_PARAMID_MAIL_APPNAME 0x0001 #define PDNS_PARAMID_MAIL_APPNAMELOCAL 0x0002 #define PDNS_PARAMID_MAIL_PACKAGE 0x0004 #define PDNS_PARAMID_MAIL_TITLE 0x0008 #define PDNS_PARAMID_MAIL_TEXT 0x0010 #define PDNS_PARAMID_MAIL_SENDER 0x0020 #define PDNS_PARAMID_MAIL_SENDERADDRESS 0x0040 #define PDNS_PARAMID_MAIL_RECEIVEDATE 0x0080 #define PDNS_PARAMID_MAIL_NOTIFYID 0x0100 #define PDNS_PARAMID_MAIL_NOTIFYCATEGORY 0x0200 #define PDNS_PARAMID_SCHEDULE_APPNAME 0x0001 #define PDNS_PARAMID_SCHEDULE_APPNAMELOCAL 0x0002 #define PDNS_PARAMID_SCHEDULE_PACKAGE 0x0004 #define PDNS_PARAMID_SCHEDULE_TITLE 0x0008 #define PDNS_PARAMID_SCHEDULE_STARTDATE 0x0010 #define PDNS_PARAMID_SCHEDULE_ENDDATE 0x0020 #define PDNS_PARAMID_SCHEDULE_AREA 0x0040 #define PDNS_PARAMID_SCHEDULE_PERSON 0x0080 #define PDNS_PARAMID_SCHEDULE_TEXT 0x0100 #define PDNS_PARAMID_SCHEDULE_CONTENTS1 0x0200 #define PDNS_PARAMID_SCHEDULE_CONTENTS2 0x0400 #define PDNS_PARAMID_SCHEDULE_CONTENTS3 0x0800 #define PDNS_PARAMID_SCHEDULE_NOTIFYID 0x1000 #define PDNS_PARAMID_SCHEDULE_NOTIFYCATEGORY 0x2000 #define PDNS_PARAMID_GENERAL_APPNAME 0x0001 #define PDNS_PARAMID_GENERAL_APPNAMELOCAL 0x0002 #define PDNS_PARAMID_GENERAL_PACKAGE 0x0004 #define PDNS_PARAMID_GENERAL_TITLE 0x0008 #define PDNS_PARAMID_GENERAL_TEXT 0x0010 #define PDNS_PARAMID_GENERAL_NOTIFYID 0x0020 #define PDNS_PARAMID_GENERAL_NOTIFYCATEGORY 0x0040 #define PDNS_PARAMID_ETC_APPNAME 0x0001 #define PDNS_PARAMID_ETC_APPNAMELOCAL 0x0002 #define PDNS_PARAMID_ETC_PACKAGE 0x0004 #define PDNS_PARAMID_ETC_CONTENTS1 0x0008 #define PDNS_PARAMID_ETC_CONTENTS2 0x0010 #define PDNS_PARAMID_ETC_CONTENTS3 0x0020 #define PDNS_PARAMID_ETC_CONTENTS4 0x0040 #define PDNS_PARAMID_ETC_CONTENTS5 0x0080 #define PDNS_PARAMID_ETC_CONTENTS6 0x0100 #define PDNS_PARAMID_ETC_CONTENTS7 0x0200 #define PDNS_PARAMID_ETC_MIMETYPEFORMEDIA 0x0400 #define PDNS_PARAMID_ETC_MEDIA 0x0800 #define PDNS_PARAMID_ETC_MIMETYPEFORIMAGE 0x1000 #define PDNS_PARAMID_ETC_IMAGE 0x2000 #define PDNS_PARAMID_ETC_NOTIFYID 0x4000 #define PDNS_PARAMID_ETC_NOTIFYCATEGORY 0x8000 /**@brief PDNS parameters. */ typedef enum { PDNS_PARAM_RESULTCODE, PDNS_PARAM_CANCEL, PDNS_PARAM_GETSTATUS, PDNS_PARAM_NOTIFYCATEGORY, PDNS_PARAM_NOTIFYCATEGORYID, PDNS_PARAM_GETPARAMETERID, PDNS_PARAM_GETPARAMETERLENGTH, PDNS_PARAM_PARAMETERIDLIST, PDNS_PARAM_UNIQUEID, PDNS_PARAM_NOTIFYID, PDNS_PARAM_NOTIFICATIONOPERATION, PDNS_PARAM_TITLE, PDNS_PARAM_TEXT, PDNS_PARAM_APPNAME, PDNS_PARAM_APPNAMELOCAL, PDNS_PARAM_NOTIFYAPP, PDNS_PARAM_RUMBLINGSETTING, PDNS_PARAM_VABRATIONPATTERN, PDNS_PARAM_LEDPATTERN, PDNS_PARAM_SENDER, PDNS_PARAM_SENDERADDRESS, PDNS_PARAM_RECEIVEDATE, PDNS_PARAM_STARTDATE, PDNS_PARAM_ENDDATE, PDNS_PARAM_AREA, PDNS_PARAM_PERSON, PDNS_PARAM_MIMETYPEFORIMAGE, PDNS_PARAM_MIMETYPEFORMEDIA, PDNS_PARAM_IMAGE, PDNS_PARAM_CONTENTS1, PDNS_PARAM_CONTENTS2, PDNS_PARAM_CONTENTS3, PDNS_PARAM_CONTENTS4, PDNS_PARAM_CONTENTS5, PDNS_PARAM_CONTENTS6, PDNS_PARAM_CONTENTS7, PDNS_PARAM_CONTENTS8, PDNS_PARAM_CONTENTS9, PDNS_PARAM_CONTENTS10, PDNS_PARAM_MEDIA, PDNS_PARAM_PACKAGE, PDNS_PARAM_CLASS, PDNS_PARAM_SHARINGINFORMATION, PDNS_PARAM_BEEPPATTERN, PDNS_PARAM_INVALID } ble_pdns_params_type_t; /**@brief PDNS STATUS code */ typedef enum { PDNS_STATUS_OK, PDNS_STATUS_PARTIAL_OK, PDNS_STATUS_CANCEL, PDNS_STATUS_ERROR_FAILED, PDNS_STATUS_ERROR_UNKOWN, PDNS_STATUS_ERROR_NO_DATA, PDNS_STATUS_ERROR_NOT_SUPPORTED, PDNS_STATUS_MAX } ble_pdns_status_t; /**@brief PDNS Rumbling Setting code */ typedef enum { PDNS_RUMBLING_SETTING_LED, PDNS_RUMBLING_SETTING_VIBRATION, PDNS_RUMBLING_SETTING_BEEP, PDNS_RUMBLING_SETTING_MAX } ble_pdns_rumbling_setting_t; /**@brief PDNS notify information */ typedef struct { uint16_t notifycategory; uint16_t uniqueid; uint16_t parameteridlist; ble_pdns_rumbling_setting_t rumblingsetting; uint8_t vibratiobpattern[4]; //TBD uint8_t ledpattern[5]; //TBD uint8_t beeppattern[4]; //TBD } ble_pdns_notify_info_t; /**@brief PDNS get notify detail data response */ typedef struct { ble_pdls_result_code_t result; uint16_t uniqueid; pdlp_opaque_t data; } ble_pdns_notify_detail_resp_t; /**@brief PDNS start app response */ typedef struct { ble_pdls_result_code_t result; } ble_pdns_start_app_resp_t; /**@brief PDSIS events */ typedef enum { PDNS_EVT_NOTIFY_INFO, PDNS_EVT_GET_PD_NOTIFY_DETAIL_DATA_RESP, PDNS_EVT_START_PD_APP_RESP } ble_pdns_event_t; /**@brief PDNS event data structure*/ typedef struct { ble_pdns_event_t event; union { ble_pdns_notify_info_t notifyinfo; ble_pdns_notify_detail_resp_t notifydetail; ble_pdns_start_app_resp_t startappresult; } data; } ble_pdns_event_data_t; typedef ble_pdls_result_code_t (*ble_pdns_event_handler_t) (ble_pdls_t * p_pdls, ble_pdns_event_data_t *p_pdns_event); // // PeripheralDeviceSettingOperationService (PDSOS) // #define PDSOS_GET_APP_VERSION 0x0000 #define PDSOS_GET_APP_VERSION_RESP 0x0001 #define PDSOS_CONFIRM_INSTALL_APP 0x0002 #define PDSOS_CONFIRM_INSTALL_APP_RESP 0x0003 #define PDSOS_GET_SETTING_INFORMATION 0x0004 #define PDSOS_GET_SETTING_INFORMATION_RESP 0x0005 #define PDSOS_GET_SETTING_NAME 0x0006 #define PDSOS_GET_SETTING_NAME_RESP 0x0007 #define PDSOS_SELECT_SETTING_INFORMATION 0x0008 #define PDSOS_SELECT_SETTING_INFORMATION_RESP 0x0009 #define PDSOS_SETTING_VALUE_ID_LED 0x00 #define PDSOS_SETTING_VALUE_ID_VIBRATOR 0x01 #define PDSOS_SETTING_REQ_ID_SETTING 0x00 #define PDSOS_SETTING_REQ_ID_START_DEMO 0x01 #define PDSOS_SETTING_REQ_ID_STOP_DEMO 0x02 /**@brief PDSOS parameters. */ typedef enum { PDSOS_PARAM_RESULTCODE, PDSOS_PARAM_CANCEL, PDSOS_PARAM_SETTINGNAMETYPE, PDSOS_PARAM_APPNAME, PDSOS_PARAM_FILEVER, PDSOS_PARAM_FILESIZE, PDSOS_PARAM_INSTALLCONFIRMSTATUS, PDSOS_PARAM_SETTINGINFORMATIONREQUEST, PDSOS_PARAM_SETTINGINFORMATIONDATA, PDSOS_PARAM_SETTINGNAMEDATA, PDSOS_PARAM_MAX } ble_pdsos_params_type_t; /**@brief PDSOS Setting Name Type */ typedef enum { PDSOS_SETTING_LEDCOLORNAME, PDSOS_SETTING_LEDPATTERNNAME, PDSOS_SETTING_VIBRATIONPATTERNNAME, PDSOS_SETTING_BEEPPATTERNNAME, PDSOS_SETTING_MAX } ble_pdsos_setting_name_type_t; /**@brief PDSOS Install Confirm Status */ typedef enum { PDSOS_INSTALL_CONFIRM_STATUS_OK, PDSOS_INSTALL_CONFIRM_STATUS_CANCEL, PDSOS_INSTALL_CONFIRM_STATUS_ERROR_FAILED, PDSOS_INSTALL_CONFIRM_STATUS_ERROR_UNKOWN, PDSOS_INSTALL_CONFIRM_STATUS_ERROR_NO_DATA, PDSOS_INSTALL_CONFIRM_STATUS_ERROR_NOT_SUPPORTED, PDSOS_INSTALL_CONFIRM_STATUS_ERROR_NO_SPACE, PDSOS_INSTALL_CONFIRM_STATUS_ERROR_ALREADY_INSTTALLED, PDSOS_INSTALL_CONFIRM_STATUS_ERROR_VERSION_OLD, PDSOS_INSTALL_CONFIRM_STATUS_MAX } ble_pdsos_status_t; /**@brief PDSOS setting notification time */ typedef enum { PDSOS_NOTIFY_TIME_OFF = 0x00, PDSOS_NOTIFY_TIME_5SEC = 0x05, PDSOS_NOTIFY_TIME_10SEC = 0x0A, PDSOS_NOTIFY_TIME_30SEC = 0x1E, PDSOS_NOTIFY_TIME_1MIN = 0x3C, PDSOS_NOTIFY_TIME_3MIN = 0xB4, } ble_pdsos_setting_notify_time_t; /**@brief PDSOS LED setting info. */ typedef struct { uint8_t color_num; uint8_t color_selected; // 0x01~ uint8_t pattern_num; uint8_t pattern_selected; // 0x01~ } ble_pdsos_led_setting_info; /**@brief PDSOS Vibrator setting info. */ typedef struct { uint8_t pattern_num; uint8_t pattern_selected; } ble_pdsos_vibrator_setting_info; /**@brief PDSOS Beep setting info. */ typedef struct { uint8_t pattern_num; uint8_t pattern_selected; } ble_pdsos_beep_setting_info; /**@brief PDSOS setting info. */ typedef struct { uint8_t setting_id; //0: LED; 1: Vibration; 2: Beep uint8_t notify_time; //ble_pdsos_setting_notify_time_t union { ble_pdsos_led_setting_info led_setting; ble_pdsos_vibrator_setting_info vibrator_setting; ble_pdsos_beep_setting_info beep_setting; } setting; } ble_pdsos_setting_info; /**@brief PDSOS setting name*/ typedef struct { pdlp_opaque_t setting; } ble_pdsos_setting_name; /**@brief PDSOS events */ typedef enum { PDSOS_EVT_GET_SETTING_INFO, PDSOS_EVT_GET_SETTING_NAME, PDSOS_EVT_SELECT_SETTING_INFO } ble_pdsos_event_t; /**@brief PDSOS Event data structure */ typedef struct { ble_pdsos_event_t event; union { ble_pdsos_setting_name_type_t setting_name_type; uint8_t setting_info_request; ble_pdsos_setting_info setting_info; } data; } ble_pdsos_event_data_t; typedef ble_pdls_result_code_t (*ble_pdsos_event_handler_t) (ble_pdls_t * p_pdls, ble_pdsos_event_data_t *p_pdsos_event); /** @brief PDLP Service init structure. This structure contains all options and data needed for * initialization of the service.*/ typedef struct { //PDPIS uint8_t servicelist; /**< Service list. */ uint16_t deviceid; /**< Device ID. */ uint32_t deviceuid; /**< Device UID. */ uint8_t devicecapability; /**< Device Capability. */ uint8_t *originalinfo; /**< Device original Information. */ uint8_t exsensortype; /**< Extended Sensor Type info. */ //PDNS uint16_t notifycategory; /**< Notify category */ ble_pdns_event_handler_t pdns_event_handler; //PDSIS uint8_t sensortypes; /**< Sensor types */ ble_pdsis_event_handler_t pdsis_event_handler; //PDSOS ble_pdsos_event_handler_t pdsos_event_handler; } ble_pdls_init_t; /**@brief Function for initializing the PDLP Service. * * @param[out] p_pdls PDLP Service structure. This structure must be supplied by * the application. It is initialized by this function and will later * be used to identify this particular service instance. * @param[in] p_pdls_init Information needed to initialize the service. * * @retval NRF_SUCCESS If the service was initialized successfully. Otherwise, an error code is returned. */ uint32_t ble_pdls_init(ble_pdls_t * p_pdls, const ble_pdls_init_t * p_pdls_init); /**@brief Function for handling the application's BLE stack events. * * @details This function handles all events from the BLE stack that are of interest to the PDLP Service. * * @param[in] p_pdlp PDLP Service structure. * @param[in] p_ble_evt Event received from the BLE stack. */ void ble_pdls_on_ble_evt(ble_pdls_t * p_pdls, ble_evt_t * p_ble_evt); /**@brief Function for PDOS device operation notification * * @param[in] p_pdls PDLP Service structure. This structure must be supplied by * the application. * @param[in] button_id Button ID to be notified to PDLP Client. * * @retval NRF_SUCCESS If the service was handled successfully. Otherwise, an error code is returned. */ uint32_t ble_pdls_pdos_notify(ble_pdls_t * p_pdls, ble_pdos_button_id_t button_id); /**@brief Function for PDSIS sensor information notification * * @param[in] p_pdls PDLP Service structure. This data must be supplied by the application. * @param[in] sensor_type Type of sensor * @param[in] p_notify_value Sensor data to be notified to PDLP Client. * * @retval NRF_SUCCESS If the service was handled successfully. Otherwise, an error code is returned. */ uint32_t ble_pdls_pdsis_notify(ble_pdls_t * p_pdls, ble_pdsis_sensor_type_t sensor_type, ble_pdsis_notify_value_t *p_notify_value); /**@brief Function for PDNS, get the notification details from PDLP Client * * @param[in] p_pdls PDLP Service structure. This data must be supplied by the application. * @param[in] unique_id Unique ID for indentification * @param[in] param_id Parameter ID to get details for * @param[in] param_len Length of parameter details, if known * * @retval NRF_SUCCESS If the service was initialized successfully. Otherwise, an error code is returned. */ uint32_t ble_pdls_pdns_get_pd_notify_detail_data(ble_pdls_t * p_pdls, uint16_t unique_id, uint8_t param_id, uint32_t param_len); /**@brief Function for PDNS, start an application on PDLP Client * * @param[in] p_pdls PDLP Service structure. This data must be supplied by the application. * @param[in] p_package Package name of notification source application * @param[in] p_notifyapp Package name of notification destination application * @param[in] p_class Name of class * @param[in] p_sharing_info Sharing info (optional) * * @retval NRF_SUCCESS If the service was handled successfully. Otherwise, an error code is returned. */ uint32_t ble_pdls_pdns_start_pd_app(ble_pdls_t *p_pdls, pdlp_opaque_t *p_package, pdlp_opaque_t *p_notifyapp, pdlp_opaque_t *p_class, pdlp_opaque_t *p_sharing_info); /**@brief Function for PDSOS, response of get seting info request from PDLP Client * * @param[in] p_pdls PDLP Service structure. This data must be supplied by the application. * @param[in] result Handling result on local device * @param[in] p_setting_info Setting information * * @retval NRF_SUCCESS If the service was initialized successfully. Otherwise, an error code is returned. */ uint32_t ble_pdls_pdsos_get_setting_info_resp(ble_pdls_t * p_pdls, ble_pdls_result_code_t result, ble_pdsos_setting_info* p_setting_info); /**@brief Function for PDSOS, response of get seting name request from PDLP Client * * @param[in] p_pdls PDLP Service structure. This data must be supplied by the application. * @param[in] result Handling result on local device * @param[in] p_setting_name Setting name(s) * * @retval NRF_SUCCESS If the service was handled successfully. Otherwise, an error code is returned. */ uint32_t ble_pdls_pdsos_get_setting_name_resp(ble_pdls_t * p_pdls, ble_pdls_result_code_t result, ble_pdsos_setting_name* p_setting_name); /**@brief Function for PDSOS, response of select seting info request from PDLP Client * * @param[in] p_pdls PDLP Service structure. This data must be supplied by the application. * @param[in] result Handling result on local device * * @retval NRF_SUCCESS If the service was handled successfully. Otherwise, an error code is returned. */ uint32_t ble_pdls_pdsos_select_setting_info_resp(ble_pdls_t * p_pdls, ble_pdls_result_code_t result); #endif // BLE_PDLP_H__ /** @} */ <file_sep>/examples/ble_peripheral/experimental_ble_app_linking_beacon_solar/src/hal_radio.c /* Copyright (c) Nordic Semiconductor ASA * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * 3. Neither the name of Nordic Semiconductor ASA nor the names of other * contributors to this software may be used to endorse or promote products * derived from this software without specific prior written permission. * * 4. This software must only be used in a processor manufactured by Nordic * Semiconductor ASA, or in a processor manufactured by a third party that * is used in combination with a processor manufactured by Nordic Semiconductor. * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "nrf.h" uint8_t access_address[4] = {0xD6, 0xBE, 0x89, 0x8E}; uint8_t seed[3] = {0x55, 0x55, 0x55}; /**@brief The maximum possible length in device discovery mode. */ #define DD_MAX_PAYLOAD_LENGTH (31 + 6) /**@brief The default SHORTS configuration. */ #define DEFAULT_RADIO_SHORTS \ ( \ (RADIO_SHORTS_READY_START_Enabled << RADIO_SHORTS_READY_START_Pos) | \ (RADIO_SHORTS_END_DISABLE_Enabled << RADIO_SHORTS_END_DISABLE_Pos) \ ) /**@brief The default CRC init polynominal. @note Written in little endian but stored in big endian, because the BLE spec. prints is in little endian but the HW stores it in big endian. */ #define CRC_POLYNOMIAL_INIT_SETTINGS ((0x5B << 0) | (0x06 << 8) | (0x00 << 16)) /**@brief This macro converts the given channel index to a freuency offset (i.e. offset from 2400 MHz). @param index - the channel index to be converted into frequency offset. @return The frequency offset for the given index. */ #define CHANNEL_IDX_TO_FREQ_OFFS(index) \ (((index) == 37)?\ (2)\ :\ (((index) == 38)?\ (26)\ :\ (((index) == 39)?\ (80)\ :\ ((/*((index) >= 0) &&*/ ((index) <= 10))?\ ((index)*2 + 4)\ :\ ((index)*2 + 6))))) void hal_radio_channel_index_set(uint8_t channel_index) { NRF_RADIO->FREQUENCY = CHANNEL_IDX_TO_FREQ_OFFS(channel_index); NRF_RADIO->DATAWHITEIV = channel_index; } void hal_radio_reset(void) { NVIC_DisableIRQ(RADIO_IRQn); NRF_RADIO->POWER = RADIO_POWER_POWER_Disabled << RADIO_POWER_POWER_Pos; NRF_RADIO->POWER = RADIO_POWER_POWER_Enabled << RADIO_POWER_POWER_Pos; NRF_RADIO->SHORTS = DEFAULT_RADIO_SHORTS; NRF_RADIO->PCNF0 = (((1UL) << RADIO_PCNF0_S0LEN_Pos) & RADIO_PCNF0_S0LEN_Msk) | (((2UL) << RADIO_PCNF0_S1LEN_Pos) & RADIO_PCNF0_S1LEN_Msk) | (((6UL) << RADIO_PCNF0_LFLEN_Pos) & RADIO_PCNF0_LFLEN_Msk); NRF_RADIO->PCNF1 = (((RADIO_PCNF1_ENDIAN_Little) << RADIO_PCNF1_ENDIAN_Pos) & RADIO_PCNF1_ENDIAN_Msk) | (((3UL) << RADIO_PCNF1_BALEN_Pos) & RADIO_PCNF1_BALEN_Msk) | (((0UL) << RADIO_PCNF1_STATLEN_Pos)& RADIO_PCNF1_STATLEN_Msk) | ((((uint32_t)DD_MAX_PAYLOAD_LENGTH) << RADIO_PCNF1_MAXLEN_Pos) & RADIO_PCNF1_MAXLEN_Msk) | ((RADIO_PCNF1_WHITEEN_Enabled << RADIO_PCNF1_WHITEEN_Pos) & RADIO_PCNF1_WHITEEN_Msk); /* The CRC polynomial is fixed, and is set here. */ /* The CRC initial value may change, and is set by */ /* higher level modules as needed. */ NRF_RADIO->CRCPOLY = (uint32_t)CRC_POLYNOMIAL_INIT_SETTINGS; NRF_RADIO->CRCCNF = (((RADIO_CRCCNF_SKIPADDR_Skip) << RADIO_CRCCNF_SKIPADDR_Pos) & RADIO_CRCCNF_SKIPADDR_Msk) | (((RADIO_CRCCNF_LEN_Three) << RADIO_CRCCNF_LEN_Pos) & RADIO_CRCCNF_LEN_Msk); NRF_RADIO->RXADDRESSES = ( (RADIO_RXADDRESSES_ADDR0_Enabled) << RADIO_RXADDRESSES_ADDR0_Pos); NRF_RADIO->MODE = ((RADIO_MODE_MODE_Ble_1Mbit) << RADIO_MODE_MODE_Pos) & RADIO_MODE_MODE_Msk; NRF_RADIO->TIFS = 150; NRF_RADIO->PREFIX0 = access_address[3]; NRF_RADIO->BASE0 = ( (((uint32_t)access_address[2]) << 24) | (((uint32_t)access_address[1]) << 16) | (((uint32_t)access_address[0]) << 8) ); NRF_RADIO->CRCINIT = ((uint32_t)seed[0]) | ((uint32_t)seed[1])<<8 | ((uint32_t)seed[2])<<16; NRF_RADIO->INTENSET = (RADIO_INTENSET_DISABLED_Enabled << RADIO_INTENSET_DISABLED_Pos); NVIC_ClearPendingIRQ(RADIO_IRQn); NVIC_EnableIRQ(RADIO_IRQn); } void hal_radio_send(uint8_t *p_data) { NRF_RADIO->PACKETPTR = (uint32_t)&(p_data[0]); NRF_RADIO->EVENTS_DISABLED = 0; NRF_RADIO->TASKS_TXEN = 1; }
92bee8b2c9cdb7d87c312afa94181f1a6cf53763
[ "AsciiDoc", "Markdown", "C" ]
19
AsciiDoc
NordicPlayground/nrf5-ble-docomo-linking
be8244267e9a1ce56e18537aed9ecc9cd49c9d31
494ead25e520cda49ec4cfcdfb46c9414afe22af
refs/heads/master
<file_sep># HMIN322_TP2Chiffrement TP2 : Chiffrement multimedia How to compile? Sous LINUX : g++ -o main Code_TP2_ChiffrementMultimedia_ChouenyibAli.cpp -O2 -L/usr/X11R6/lib -lm -lpthread -lX11 <file_sep>#include "CImg.h" #include <iostream> #include <cstdlib> #include <bitset> #include <vector> using namespace cimg_library; bool is_prime(int number); int pgcd (int a, int b); bool relativly_prime(int a, int b); std::vector<int> possible_exponent_of_e(int phi_n); CImg<int> rsa_algorithm(CImg<int> img, int n, int e); CImg<int> binarizeIMG(CImg<int> img); double entropie (CImg<int> img); int puissance(int x, int n); int power_mod(int x, int e, int n); int main(int argc, char const *argv[]) { CImg<> img_read; // CImg<> img_read2; if (argc != 4) { printf("ERROR : arguments not complete\n"); return 1; } img_read.load(argv[1]); int number = atoi(argv[2]); int number2 = atoi(argv[3]); if (is_prime(number)) std::cout << number << " est un nombre premier" << '\n'; else std::cout << number << " n'est pas un nombre premier" << '\n'; if (relativly_prime(number, number2)) std::cout << number2 << " & " << number << " sont premiers entre eux " << '\n'; else std::cout << number2 << " & " << number << " ne sont pas premiers entre eux " << '\n'; int phi_n = (number2 - 1) * (number2 - 1); int n = number2 * number; std::vector<int> v = possible_exponent_of_e(phi_n); std::cout << " phi(n) = " << phi_n << " et n = " << n <<'\n'; for (int i = 0; i < v.size(); ++i) { std::cout << v[i] << ", "; } std::cout << '\n'; // on prend e = 17 CImg<int> result = rsa_algorithm(img_read, n, 17); result.save_png("../img/rsa_result.png"); img_read.save_png("../img/original.png"); // std::cout << " puissance(3, 17, 253) : " << puissance(3, 17) % 253 << " et power_mod(3, 17, 253) : " << power_mod(3, 17, 253) << '\n'; double entrop = entropie (result); std::cout << " L'entropie de l'image chiffrée est de : " << entrop << '\n'; CImg<int> binarized = binarizeIMG(img_read); CImg<int> result_of_binarized = rsa_algorithm(binarized, n, 17); binarized.save_png("../img/binarized.png"); result_of_binarized.save_png("../img/result_of_binarized.png"); return 0; } bool is_prime(int number) { int half = number / 2; for (int i = 2; i < half; i++) { if (number % i == 0 && i != number) return false; } return true; } int pgcd(int a, int b) { int t; while(b != 0){ t = a; a = b; b = t%b; } return a; } bool relativly_prime(int a, int b) { return pgcd(a, b) == 1; } std::vector<int> possible_exponent_of_e(int phi_n) { std::vector<int> vect; for (int i = 1; i < phi_n; ++i) { if (pgcd(i, phi_n) == 1) vect.push_back(i); } return vect; } CImg<int> rsa_algorithm(CImg<int> img, int n, int e) { int width = img.width(); int height = img.height(); CImg<int> result(width, height, 1, 1, 0); for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { result(i, j) = power_mod(img(i, j), e, n); } } return result; } int puissance (int x, int n) { int temp; if( n == 0) return 1; temp = puissance(x, n/2); if (n%2 == 0) return temp*temp; else return x*temp*temp; } int power_mod(int x, int e, int n) { int val = (x * x) % n; for (int i = 3; i <= e; i++) { val = (val * x) % n; } return val; } CImg<int> binarizeIMG(CImg<int> img) { int width = img.width(); int height = img.height(); CImg<int> result(width, height, 1, 1, 0); for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { if (img(i, j) >= 128 ) result(i, j) = 172; } } return result; } double entropie (CImg<int> img) { float H = 0; std::vector<int> occurence(255, 0); int width = img.width(); int height = img.height(); for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { int pixel = (int)img(i, j); if (pixel > 255 ) pixel = 255; if (pixel < 0) pixel = 0; // std::cout << pixel << ","; occurence[pixel] ++; } } for (int i = 0; i < occurence.size(); ++i) { double P = (double)occurence[i] / 255.0; std::cout << P << ", "; double logarithm = (P == 0) ? 0.0 : log2(P); H += (P * logarithm); } return H * (-1); }
c8908bb2924d4500944de093c0b2616dba657724
[ "Markdown", "C++" ]
2
Markdown
CaMarchPa/HMIN322_TP2Chiffrement
e2dc0132e5678516375e54b2a1f37a939512b534
7f43ba4fa63e79e72d561b2926495e386dd49846
refs/heads/master
<file_sep>// // String+Extension.swift // TextInput // // Created by <NAME> on 23.10.2017. // Copyright © 2017 <NAME>. All rights reserved. // import Foundation extension String { func characterAt(_ index: Int) -> Character? { guard index < count else { return nil } return self[self.index(self.startIndex, offsetBy: index)] } func slice(from: String, toString: String) -> String? { return (range(of: from)?.upperBound).flatMap { substringFrom in (range(of: toString, range: substringFrom..<endIndex)?.lowerBound).map { substringTo in String(self[substringFrom..<substringTo]) } } } func sliceAfter(substring: String) -> String { guard self.contains(substring) else { return self } guard count > substring.count else { return "" } guard let lastSubstringCharacter = substring.last else { return "" } guard let substringIndex = firstIndex(of: lastSubstringCharacter) else { return "" } let indexAfterSubstringIndex = index(substringIndex, offsetBy: 1) return String(self[indexAfterSubstringIndex..<endIndex]) } func sliceBefore(substring: String) -> String { guard self.contains(substring) else { return self } guard count > substring.count else { return "" } guard let firstSubstringCharacter = substring.first else { return self } guard let substringStartIndex = lastIndex(of: firstSubstringCharacter) else { return self } return String(self[startIndex..<substringStartIndex]) } func slice(from: String, to: String) -> String { return sliceAfter(substring: from).sliceBefore(substring: to) } func removePrefix(_ prefix: String) -> String { guard !prefix.isEmpty else { return self } return sliceAfter(substring: prefix) } func removeSuffix(_ suffix: String) -> String { guard !suffix.isEmpty else { return self } return sliceBefore(substring: suffix) } func leftSlice(limit: Int) -> String { guard limit < count else { return self } let rangeBegin = startIndex let rangeEnd = index(startIndex, offsetBy: limit) return String(self[rangeBegin..<rangeEnd]) } func slice(from: Int, length: Int) -> String? { guard from < count, from + length < count else { return nil } let fromIndex = index(startIndex, offsetBy: from) let toIndex = index(fromIndex, offsetBy: length) return String(self[fromIndex..<toIndex]) } func replacingCharacters(in range: NSRange, with replacement: String) -> String { guard range.location <= self.count else { return self } let maxLength = self.count var limitedRange = NSRange(location: range.location, length: range.length) if range.location + range.length > maxLength { limitedRange.length = self.count - range.location } guard let swiftRange = Range(limitedRange, in: self) else { return self } return replacingCharacters(in: swiftRange, with: replacement) } } <file_sep>// // DefaultTextInputFormatterDeleteTests.swift // AnyFormatKitTests // // Created by <NAME> on 09.06.2019. // Copyright © 2019 <NAME>. All rights reserved. // import XCTest @testable import AnyFormatKit class DefaultTextInputFormatterDeleteTests: XCTestCase { private let formatter = DefaultTextInputFormatter(textPattern: "## ## ##") func test12_34to12_3() { let actualResult = formatter.formatInput( currentText: "12 34", range: NSRange(location: 4, length: 1), replacementString: "") let expectedResult = FormattedTextValue(formattedText: "12 3", caretBeginOffset: 4) XCTAssert(actualResult == expectedResult, "\n\(actualResult) must be equal to\n\(expectedResult)") } func test12_3to12() { let actualResult = formatter.formatInput( currentText: "12 3", range: NSRange(location: 3, length: 1), replacementString: "") let expectedResult = FormattedTextValue(formattedText: "12", caretBeginOffset: 2) XCTAssert(actualResult == expectedResult, "\n\(actualResult) must be equal to\n\(expectedResult)") } func test12to1() { let actualResult = formatter.formatInput( currentText: "12", range: NSRange(location: 1, length: 1), replacementString: "") let expectedResult = FormattedTextValue(formattedText: "1", caretBeginOffset: 1) XCTAssert(actualResult == expectedResult, "\n\(actualResult) must be equal to\n\(expectedResult)") } func test1to_() { let actualResult = formatter.formatInput( currentText: "1", range: NSRange(location: 0, length: 1), replacementString: "") let expectedResult = FormattedTextValue(formattedText: "", caretBeginOffset: 0) XCTAssert(actualResult == expectedResult, "\n\(actualResult) must be equal to\n\(expectedResult)") } func test12_34to12_4() { let actualResult = formatter.formatInput( currentText: "12 34", range: NSRange(location: 3, length: 1), replacementString: "") let expectedResult = FormattedTextValue(formattedText: "12 4", caretBeginOffset: 2) XCTAssert(actualResult == expectedResult, "\n\(actualResult) must be equal to\n\(expectedResult)") } func test12_I34to12I_34() { let actualResult = formatter.formatInput( currentText: "12 34", range: NSRange(location: 2, length: 1), replacementString: "") let expectedResult = FormattedTextValue(formattedText: "12 34", caretBeginOffset: 2) XCTAssert(actualResult == expectedResult, "\n\(actualResult) must be equal to\n\(expectedResult)") } func test12_34to13_4() { let actualResult = formatter.formatInput( currentText: "12 34", range: NSRange(location: 1, length: 1), replacementString: "") let expectedResult = FormattedTextValue(formattedText: "13 4", caretBeginOffset: 1) XCTAssert(actualResult == expectedResult, "\n\(actualResult) must be equal to\n\(expectedResult)") } func test12_34to23_4() { let actualResult = formatter.formatInput( currentText: "12 34", range: NSRange(location: 0, length: 1), replacementString: "") let expectedResult = FormattedTextValue(formattedText: "23 4", caretBeginOffset: 0) XCTAssert(actualResult == expectedResult, "\n\(actualResult) must be equal to\n\(expectedResult)") } func test12_34to12() { let actualResult = formatter.formatInput( currentText: "12 34", range: NSRange(location: 3, length: 2), replacementString: "") let expectedResult = FormattedTextValue(formattedText: "12", caretBeginOffset: 2) XCTAssert(actualResult == expectedResult, "\n\(actualResult) must be equal to\n\(expectedResult)") } func test12_34to34() { let actualResult = formatter.formatInput( currentText: "12 34", range: NSRange(location: 0, length: 2), replacementString: "") let expectedResult = FormattedTextValue(formattedText: "34", caretBeginOffset: 0) XCTAssert(actualResult == expectedResult, "\n\(actualResult) must be equal to\n\(expectedResult)") } func test12_34to14() { let actualResult = formatter.formatInput( currentText: "12 34", range: NSRange(location: 1, length: 3), replacementString: "") let expectedResult = FormattedTextValue(formattedText: "14", caretBeginOffset: 1) XCTAssert(actualResult == expectedResult, "\n\(actualResult) must be equal to\n\(expectedResult)") } func test12_34to1() { let actualResult = formatter.formatInput( currentText: "12 34", range: NSRange(location: 1, length: 4), replacementString: "") let expectedResult = FormattedTextValue(formattedText: "1", caretBeginOffset: 1) XCTAssert(actualResult == expectedResult, "\n\(actualResult) must be equal to\n\(expectedResult)") } func test1I2_I34to13_4() { let actualResult = formatter.formatInput( currentText: "12 34", range: NSRange(location: 1, length: 2), replacementString: "") let expectedResult = FormattedTextValue(formattedText: "13 4", caretBeginOffset: 1) XCTAssert(actualResult == expectedResult, "\n\(actualResult) must be equal to\n\(expectedResult)") } func test12I_3I4to12_4() { let actualResult = formatter.formatInput( currentText: "12 34", range: NSRange(location: 2, length: 2), replacementString: "") let expectedResult = FormattedTextValue(formattedText: "12 4", caretBeginOffset: 2) XCTAssert(actualResult == expectedResult, "\n\(actualResult) must be equal to\n\(expectedResult)") } func test12_34to4() { let actualResult = formatter.formatInput( currentText: "12 34", range: NSRange(location: 0, length: 4), replacementString: "") let expectedResult = FormattedTextValue(formattedText: "4", caretBeginOffset: 0) XCTAssert(actualResult == expectedResult, "\n\(actualResult) must be equal to\n\(expectedResult)") } func test12_34to_() { let actualResult = formatter.formatInput( currentText: "12 34", range: NSRange(location: 0, length: 5), replacementString: "") let expectedResult = FormattedTextValue(formattedText: "", caretBeginOffset: 0) XCTAssert(actualResult == expectedResult, "\n\(actualResult) must be equal to\n\(expectedResult)") } } <file_sep>// // DefaultTextInputFormatterInputTests.swift // AnyFormatKitTests // // Created by <NAME> on 09.06.2019. // Copyright © 2019 <NAME>. All rights reserved. // import XCTest @testable import AnyFormatKit class DefaultTextInputFormatterInputTests: XCTestCase { let formatter = DefaultTextInputFormatter(textPattern: "## ## ##") override func setUp() { } override func tearDown() { } func test_to1() { let actualResult = formatter.formatInput( currentText: "", range: NSRange(location: 0, length: 0), replacementString: "1") let expectedResult = FormattedTextValue(formattedText: "1", caretBeginOffset: 1) XCTAssert(actualResult == expectedResult, "\n\(actualResult) must be equal to\n\(expectedResult)") } func test1to12() { let actualResult = formatter.formatInput( currentText: "1", range: NSRange(location: 1, length: 0), replacementString: "2") let expectedResult = FormattedTextValue(formattedText: "12", caretBeginOffset: 2) XCTAssert(actualResult == expectedResult, "\n\(actualResult) must be equal to\n\(expectedResult)") } func test12to12_3() { let actualResult = formatter.formatInput( currentText: "12", range: NSRange(location: 2, length: 0), replacementString: "3") let expectedResult = FormattedTextValue(formattedText: "12 3", caretBeginOffset: 4) XCTAssert(actualResult == expectedResult, "\n\(actualResult) must be equal to\n\(expectedResult)") } func test12_3to12_34() { let actualResult = formatter.formatInput( currentText: "12 3", range: NSRange(location: 4, length: 0), replacementString: "4") let expectedResult = FormattedTextValue(formattedText: "12 34", caretBeginOffset: 5) XCTAssert(actualResult == expectedResult, "\n\(actualResult) must be equal to\n\(expectedResult)") } func test12_3to01_23() { let actualResult = formatter.formatInput( currentText: "12 3", range: NSRange(location: 0, length: 0), replacementString: "0") let expectedResult = FormattedTextValue(formattedText: "01 23", caretBeginOffset: 1) XCTAssert(actualResult == expectedResult, "\n\(actualResult) must be equal to\n\(expectedResult)") } func test12_3to10_23() { let actualResult = formatter.formatInput( currentText: "12 3", range: NSRange(location: 1, length: 0), replacementString: "0") let expectedResult = FormattedTextValue(formattedText: "10 23", caretBeginOffset: 2) XCTAssert(actualResult == expectedResult, "\n\(actualResult) must be equal to\n\(expectedResult)") } func test12I_3to12_03() { let actualResult = formatter.formatInput( currentText: "12 3", range: NSRange(location: 2, length: 0), replacementString: "0") let expectedResult = FormattedTextValue(formattedText: "12 03", caretBeginOffset: 4) XCTAssert(actualResult == expectedResult, "\n\(actualResult) must be equal to\n\(expectedResult)") } func test12_I3to12_03() { let actualResult = formatter.formatInput( currentText: "12 3", range: NSRange(location: 3, length: 0), replacementString: "0") let expectedResult = FormattedTextValue(formattedText: "12 03", caretBeginOffset: 4) XCTAssert(actualResult == expectedResult, "\n\(actualResult) must be equal to\n\(expectedResult)") } }
cdbcfc9e1b001d31985ec7bd93fb826db66e8e4d
[ "Swift" ]
3
Swift
Eomkicheol/AnyFormatKit
1fb545731dbf3b49168908a3c2150a62529f7d13
136a029fc769b804f07ae285f0a61d6a3f9fd57e
refs/heads/master
<file_sep># Hello-world just get started 1- changing in github
70c1eca4b5729dc476202cb95a619a9afeb50ef2
[ "Markdown" ]
1
Markdown
sylumsid/Hello-world
53f389eb071dc8dd4865fb1cd76df1039cb58e76
17d577526b185fb69f4e88bc8e493d0f3d79134e
refs/heads/master
<file_sep>package model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name = "AGENTE") public class Agente { private int id; private long cnes; private long senha; private String email; private String nome; private long telefone; private long cpf; private Agente agente; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID") public int getId() { return id; } public void setId(int id) { this.id = id; } @Column(name = "CNES") public long getCnes() { return cnes; } public void setCnes(long cnes) { this.cnes = cnes; } @Column(name = "SENHA") public long getSenha() { return senha; } public void setSenha(long senha) { this.senha = senha; } @Column(name = "EMAIL") public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Column(name = "NOME") public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } @Column(name = "TELEFONE") public long getTelefone() { return telefone; } public void setTelefone(long telefone) { this.telefone = telefone; } @Column(name = "CPF") public long getCpf() { return cpf; } public void setCpf(long cpf) { this.cpf = cpf; } @ManyToOne @JoinColumn(name = "AGUENTE_FK") public Agente getAgente(){ return agente; } public void setPessoa(Agente agente){ this.agente = agente; } } <file_sep>package business; import java.util.List; import model.Foco; import persistense.FocoDao; public class FocoController { private static FocoDao dao = new FocoDao(); public static void setDao(FocoDao dao){ FocoController.dao = dao; } public static void saveFoco(Foco foco){ if(dao.containsFoco(foco.getId())) throw new RuntimeException("Ha uma pessoa com o mesmo nome registrada!"); else dao.insertFoco(foco); } public static void upDatePessoa(Foco foco){ dao.upDateFoco(foco); } public static void deleteFoco(Foco foco){ if(dao.containsFoco(foco.getId())) dao.removeFoco(foco); else throw new RuntimeException("Pessoa não registrada!"); } public static List<Foco> listPessoa(){ return dao.getAll(); } } <file_sep>package persistense; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public class EntityManagerFactoryHolder { public static final EntityManagerFactory factory = Persistence.createEntityManagerFactory("DENGUE"); }
a6884578bf89c96b8174047d182f4e1c704369fe
[ "Java" ]
3
Java
mapadengue/projectmapadadengue
e558b655f0a98b8b8881f506ebdfbe3a008fed24
9d49d88b63ce7b360186724832fd0ff653ef0dc4
refs/heads/master
<file_sep># stly-test files to test Statically
8f2e55ae7c82b3b68ad4bdb6873890f1e687f2e7
[ "Markdown" ]
1
Markdown
fransallen/stly-test
cbf4c92be207da93931c9d530e04ca47deeaa6b7
6123761b660fe268f9b9f698e86ee219a0237e3b
refs/heads/master
<file_sep>--- layout: post title: Bullying in Latin American schools subtitle: Bar chart based in PISA data, #SWDChallenge tags: SWDChallenge --- My bar chart for the February #SWDChallange addresses the topic of bullying in Latin American schools using PISA 2018 data. The idea was to make it interactive, so the user could explore two layers of information: the frequency of the reported bullying (at least once a month vs at least once a year), and the differences across countries. I tried to do the chart using D3 first, and I managed to create the static version, but when I tried to apply the "update" pattern with the filtered data it broke. So I moved on Tableau, to analyze the data, arrange the main ideas and try different layouts. After a few iterations, I got to this version: <div class="mcb-wrap-inner"><div class="column mcb-column mcb-item-ny8ost4q1 one column_column"><div class="column_attr clearfix" style=""><center><iframe src="https://public.tableau.com/views/BullyingLat/Bullying?:showVizHome=no&amp;:embed=true" width="800" height="940" frameborder="0"></iframe></center></div></div></div> <file_sep>--- layout: post title: Achieving effective learnings in North, Central & South American countries subtitle: The SDG Viz Project tags: [SDGVizProject] comments: true --- This is my first entry for [The SDG Viz Project](https://thesdgvizproject.com/) that is being carried out by [<NAME>](https://mobile.twitter.com/BMooreWasTaken), [<NAME>](https://mobile.twitter.com/VinodhDataArt) & [<NAME>](https://mobile.twitter.com/jaxx084). Because education is one of my research interests I thought the challenge for this month (SDG 4) was a good moment to participate. When thinking about what I could visualize I remembered that at the end of last year the OECD launched the results of the Pisa 2018 study, which included a [chapter regarding the target 4.1 of the SDG 4](https://www.oecd-ilibrary.org/education/pisa-2018-results-volume-i_5f07c754-en). Using the Pisa 2018 data and the Pisa for development 2017 data, that chapter includes information about the share of students (15-year-olds) that achieve at least minimum proficiency in reading and math, for 84 countries around the world. ![Viz](/assets/img/pisa-original.png){: .mx-auto.d-block :} I thought the SDG Viz Project could be a good excuse to use the information of those tables and design a visualization that could communicate a clearer message and allow a more effective overview of the data. My first design choice was to work with a subset of the data. To narrow the analysis I decided to focus on one continent, so I worked with countries from North, Central, and South America. The underlying question was "What are the educational challenges in that region regarding the achievement of the SDG target 4.1.1?" The SDG goal 4 is an enormous enterprise on its own. So in the introduction of the viz I wanted to make clear that I was focusing on a fraction of that goal -the target 4.1.1- which I illustrated coloring only one red dot (out of ten targets). ![Viz](/assets/img/target-in-context.png){: .mx-auto.d-block :} Now, to show how close or how far are countries for achieving that target, I designed a three-layered visualization: * The first layer presents a parallel bar chart for the results for reading and math, showing the high diversity of results that we see on the continent. Canada is relatively close to the target, while in countries like Dominican Republic, Paraguay, Guatemala or Honduras most of 15-year-old students are not reaching the minimum skills in those two subjects. ![Viz](/assets/img/screenshot-1.png){: .mx-auto.d-block :} * The second and third layer addresses the equity dimension of the results. The SDG goals challenge countries so that no one group of people can be left behind. The Pisa team addressed this dimension using a “parity index” that describes how equal or unequal are the learning results: if the index is closer to 0 then the learning results are favoring the boys (and that happens in some countries regarding math results) or the economically advantaged students (and that happens for both subjects in most countries, but we also see here diversity between countries). ![Viz](/assets/img/screenshot-2.png){: .mx-auto.d-block :} * Finally, I also accompany these three layers with a map with the main results, which does not add new information, but reinforces the main points and can help the reader localize the countries with data. One of the main points of the OECD report - and one that is also a key message of this viz - is that we still have some way to reach the SDG goal 4. This data challenges countries to rethink their policies, strategies, and collaborations in order to achieve the target by 2030. The interactive viz is [here](https://public.tableau.com/profile/maximiliano4575#!/vizhome/SDG4v2/SDG4?publish=yes): <div class="mcb-wrap-inner"><div class="column mcb-column mcb-item-ny8ost4q1 one column_column"><div class="column_attr clearfix" style=""><center><iframe src="https://public.tableau.com/views/SDG4v2/SDG4?:showVizHome=no&amp;:embed=true" width="1150" height="1400" frameborder="0"></iframe></center></div></div></div> <file_sep>--- layout: post title: Consumption of animal-free products subtitle: MakeoverMonday Week 23 tags: [MakeoverMonday] comments: true --- <iframe title="How often do British people with different food habits consume animal-free products?" aria-label="Split Bars" id="datawrapper-chart-qHw1A" src="https://datawrapper.dwcdn.net/qHw1A/3/" scrolling="no" frameborder="0" style="width: 0; min-width: 100% !important; border: none;" height="491"></iframe><script type="text/javascript">!function(){"use strict";window.addEventListener("message",(function(a){if(void 0!==a.data["datawrapper-height"])for(var e in a.data["datawrapper-height"]){var t=document.getElementById("datawrapper-chart-"+e)||document.querySelector("iframe[src*='"+e+"']");t&&(t.style.height=a.data["datawrapper-height"][e]+"px")}}))}(); </script> <file_sep>--- layout: post title: Visualizing Auto Insurance Rate subtitle: MakeoverMonday Week 20 tags: [MakeoverMonday] comments: true --- The #MakeoverMonday Challenge week 20 involved visualizing auto insurance rate in the US by State. The original viz was a radial chart created by [howmuch.net](https://howmuch.net/articles/car-insurance-rates-in-2020): ![Viz](/assets/img/car-insurance-rates-in-2020.jpg){: .mx-auto.d-block :} **What works?** * Title and subtitle are short and descriptive. * Design is visually attractive, related to the topic (circular chart, that resembles a wheel). * I liked the color palette. **What can be improved?** * I did not get the distinction between full & minimum rate by looking at the chart, I thought it could be clarifying to add the explanation in the chart or as a hover in an interactive version. * Even though the circle is attractive, it is not as effective to compare between states, especially between states that are far apart in the wheel. * The full and minimum rates are distinct measures, but the chart gives the impression that they add up. It can be a little confusing. * My final solution was a dot-plot with the minimum and full rates encoded as circles joined together by a line. States are ordered by their rank number. And I added a map to reinforce the ranking, especially the 3 most expensive states. * This is my makeover: <div class="mcb-wrap-inner"><div class="column mcb-column mcb-item-ny8ost4q1 one column_column"><div class="column_attr clearfix" style=""><center><iframe src="https://public.tableau.com/views/makeovermondaycars/carInsurance?:showVizHome=no&amp;:embed=true" width="1200" height="1100" frameborder="0"></iframe></center></div></div></div> <file_sep>--- layout: post title: LGBT youth and their experiences of discrimination subtitle: SWDChallenge tags: [SWDChallenge] comments: true --- A quick viz to participate in the #StorytellingWithData January challenge. Probably not the best way to allow precise comparisons between groups, but after seeing some nice small multiples of radar charts I thought I could give it a try as an exercise. The main point to convey visually is that for straight and cisgender youth the area covered by feelings of discrimination is very small, and for others it is much bigger. The analysis is part of current research I am carrying on, where I study the experience of violence and discrimination that LGBT youth suffers, and how that relates to several indicators of subjective wellbeing. ![Viz](/assets/img/SWD-small-multiples-challenge.png){: .mx-auto.d-block :} <file_sep>--- layout: post title: Popular films with a female director (2000-2018) subtitle: Area chart based on IMDB data tags: SWDChallenge --- I got encouraged to do this visualization after seeing the documentary ["Half the picture"](https://www.imdb.com/title/tt5713994/) of <NAME>... Watching that movie I got to know the challenges that women face to get the director role, and how the number of female directors has remained pretty much stable in the last decades. It seemed to me that the area chart served to make that point. In the main graph, we see a barely visible yellow area, which has not managed to increase significantly over the years. In the small multiples, we can see some nuances in the different film genres, although the opportunity barriers are present in pretty much every genre... showing that the opportunities to portray diverse experiences from the director's chair are not equal. The data comes from databases released by IMDb for personal, non-commercial use. And for the design I was inspired by the work of [<NAME>'s](https://public.tableau.com/profile/jessica7027#!/vizhome/BeverageofChoice/BeverageofChoice) area charts about beverage preferences in different countries and the tips of [Judit Bekker](https://www.youtube.com/watch?v=OywYYW4clCU&t=3151s) on how to combine Illustrator and Tableau. <div class="mcb-wrap-inner"><div class="column mcb-column mcb-item-ny8ost4q1 one column_column"><div class="column_attr clearfix" style=""><center><iframe src="https://public.tableau.com/views/FemaleDirectors/FemaleDirectors?:showVizHome=no&amp;:embed=true" width="1260" height="1380" frameborder="0"></iframe></center></div></div></div> <file_sep>--- layout: post title: The best LGBT-themed movies subtitle: Viz por Pride Month tags: comments: true --- # The topic Before June ended I wanted to create some kind of visualization that would commemorate this LGBT Pride Month. Several topics came to mind. Some of them were serious subjects -like hate crimes occurring around the world- and others were lighter in tone (I thought about doing a viz of one of my favorite tv shows, RuPaul’s Drag Race). After thinking it through, I decided to come back to the topic of films that I explored in [my visualization of female directors](https://public.tableau.com/profile/maximiliano4575#!/vizhome/FemaleDirectors/FemaleDirectors). In that viz, I showed how really few popular films were directed by women, and I showed how that trend has not changed significantly in the last years. With that data-story, I wanted to argue that it is not trivial who directs films because that role has the power to tell the story, the power to portray (or not portray) diverse life experiences. Having a landscape of directors that is so unbalanced according to gender implies that there are experiences and points of view that are not being represented. Groups of people that are not seeing themselves on the screen, who probably don’t relate or identify with the stories that are being showcased in the mainstream film industry. Something similar happens when we talk about how LGBT people are represented in cinema and in cultural products in general. A documentary that shows this dimension very well is [“The celluloid closet”](https://www.imdb.com/title/tt0112651/) by <NAME> and <NAME>, which shows how throughout the 20th century LGBT characters and stories entered the film industry only interstitially, indirectly, and mainly through subtleties. Today the reality is different. Every year many films that portray LGBT experiences are produced and released around the world. So the goal of my visualization was to highlight those films -those cultural objects- that help the LGBT community (especially teenagers and youth) to find narratives and characters with whom to identify and that help them develop their own biographies. # The data For the female directors' project, I analyzed data made available by [IMDB](https://www.imdb.com/). So I tried to start from there. However, the keyword system of the website that classified the films as LGBT-themed did not seem precise or exhaustive (films that did not have LGBT lives at their center had the tag, and other movies that for me were part of the canon did not have the tag). My next exploration was Wikipedia. There I found [lists of LGBT movies](https://en.wikipedia.org/wiki/List_of_LGBT-related_films_by_year) by decade, which I was able to extract and consolidate using R. With that data I could see how the number of movies that portray LGBT characters or stories has significantly increased in the last 30 years. <iframe title="Number of LGBT movies 1970-2020" aria-label="Interactive line chart" id="datawrapper-chart-tKFEP" src="https://datawrapper.dwcdn.net/tKFEP/1/" scrolling="no" frameborder="0" style="width: 0; min-width: 100% !important; max-width: 600 !important; border: none;" height="400"></iframe><script type="text/javascript">!function(){"use strict";window.addEventListener("message",(function(a){if(void 0!==a.data["datawrapper-height"])for(var e in a.data["datawrapper-height"]){var t=document.getElementById("datawrapper-chart-"+e)||document.querySelector("iframe[src*='"+e+"']");t&&(t.style.height=a.data["datawrapper-height"][e]+"px")}}))}(); </script> This data was promising: I had 2,258 titles, the year of release, the film’s director, country, and genre. However, I had no detail regarding what the movie was about, and collecting that information was going to take a long time. So I left that data for some future exploration. In the end, I came across a very [comprehensive article on the website Rotten Tomatoes](https://editorial.rottentomatoes.com/guide/best-lgbt-movies-of-all-time/), that featured the 200 best LGBT movies. The list had the hyperlinks to the entry for each film, which allowed me to get their synopsis. With that information I classified each movie into one of five categories, depending on which was the focus or main character of the story (lesbian, gay, bisexual, trans or LGBTQ+ in general). # The Viz I got a first idea on how to visualize the data when I was watching a [Tidy Tuesday live Screencast made by <NAME>](https://www.youtube.com/watch?v=-W-OopvhNPo). There, David made a timeline using ggplot that I liked and thought I could use: ![Viz](/assets/img/reference.png){: .mx-auto.d-block :} With that idea in mind, I made a very basic sketch. I started with something similar to that timeline, but due to the structure of my data (there can be more than one movie per year) I realized that what I needed was a “bee swarm plot”. ![Viz](/assets/img/sketch.jpg){: .mx-auto.d-block :} I imagine there must be more elegant ways to do a bee swarm plot, but I followed Ken Flerlage's principle that [everything can be visualized in Tableau if you have an X & Y coordinate](https://www.flerlagetwins.com/2017/11/beyond-show-me-part-1-its-all-about-x-y_46.html). So with a combination of tools/formats ([RawGraphs](https://rawgraphs.io/) & SVGs) I extracted the X & Y coordinates of the bee swarm plot and added them to my LGBT movie data frame. With that data, I was able to make a first version of the chart in Tableau, and I started to refine the design from that. ![Viz](/assets/img/viz.png){: .mx-auto.d-block :} For the interactive layer, I wanted to allow the user to get more in-depth information about each point/movie. So I added a tooltip that included the title, year, rank, and score of the movie. Along with that basic information, I added an excerpt from the synopsis and the poster of the movie (which I incorporated into the tooltip following [Ryan Sleeper’s tutorial](https://playfairdata.com/how-to-add-an-image-to-a-tableau-tooltip/)). To convey a visual feeling of Pride Month I looked for inspiration on the web and [found a free font that I loved and that was inspired by the rainbow flag creator, <NAME>](https://www.typewithpride.com/). I used the font for the title and the labels. After that, I was almost ready. But I wanted to add some text that would not compete so much with the chart. So I added a black column in the left that would give me space to add some written context of the data, explain how to read the chart, and add a quote that I feel sums up nicely why LGBT movies are important to many people's lives. After several tweaks of aligning elements, adjusting the size, etc. I got to this final product Any feedback is welcome at [@maxthamt](https://twitter.com/maxthamt)! <div class="mcb-wrap-inner"><div class="column mcb-column mcb-item-ny8ost4q1 one column_column"><div class="column_attr clearfix" style=""><center><iframe src="https://public.tableau.com/views/pride/lgbt-movies?:showVizHome=no&amp;:embed=true" width="1093" height="819" frameborder="0"></iframe></center></div></div></div> <file_sep>--- layout: page title: About me --- I am a social science researcher and I have been studying and exploring the data visualization field for the last year or so. I mainly viz for work to communicate research insights about educational topics & youth studies. I also do viz for personal research projects and to learn design principles & techniques. Here is my [Tableau Public profile](https://public.tableau.com/profile/maximiliano4575#!/) and this is my [Twitter](https://twitter.com/maxthamt).
f064b48e7e19116b893426c890f3b7636e039ae3
[ "Markdown" ]
8
Markdown
maxthamt/maxthamt.github.io
3a996760b099bf05a7a6f92475b60df82d42d943
af99357a23ebf3a35a381f94fefdafe922f9556e
refs/heads/master
<repo_name>elttam/ctf-eminem-brown<file_sep>/webapp/app.rb #!/usr/bin/env ruby class Gem::StubSpecification; def data; raise "no-data-for-you"; end; end class Flag def self.[](password) if password == "<PASSWORD>" puts File.read("flag.txt") end end end unless ARGV.empty? Marshal.load(STDIN.read) exit! end require "sinatra" require "sinatra/cookies" require "base64" configure do enable :inline_templates end helpers do include ERB::Util end set :environment, :production get "/" do @title = "Eminem Challenge" erb :index end get "/version" do RUBY_VERSION end get "/source" do File.read(__FILE__) end get "/bruce" do payload = Base64.urlsafe_decode64(params[:payload].to_s) response = "" IO.popen("ruby #{__FILE__} --stan 2>/dev/null", "r+") do |pipe| pipe.puts payload pipe.close_write response = pipe.gets end response end __END__ @@ layout <!doctype html> <html> <head> <style> html, body { height: 100%; background-color: brown; height: 100%; margin: 0px; padding: 0px; color: white; font-family: courier, monospace; text-align: center; } h1 { margin-top: 5%; } a { color: green; } input { padding: 10px; } </style> <title><%= h @title %></title> </head> <body> <div class="box"> <h1><%= h @title %></h1> <%= yield %></p> </div> </body> </html> @@ index <a href="/version">Version</a><br /> <a href="/source">Source Code</a>
b17ac3cd1750eadac8c46a563d361371fe9dd3e6
[ "Ruby" ]
1
Ruby
elttam/ctf-eminem-brown
949585534efdee5b54cdbf2d2a8dd2ed83df6161
8f9971ba8858f4d2b79e33585e5e0be0b450136d
refs/heads/master
<file_sep>import React from 'react' import { IonPage, IonHeader, IonToolbar, IonTitle, IonContent } from '@ionic/react' const AddPage: React.FC=()=>{ return( <IonPage> <IonHeader> <IonToolbar> <IonTitle>Add New Order</IonTitle> </IonToolbar> </IonHeader> <IonContent> <h1> Stuff here </h1> </IonContent> </IonPage> ) }; export default AddPage <file_sep>import React from 'react'; import { Route,Redirect} from 'react-router-dom'; import { IonApp, IonRouterOutlet, IonTabs, IonTabBar, IonTabButton, IonIcon, IonLabel } from '@ionic/react'; import { IonReactRouter } from '@ionic/react-router'; /* Core CSS required for Ionic components to work properly */ import '@ionic/react/css/core.css'; /* Basic CSS for apps built with Ionic */ import '@ionic/react/css/normalize.css'; import '@ionic/react/css/structure.css'; import '@ionic/react/css/typography.css'; import { apps, flash, send } from 'ionicons/icons'; import AddPage from './pages/Add'; import ListPage from './pages/List'; import StatusPage from './pages/Status'; const App: React.FC = () => ( <IonApp> <IonReactRouter> <IonTabs> <IonRouterOutlet> <Route path="/add" component={AddPage} exact={true} /> <Route path="/list" component={ListPage} exact={true} /> <Route path="/status" component={StatusPage} exact={true} /> <Route path="/" render={() => <Redirect to="/list" />} exact={true} /> </IonRouterOutlet> <IonTabBar slot="bottom"> <IonTabButton tab="tab1" href="/add"> <IonIcon icon={flash} /> <IonLabel>Add</IonLabel> </IonTabButton> <IonTabButton tab="tab2" href="/list"> <IonIcon icon={apps} /> <IonLabel>List</IonLabel> </IonTabButton> <IonTabButton tab="tab3" href="/status"> <IonIcon icon={send} /> <IonLabel>Status</IonLabel> </IonTabButton> </IonTabBar> </IonTabs> </IonReactRouter> </IonApp> ); export default App<file_sep>import React from 'react' import { IonPage, IonHeader, IonToolbar, IonTitle, IonContent } from '@ionic/react'; const ListPage: React.FC=()=>{ return( <IonPage> <IonHeader> <IonToolbar> <IonTitle>Order List</IonTitle> </IonToolbar> </IonHeader> <IonContent> <h1> Stuff here </h1> </IonContent> </IonPage> ) }; export default ListPage
a83554e2b9c8b654d0a653a66e12ede7bdc571f5
[ "TSX" ]
3
TSX
matt3214/order-up
d2d38c659e8068c947b02f4ccaa364ddc4e90a0d
751e4e7213a11b266b098b7ffd2571c90cadf21d
refs/heads/master
<repo_name>sameer1319/sameer1319.github.io<file_sep>/README.md # sameer1319.github.io
7bbbda092b82201cd4dcab9156c99bb3cad5833d
[ "Markdown" ]
1
Markdown
sameer1319/sameer1319.github.io
251f361e0383c99fd7b7297c1682670bc355b5ab
828b28b56cc7466fecb554eade1977ba4b63babb
refs/heads/master
<repo_name>zegitz/emmefx-frontend<file_sep>/src/js/services/angular-authentication.js (function (window, angular, undefined) { 'use strict'; angular.module('Authentication', ['ngCookies']) .service('$authentication', ['$cookieStore','$location','$rootScope', function ($cookieStore,$location,$rootScope) { var $authService = this; //$cookieStore.put("authentication",$estruturaPadraoInfo); //FORCE LOGOUT $authService.data = (!$cookieStore.get("authentication") ? {logado: false, user: {admin: false}} : $cookieStore.get("authentication")); //console.log("Authentication data:",$authService.data); $authService.verificaLogin = function () { if (!$authService.data.logado) { $authService.logout(); } }; $authService.login = function ($userInfo, $redirect) { if ($authService.data.user.account_status && $userInfo.account_block_payment_pending) { $location.path('/order/list'); } $authService.data.logado = true; $authService.data.user = angular.extend($authService.data.user, ($userInfo == "undefined" ? {} : $userInfo)); //console.log($authService.data.user,$userInfo); $cookieStore.put("authentication",$authService.data); if ($("#rs-wrapper").data('backstretch')) { $("#rs-wrapper").backstretch("destroy", 0); $("#rs-wrapper").data('backstretch',''); } if ($redirect != "undefined" && $redirect) { document.location.href = config.authentication.url.login; } }; $authService.logout = function ($redirect) { console.log("AuthService Logout"); $("#rs-wrapper").backstretch("assets/img/bg.jpg"); delete $storage.loginInformation; $rootScope.$localStorage.$reset(); $authService.data = {logado: false, user: {admin: false}}; var elementsShowLogado = angular.element(document).find(".logado"); // console.log(elementsShowLogado); elementsShowLogado.css("display", 'none'); $cookieStore.put("authentication",$authService.data); if ($redirect != "undefined" && $redirect) { document.location.href = config.authentication.url.login; } }; }]); })(window, window.angular); <file_sep>/src/js/OLD/23_login.js (function () { 'use strict'; angular.module('emmefxApp') .controller('loginctrl',loginctrl); loginctrl.$inject = ['$window','$scope', '$rootScope','$http', 'cssInjector','$interval', '$timeout','$localStorage','$resource','toastr'] function loginctrl($window,$scope, $rootScope, $http ,cssInjector, $interval, $timeout,$localStorage, $resource, toastr ) { var $ctrl = this; $scope.userlogin = []; $rootScope.storage = $localStorage; cssInjector.add("/css/bootstrap.css"); cssInjector.add("/css/font1.css"); cssInjector.add("/css/font2.css"); cssInjector.add("/css/font3.css"); cssInjector.add("/css/line-awesome.css"); cssInjector.add("/css/flag-icon.css"); cssInjector.add("/css/pace.css"); cssInjector.add("/css/custom.css"); cssInjector.add("/css/bootstrap-extended.css"); cssInjector.add("/css/colors.css"); cssInjector.add("/css/components.css"); cssInjector.add("/css/vertical-compact-menu.css"); cssInjector.add("/css/cryptocoins.css") cssInjector.add("/css/account-login.css"); cssInjector.add("/css/angular-toastr.css"); var addressApi = "http://netpdm.com.br:83/api"; $scope.submitLogin = function(){ $http({ url: addressApi+'/user/login', method: "POST", headers: { 'Content-Type': "application/json;charset=utf-8" }, data: { "email" : $scope.userlogin.email, "password" : $<PASSWORD> } }) .then(function(response) { if(response.data.auth == 1){ location.href = '#!/home'; $rootScope.dataUsuario = response.data; $rootScope.storage = $localStorage.$default(response.data); toastr.success("Seja Bem Vindo "+ response.data.username, 'Autenticação Ok!'); }else{ toastr.error("Verifique sua Senha.", 'Erro de Autenticação!'); } }, function(response) { // optional console.log(response); }); }; } })();<file_sep>/src/js/controllers/home.js (function () { 'use strict'; angular.module('emmefxApp') .controller('homectrl', homectrl) homectrl.$inject = ['$window','$scope', '$rootScope', '$http','$localStorage','$interval', '$timeout'] function homectrl($window,$scope, $rootScope, $http ,$localStorage, $interval, $timeout) { var $ctrl = this; $rootScope.storage = $localStorage; if(!($rootScope.storage.auth == 1)){ $localStorage.$reset(); location.href = '#!/login'; } $ctrl.geragrafico = function(){ var verticalBar3 = new Chartist.Bar('#ico-token-supply-demand-chart', { labels: ['01/11', '02/11', '03/11', '04/11', '05/11', '06/11', '07/11', '08/11', '09/11', '10/11', '11/11', '12/11'], series: [ [4000, 7000, 5000, 2500, 5200, 4400, 7000, 4200, 7500, 2000, 3000, 5000], ] }, { axisY: { labelInterpolationFnc: function(value) { return (value / 1000) + 'k'; }, height: 10, offset: 40, scaleMinSpace: 20 }, axisX: { showGrid: true, labelInterpolationFnc: function(value, index) { return value; } }, plugins: [ Chartist.plugins.tooltip({ appendToBody: true, pointClass: 'ct-point' }) ] }); verticalBar3.on('draw', function(data) { if (data.type === 'bar') { data.element.attr({ style: 'stroke-width: 25px', y1: 250, x1: data.x1 + 0.001 }); data.group.append(new Chartist.Svg('circle', { cx: data.x2, cy: data.y2, r: 12 }, 'ct-slice-pie')); } }); verticalBar3.on('created', function(data) { var defs = data.svg.querySelector('defs') || data.svg.elem('defs'); defs.elem('linearGradient', { id: 'barGradient3', x1: 0, y1: 0, x2: 0, y2: 1 }).elem('stop', { offset: 0, 'stop-color': 'rgb(255, 63, 45)' }).parent().elem('stop', { offset: 1, 'stop-color': 'rgb(254, 200, 0)' }); return defs; }); } $ctrl.geragrafico1 = function(){ var chart = new Chartist.Pie('#token-distribution-chart', { // series: [10, 20, 50, 20, 5, 50, 15], series: [{ "name": "<NAME>", "className": "ct-crowdsale", "value": 5 }, { "name": "<NAME>", "className": "ct-team", "value": 15 }, { "name": "<NAME>", "className": "ct-advisors", "value": 25 }, { "name": "<NAME>", "className": "ct-project-advisors", "value": 45 }, { "name": "<NAME>", "className": "ct-masternodes", "value": 10 }, ], labels: ["Private Sale", "Pre Sale", "Start Sale", "Public Sale", "Team"] }, { donut: true, startAngle: 30, donutSolid: true, donutWidth: 50, plugins: [ Chartist.plugins.tooltip({ appendToBody: true, pointClass: 'ct-tooltip' }) ], labelInterpolationFnc: function(value) { var total = chart.data.series.reduce(function(prev, series) { return prev + series.value; }, 0); return total + '%'; } }); chart.on('created', function() { var defs = chart.svg.elem('defs'); defs.elem('linearGradient', { id: 'ct-crowdsale', x1: 0, y1: 1, x2: 0, y2: 0 }).elem('stop', { offset: 0, 'stop-color': '#2191ff' }).parent().elem('stop', { offset: 1, 'stop-color': '#2abbfe' }); defs.elem('linearGradient', { id: 'ct-team', x1: 0, y1: 1, x2: 0, y2: 0 }).elem('stop', { offset: 0, 'stop-color': '#892ffe' }).parent().elem('stop', { offset: 1, 'stop-color': '#c37bfe' }); defs.elem('linearGradient', { id: 'ct-advisors', x1: 0, y1: 1, x2: 0, y2: 0 }).elem('stop', { offset: 0, 'stop-color': '#6aecae' }).parent().elem('stop', { offset: 1, 'stop-color': '#39d98c' }); defs.elem('linearGradient', { id: 'ct-project-advisors', x1: 0, y1: 1, x2: 0, y2: 0 }).elem('stop', { offset: 0, 'stop-color': '#f19686' }).parent().elem('stop', { offset: 1, 'stop-color': '#e85d44' }); defs.elem('linearGradient', { id: 'ct-masternodes', x1: 0, y1: 1, x2: 0, y2: 0 }).elem('stop', { offset: 0, 'stop-color': '#e67ea5' }).parent().elem('stop', { offset: 1, 'stop-color': '#fa679d' }); defs.elem('linearGradient', { id: 'ct-program', x1: 0, y1: 1, x2: 0, y2: 0 }).elem('stop', { offset: 0, 'stop-color': '#99f3f3' }).parent().elem('stop', { offset: 1, 'stop-color': '#33d4d8' }); }); chart.on('draw', function(data) { if (data.type === 'label') { if (data.index === 0) { data.element.attr({ dx: data.element.root().width() / 2, dy: data.element.root().height() / 2 }); } else { data.element.remove(); } } }); } $ctrl.timeline = function(){ jQuery(document).ready(function($){ var timelines = $('.cd-horizontal-timeline'), eventsMinDistance = 60; (timelines.length > 0) && initTimeline(timelines); function initTimeline(timelines) { timelines.each(function(){ var timeline = $(this), timelineComponents = {}; //cache timeline components timelineComponents['timelineWrapper'] = timeline.find('.events-wrapper'); timelineComponents['eventsWrapper'] = timelineComponents['timelineWrapper'].children('.events'); timelineComponents['fillingLine'] = timelineComponents['eventsWrapper'].children('.filling-line'); timelineComponents['timelineEvents'] = timelineComponents['eventsWrapper'].find('a'); timelineComponents['timelineDates'] = parseDate(timelineComponents['timelineEvents']); timelineComponents['eventsMinLapse'] = minLapse(timelineComponents['timelineDates']); timelineComponents['timelineNavigation'] = timeline.find('.cd-timeline-navigation'); timelineComponents['eventsContent'] = timeline.children('.events-content'); //assign a left postion to the single events along the timeline setDatePosition(timelineComponents, eventsMinDistance); //assign a width to the timeline var timelineTotWidth = setTimelineWidth(timelineComponents, eventsMinDistance); //the timeline has been initialize - show it timeline.addClass('loaded'); //detect click on the next arrow timelineComponents['timelineNavigation'].on('click', '.next', function(event){ event.preventDefault(); updateSlide(timelineComponents, timelineTotWidth, 'next'); }); //detect click on the prev arrow timelineComponents['timelineNavigation'].on('click', '.prev', function(event){ event.preventDefault(); updateSlide(timelineComponents, timelineTotWidth, 'prev'); }); //detect click on the a single event - show new event content timelineComponents['eventsWrapper'].on('click', 'a', function(event){ event.preventDefault(); timelineComponents['timelineEvents'].removeClass('selected'); $(this).addClass('selected'); updateOlderEvents($(this)); updateFilling($(this), timelineComponents['fillingLine'], timelineTotWidth); updateVisibleContent($(this), timelineComponents['eventsContent']); }); //on swipe, show next/prev event content timelineComponents['eventsContent'].on('swipeleft', function(){ var mq = checkMQ(); ( mq == 'mobile' ) && showNewContent(timelineComponents, timelineTotWidth, 'next'); }); timelineComponents['eventsContent'].on('swiperight', function(){ var mq = checkMQ(); ( mq == 'mobile' ) && showNewContent(timelineComponents, timelineTotWidth, 'prev'); }); //keyboard navigation $(document).keyup(function(event){ if(event.which=='37' && elementInViewport(timeline.get(0)) ) { showNewContent(timelineComponents, timelineTotWidth, 'prev'); } else if( event.which=='39' && elementInViewport(timeline.get(0))) { showNewContent(timelineComponents, timelineTotWidth, 'next'); } }); }); } function updateSlide(timelineComponents, timelineTotWidth, string) { //retrieve translateX value of timelineComponents['eventsWrapper'] var translateValue = getTranslateValue(timelineComponents['eventsWrapper']), wrapperWidth = Number(timelineComponents['timelineWrapper'].css('width').replace('px', '')); //translate the timeline to the left('next')/right('prev') (string == 'next') ? translateTimeline(timelineComponents, translateValue - wrapperWidth + eventsMinDistance, wrapperWidth - timelineTotWidth) : translateTimeline(timelineComponents, translateValue + wrapperWidth - eventsMinDistance); } function showNewContent(timelineComponents, timelineTotWidth, string) { //go from one event to the next/previous one var visibleContent = timelineComponents['eventsContent'].find('.selected'), newContent = ( string == 'next' ) ? visibleContent.next() : visibleContent.prev(); if ( newContent.length > 0 ) { //if there's a next/prev event - show it var selectedDate = timelineComponents['eventsWrapper'].find('.selected'), newEvent = ( string == 'next' ) ? selectedDate.parent('li').next('li').children('a') : selectedDate.parent('li').prev('li').children('a'); updateFilling(newEvent, timelineComponents['fillingLine'], timelineTotWidth); updateVisibleContent(newEvent, timelineComponents['eventsContent']); newEvent.addClass('selected'); selectedDate.removeClass('selected'); updateOlderEvents(newEvent); updateTimelinePosition(string, newEvent, timelineComponents); } } function updateTimelinePosition(string, event, timelineComponents) { //translate timeline to the left/right according to the position of the selected event var eventStyle = window.getComputedStyle(event.get(0), null), eventLeft = Number(eventStyle.getPropertyValue("left").replace('px', '')), timelineWidth = Number(timelineComponents['timelineWrapper'].css('width').replace('px', '')), timelineTotWidth = Number(timelineComponents['eventsWrapper'].css('width').replace('px', '')); var timelineTranslate = getTranslateValue(timelineComponents['eventsWrapper']); if( (string == 'next' && eventLeft > timelineWidth - timelineTranslate) || (string == 'prev' && eventLeft < - timelineTranslate) ) { translateTimeline(timelineComponents, - eventLeft + timelineWidth/2, timelineWidth - timelineTotWidth); } } function translateTimeline(timelineComponents, value, totWidth) { var eventsWrapper = timelineComponents['eventsWrapper'].get(0); value = (value > 0) ? 0 : value; //only negative translate value value = ( !(typeof totWidth === 'undefined') && value < totWidth ) ? totWidth : value; //do not translate more than timeline width setTransformValue(eventsWrapper, 'translateX', value+'px'); //update navigation arrows visibility (value == 0 ) ? timelineComponents['timelineNavigation'].find('.prev').addClass('inactive') : timelineComponents['timelineNavigation'].find('.prev').removeClass('inactive'); (value == totWidth ) ? timelineComponents['timelineNavigation'].find('.next').addClass('inactive') : timelineComponents['timelineNavigation'].find('.next').removeClass('inactive'); } function updateFilling(selectedEvent, filling, totWidth) { //change .filling-line length according to the selected event var eventStyle = window.getComputedStyle(selectedEvent.get(0), null), eventLeft = eventStyle.getPropertyValue("left"), eventWidth = eventStyle.getPropertyValue("width"); eventLeft = Number(eventLeft.replace('px', '')) + Number(eventWidth.replace('px', ''))/2; var scaleValue = eventLeft/totWidth; setTransformValue(filling.get(0), 'scaleX', scaleValue); } function setDatePosition(timelineComponents, min) { for (var i = 0; i < timelineComponents['timelineDates'].length; i++) { var distance = daydiff(timelineComponents['timelineDates'][0], timelineComponents['timelineDates'][i]), distanceNorm = Math.round(distance/timelineComponents['eventsMinLapse']) + 2; timelineComponents['timelineEvents'].eq(i).css('left', distanceNorm*min+'px'); } } function setTimelineWidth(timelineComponents, width) { var timeSpan = daydiff(timelineComponents['timelineDates'][0], timelineComponents['timelineDates'][timelineComponents['timelineDates'].length-1]), timeSpanNorm = timeSpan/timelineComponents['eventsMinLapse'], timeSpanNorm = Math.round(timeSpanNorm) + 4, totalWidth = timeSpanNorm*width; timelineComponents['eventsWrapper'].css('width', totalWidth+'px'); updateFilling(timelineComponents['eventsWrapper'].find('a.selected'), timelineComponents['fillingLine'], totalWidth); updateTimelinePosition('next', timelineComponents['eventsWrapper'].find('a.selected'), timelineComponents); return totalWidth; } function updateVisibleContent(event, eventsContent) { var eventDate = event.data('date'), visibleContent = eventsContent.find('.selected'), selectedContent = eventsContent.find('[data-date="'+ eventDate +'"]'), selectedContentHeight = selectedContent.height(); if (selectedContent.index() > visibleContent.index()) { var classEnetering = 'selected enter-right', classLeaving = 'leave-left'; } else { var classEnetering = 'selected enter-left', classLeaving = 'leave-right'; } selectedContent.attr('class', classEnetering); visibleContent.attr('class', classLeaving).one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(){ visibleContent.removeClass('leave-right leave-left'); selectedContent.removeClass('enter-left enter-right'); }); eventsContent.css('height', selectedContentHeight+'px'); } function updateOlderEvents(event) { event.parent('li').prevAll('li').children('a').addClass('older-event').end().end().nextAll('li').children('a').removeClass('older-event'); } function getTranslateValue(timeline) { var timelineStyle = window.getComputedStyle(timeline.get(0), null), timelineTranslate = timelineStyle.getPropertyValue("-webkit-transform") || timelineStyle.getPropertyValue("-moz-transform") || timelineStyle.getPropertyValue("-ms-transform") || timelineStyle.getPropertyValue("-o-transform") || timelineStyle.getPropertyValue("transform"); if( timelineTranslate.indexOf('(') >=0 ) { var timelineTranslate = timelineTranslate.split('(')[1]; timelineTranslate = timelineTranslate.split(')')[0]; timelineTranslate = timelineTranslate.split(','); var translateValue = timelineTranslate[4]; } else { var translateValue = 0; } return Number(translateValue); } function setTransformValue(element, property, value) { element.style["-webkit-transform"] = property+"("+value+")"; element.style["-moz-transform"] = property+"("+value+")"; element.style["-ms-transform"] = property+"("+value+")"; element.style["-o-transform"] = property+"("+value+")"; element.style["transform"] = property+"("+value+")"; } //based on http://stackoverflow.com/questions/542938/how-do-i-get-the-number-of-days-between-two-dates-in-javascript function parseDate(events) { var dateArrays = []; events.each(function(){ var singleDate = $(this), dateComp = singleDate.data('date').split('T'); if( dateComp.length > 1 ) { //both DD/MM/YEAR and time are provided var dayComp = dateComp[0].split('/'), timeComp = dateComp[1].split(':'); } else if( dateComp[0].indexOf(':') >=0 ) { //only time is provide var dayComp = ["2000", "0", "0"], timeComp = dateComp[0].split(':'); } else { //only DD/MM/YEAR var dayComp = dateComp[0].split('/'), timeComp = ["0", "0"]; } var newDate = new Date(dayComp[2], dayComp[1]-1, dayComp[0], timeComp[0], timeComp[1]); dateArrays.push(newDate); }); return dateArrays; } function daydiff(first, second) { return Math.round((second-first)); } function minLapse(dates) { //determine the minimum distance among events var dateDistances = []; for (var i = 1; i < dates.length; i++) { var distance = daydiff(dates[i-1], dates[i]); dateDistances.push(distance); } return Math.min.apply(null, dateDistances); } /* How to tell if a DOM element is visible in the current viewport? http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport */ function elementInViewport(el) { var top = el.offsetTop; var left = el.offsetLeft; var width = el.offsetWidth; var height = el.offsetHeight; while(el.offsetParent) { el = el.offsetParent; top += el.offsetTop; left += el.offsetLeft; } return ( top < (window.pageYOffset + window.innerHeight) && left < (window.pageXOffset + window.innerWidth) && (top + height) > window.pageYOffset && (left + width) > window.pageXOffset ); } function checkMQ() { //check if mobile or desktop device return window.getComputedStyle(document.querySelector('.cd-horizontal-timeline'), '::before').getPropertyValue('content').replace(/'/g, "").replace(/"/g, ""); } }); } $ctrl.appmenu = function() { /*========================================================================================= File Name: app-menu.js Description: Menu navigation, custom scrollbar, hover scroll bar, multilevel menu initialization and manipulations ---------------------------------------------------------------------------------------- Item Name: Crypto ICO - Cryptocurrency Website Landing Page HTML + Dashboard Template Version: 1.0 Author: Pixinvent Author URL: hhttp://www.themeforest.net/user/pixinvent ==========================================================================================*/ (function(window, document, $) { 'use strict'; $.app = $.app || {}; var $body = $('body'); var $window = $( window ); // Main menu $.app.menu = { expanded: null, collapsed: null, hidden : null, container: null, horizontalMenu: false, manualScroller: { obj: null, init: function() { var scroll_theme = ($('.main-menu').hasClass('menu-dark')) ? 'light' : 'dark'; this.obj = $(".main-menu-content").perfectScrollbar({ suppressScrollX: true, theme: scroll_theme }); }, update: function() { if (this.obj) { // Scroll to currently active menu on page load if data-scroll-to-active is true if($('.main-menu').data('scroll-to-active') === true){ var position; if( $(".main-menu-content").find('li.active').parents('li').length > 0 ){ position = $(".main-menu-content").find('li.active').parents('li').last().position(); } else{ position = $(".main-menu-content").find('li.active').position(); } setTimeout(function(){ // $.app.menu.container.scrollTop(position.top); if(position !== undefined){ $.app.menu.container.stop().animate({scrollTop:position.top}, 300); } $('.main-menu').data('scroll-to-active', 'false'); },300); } $(".main-menu-content").perfectScrollbar('update'); } }, enable: function() { this.init(); }, disable: function() { if (this.obj) { $('.main-menu-content').perfectScrollbar('destroy'); } }, updateHeight: function(){ if( ($body.data('menu') == 'vertical-menu' || $body.data('menu') == 'vertical-menu-modern' || $body.data('menu') == 'vertical-overlay-menu' ) && $('.main-menu').hasClass('menu-fixed')){ $('.main-menu-content').css('height', $(window).height() - $('.header-navbar').height() - $('.main-menu-header').outerHeight() - $('.main-menu-footer').outerHeight() ); this.update(); } } }, init: function(compactMenu) { if($('.main-menu-content').length > 0){ this.container = $('.main-menu-content'); var menuObj = this; var defMenu = ''; if(compactMenu === true){ defMenu = 'collapsed'; } this.change(defMenu); } }, change: function(defMenu) { var currentBreakpoint = Unison.fetch.now(); // Current Breakpoint this.reset(); var menuType = $body.data('menu'); if (currentBreakpoint) { switch (currentBreakpoint.name) { case 'xl': case 'lg': if(menuType === 'vertical-overlay-menu'){ this.hide(); } else if(menuType === 'vertical-compact-menu'){ this.open(); } else{ if(defMenu === 'collapsed') this.collapse(defMenu); else this.expand(); } break; case 'md': if(menuType === 'vertical-overlay-menu'){ this.hide(); } else if(menuType === 'vertical-compact-menu'){ this.open(); } else{ this.collapse(); } break; case 'sm': this.hide(); break; case 'xs': this.hide(); break; } } // On the small and extra small screen make them overlay menu if(menuType === 'vertical-compact-menu'){ this.toOverlayMenu(currentBreakpoint.name); } // Added data attribute brand-center for navbar-brand-center // TODO:AJ: Shift this feature in PUG. if($('.header-navbar').hasClass('navbar-brand-center')){ $('.header-navbar').attr('data-nav','brand-center'); } if(currentBreakpoint.name == 'sm' || currentBreakpoint.name == 'xs'){ $('.header-navbar[data-nav=brand-center]').removeClass('navbar-brand-center'); }else{ $('.header-navbar[data-nav=brand-center]').addClass('navbar-brand-center'); } // Dropdown submenu on small screen on click // -------------------------------------------------- $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) { if($(this).siblings('ul.dropdown-menu').length > 0){ event.preventDefault(); } event.stopPropagation(); $(this).parent().siblings().removeClass('show'); $(this).parent().toggleClass('show'); }); }, transit: function(callback1, callback2) { var menuObj = this; $body.addClass('changing-menu'); callback1.call(menuObj); if($body.hasClass('vertical-layout')){ if($body.hasClass('menu-open') || $body.hasClass('menu-expanded')){ $('.menu-toggle').addClass('is-active'); // Show menu header search when menu is normally visible if( $body.data('menu') === 'vertical-menu' || $body.data('menu') === 'vertical-content-menu'){ if($('.main-menu-header')){ $('.main-menu-header').show(); } } } else{ $('.menu-toggle').removeClass('is-active'); // Hide menu header search when only menu icons are visible if( $body.data('menu') === 'vertical-menu' || $body.data('menu') === 'vertical-content-menu'){ if($('.main-menu-header')){ $('.main-menu-header').hide(); } } } } setTimeout(function() { callback2.call(menuObj); $body.removeClass('changing-menu'); menuObj.update(); }, 500); }, open: function() { this.transit(function() { $body.removeClass('menu-hide menu-collapsed').addClass('menu-open'); this.hidden = false; this.expanded = true; }, function() { if(!$('.main-menu').hasClass('menu-native-scroll') && $('.main-menu').hasClass('menu-fixed') ){ this.manualScroller.enable(); $('.main-menu-content').css('height', $(window).height() - $('.header-navbar').height() - $('.main-menu-header').outerHeight() - $('.main-menu-footer').outerHeight() ); // this.manualScroller.update(); } }); }, hide: function() { this.transit(function() { $body.removeClass('menu-open menu-expanded').addClass('menu-hide'); this.hidden = true; this.expanded = false; }, function() { if(!$('.main-menu').hasClass('menu-native-scroll') && $('.main-menu').hasClass('menu-fixed')){ this.manualScroller.enable(); } }); }, expand: function() { if (this.expanded === false) { if( $body.data('menu') == 'vertical-menu-modern' ){ $('.modern-nav-toggle').find('.toggle-icon') .removeClass('ft-toggle-left').addClass('ft-toggle-right'); // Code for localStorage if (typeof(Storage) !== "undefined") { localStorage.setItem("menuLocked", "true"); } } /*if( $body.data('menu') == 'vertical-menu' || $body.data('menu') == 'vertical-menu-modern'){ this.changeLogo('expand'); }*/ this.transit(function() { $body.removeClass('menu-collapsed').addClass('menu-expanded'); this.collapsed = false; this.expanded = true; }); } }, collapse: function(defMenu) { if (this.collapsed === false) { if( $body.data('menu') == 'vertical-menu-modern' ){ $('.modern-nav-toggle').find('.toggle-icon') .removeClass('ft-toggle-right').addClass('ft-toggle-left'); // Code for localStorage if (typeof(Storage) !== "undefined") { localStorage.setItem("menuLocked", "false"); } } this.transit(function() { $body.removeClass('menu-expanded').addClass('menu-collapsed'); this.collapsed = true; this.expanded = false; }); } }, toOverlayMenu: function(screen){ var menu = $body.data('menu'); if(screen == 'sm' || screen == 'xs'){ if($body.hasClass(menu)){ $body.removeClass(menu).addClass('vertical-overlay-menu'); } if(menu == 'vertical-content-menu'){ $('.main-menu').addClass('menu-fixed'); } } else{ if($body.hasClass('vertical-overlay-menu')){ $body.removeClass('vertical-overlay-menu').addClass(menu); } if(menu == 'vertical-content-menu'){ $('.main-menu').removeClass('menu-fixed'); } } }, toggle: function() { var currentBreakpoint = Unison.fetch.now(); // Current Breakpoint var collapsed = this.collapsed; var expanded = this.expanded; var hidden = this.hidden; var menu = $body.data('menu'); switch (currentBreakpoint.name) { case 'xl': case 'lg': case 'md': if(expanded === true){ if(menu == 'vertical-compact-menu' || menu == 'vertical-overlay-menu'){ this.hide(); } else{ this.collapse(); } } else{ if(menu == 'vertical-compact-menu' || menu == 'vertical-overlay-menu'){ this.open(); } else{ this.expand(); } } break; case 'sm': if (hidden === true) { this.open(); } else { this.hide(); } break; case 'xs': if (hidden === true) { this.open(); } else { this.hide(); } break; } }, update: function() { this.manualScroller.update(); }, reset: function() { this.expanded = false; this.collapsed = false; this.hidden = false; $body.removeClass('menu-hide menu-open menu-collapsed menu-expanded'); }, }; // Navigation Menu $.app.nav = { container: $('.navigation-main'), initialized : false, navItem: $('.navigation-main').find('li').not('.navigation-category'), config: { speed: 300, }, init: function(config) { this.initialized = true; // Set to true when initialized $.extend(this.config, config); this.bind_events(); }, bind_events: function() { var menuObj = this; $('.navigation-main').on('mouseenter.app.menu', 'li', function() { var $this = $(this); $('.hover', '.navigation-main').removeClass('hover'); if( ($body.hasClass('menu-collapsed') && $body.data('menu') != 'vertical-menu-modern') || ($body.data('menu') == 'vertical-compact-menu' && !$body.hasClass('vertical-overlay-menu')) ){ $('.main-menu-content').children('span.menu-title').remove(); $('.main-menu-content').children('a.menu-title').remove(); $('.main-menu-content').children('ul.menu-content').remove(); // Title var menuTitle = $this.find('span.menu-title').clone(), tempTitle, tempLink; if(!$this.hasClass('has-sub') ){ tempTitle = $this.find('span.menu-title').text(); tempLink = $this.children('a').attr('href'); if(tempTitle !== ''){ menuTitle = $("<a>"); menuTitle.attr("href", tempLink); menuTitle.attr("title", tempTitle); menuTitle.text(tempTitle); menuTitle.addClass("menu-title"); } } // menu_header_height = ($('.main-menu-header').length) ? $('.main-menu-header').height() : 0, // fromTop = menu_header_height + $this.position().top + parseInt($this.css( "border-top" ),10); var fromTop; if($this.css( "border-top" )){ fromTop = $this.position().top + parseInt($this.css( "border-top" ), 10); } else{ fromTop = $this.position().top; } if($body.data('menu') !== 'vertical-compact-menu'){ menuTitle.appendTo('.main-menu-content').css({ position:'fixed', top : fromTop, }); } // Content if($this.hasClass('has-sub') && $this.hasClass('nav-item')) { var menuContent = $this.children('ul:first'); menuObj.adjustSubmenu($this); } } $this.addClass('hover'); }).on('mouseleave.app.menu', 'li', function() { // $(this).removeClass('hover'); }).on('active.app.menu', 'li', function(e) { $(this).addClass('active'); e.stopPropagation(); }).on('deactive.app.menu', 'li.active', function(e) { $(this).removeClass('active'); e.stopPropagation(); }).on('open.app.menu', 'li', function(e) { var $listItem = $(this); $listItem.addClass('open'); menuObj.expand($listItem); // If menu collapsible then do not take any action if ($('.main-menu').hasClass('menu-collapsible')) { return false; } // If menu accordion then close all except clicked once else{ $listItem.siblings('.open').find('li.open').trigger('close.app.menu'); $listItem.siblings('.open').trigger('close.app.menu'); } e.stopPropagation(); }).on('close.app.menu', 'li.open', function(e) { var $listItem = $(this); $listItem.removeClass('open'); menuObj.collapse($listItem); e.stopPropagation(); }).on('click.app.menu', 'li', function(e) { var $listItem = $(this); if($listItem.is('.disabled')){ e.preventDefault(); } else{ if( ($body.hasClass('menu-collapsed') && $body.data('menu') != 'vertical-menu-modern') || ($body.data('menu') == 'vertical-compact-menu' && $listItem.is('.has-sub') && !$body.hasClass('vertical-overlay-menu'))){ e.preventDefault(); } else{ if ($listItem.has('ul')) { if ($listItem.is('.open')) { $listItem.trigger('close.app.menu'); } else { $listItem.trigger('open.app.menu'); } } else { if (!$listItem.is('.active')) { $listItem.siblings('.active').trigger('deactive.app.menu'); $listItem.trigger('active.app.menu'); } } } } e.stopPropagation(); }); $('.navbar-header, .main-menu').on('mouseenter',modernMenuExpand).on('mouseleave',modernMenuCollapse); function modernMenuExpand(){ if( $body.data('menu') == 'vertical-menu-modern'){ $('.main-menu, .navbar-header').addClass('expanded'); if($body.hasClass('menu-collapsed')){ var $listItem = $('.main-menu li.menu-collapsed-open'), $subList = $listItem.children('ul'); $subList.hide().slideDown(200, function() { $(this).css('display', ''); }); $listItem.addClass('open').removeClass('menu-collapsed-open'); // $.app.menu.changeLogo('expand'); } } } function modernMenuCollapse(){ if($body.hasClass('menu-collapsed') && $body.data('menu') == 'vertical-menu-modern'){ setTimeout(function(){ if($('.main-menu:hover').length === 0 && $('.navbar-header:hover').length === 0){ $('.main-menu, .navbar-header').removeClass('expanded'); if($body.hasClass('menu-collapsed')){ var $listItem = $('.main-menu li.open'), $subList = $listItem.children('ul'); $listItem.addClass('menu-collapsed-open'); $subList.show().slideUp(200, function() { $(this).css('display', ''); }); $listItem.removeClass('open'); // $.app.menu.changeLogo(); } } },1); } } $('.main-menu-content').on('mouseleave', function(){ if( $body.hasClass('menu-collapsed') || $body.data('menu') == 'vertical-compact-menu' ){ $('.main-menu-content').children('span.menu-title').remove(); $('.main-menu-content').children('a.menu-title').remove(); $('.main-menu-content').children('ul.menu-content').remove(); } $('.hover', '.navigation-main').removeClass('hover'); }); // If list item has sub menu items then prevent redirection. $('.navigation-main li.has-sub > a').on('click',function(e){ e.preventDefault(); }); $('ul.menu-content').on('click', 'li', function(e) { var $listItem = $(this); if($listItem.is('.disabled')){ e.preventDefault(); } else{ if ($listItem.has('ul')) { if ($listItem.is('.open')) { $listItem.removeClass('open'); menuObj.collapse($listItem); } else { $listItem.addClass('open'); menuObj.expand($listItem); // If menu collapsible then do not take any action if ($('.main-menu').hasClass('menu-collapsible')) { return false; } // If menu accordion then close all except clicked once else{ $listItem.siblings('.open').find('li.open').trigger('close.app.menu'); $listItem.siblings('.open').trigger('close.app.menu'); } e.stopPropagation(); } } else { if (!$listItem.is('.active')) { $listItem.siblings('.active').trigger('deactive.app.menu'); $listItem.trigger('active.app.menu'); } } } e.stopPropagation(); }); }, /** * Ensure an admin submenu is within the visual viewport. * @param {jQuery} $menuItem The parent menu item containing the submenu. */ adjustSubmenu: function ( $menuItem ) { var menuHeaderHeight, menutop, topPos, winHeight, bottomOffset, subMenuHeight, popOutMenuHeight, borderWidth, scroll_theme, $submenu = $menuItem.children('ul:first'), ul = $submenu.clone(true); menuHeaderHeight = $('.main-menu-header').height(); menutop = $menuItem.position().top; winHeight = $window.height(); borderWidth = 0; subMenuHeight = $submenu.height(); if(parseInt($menuItem.css( "border-top" ),10) > 0){ borderWidth = parseInt($menuItem.css( "border-top" ),10); } popOutMenuHeight = winHeight - menutop - $menuItem.height() - 30; scroll_theme = ($('.main-menu').hasClass('menu-dark')) ? 'light' : 'dark'; if($body.data('menu') === 'vertical-compact-menu'){ topPos = menutop + borderWidth; popOutMenuHeight = winHeight - menutop - 30; } else if($body.data('menu') === 'vertical-content-menu'){ topPos = menutop + $menuItem.height() + borderWidth; popOutMenuHeight = winHeight - $('.content-header').height() -$menuItem.height() - menutop - 60; } else{ topPos = menutop + $menuItem.height() + borderWidth; } if($body.data('menu') == 'vertical-content-menu'){ ul.addClass('menu-popout').appendTo('.main-menu-content').css({ 'top' : topPos, 'position' : 'fixed', }); } else{ ul.addClass('menu-popout').appendTo('.main-menu-content').css({ 'top' : topPos, 'position' : 'fixed', 'max-height': popOutMenuHeight, }); $('.main-menu-content > ul.menu-content').perfectScrollbar({ theme:scroll_theme, }); } }, collapse: function($listItem, callback) { var $subList = $listItem.children('ul'); $subList.show().slideUp($.app.nav.config.speed, function() { $(this).css('display', ''); $(this).find('> li').removeClass('is-shown'); if (callback) { callback(); } $.app.nav.container.trigger('collapsed.app.menu'); }); }, expand: function($listItem, callback) { var $subList = $listItem.children('ul'); var $children = $subList.children('li').addClass('is-hidden'); $subList.hide().slideDown($.app.nav.config.speed, function() { $(this).css('display', ''); if (callback) { callback(); } $.app.nav.container.trigger('expanded.app.menu'); }); setTimeout(function() { $children.addClass('is-shown'); $children.removeClass('is-hidden'); }, 0); }, refresh: function() { $.app.nav.container.find('.open').removeClass('open'); }, }; })(window, document, jQuery); } $ctrl.app = function(){ var menuObj = this; var $body = $('body'); var windowEl = angular.element($window); menuObj.expand = function() { if (this.expanded === false) { if( $body.data('menu') == 'vertical-menu-modern' ){ $('.modern-nav-toggle').find('.toggle-icon') .removeClass('ft-toggle-left').addClass('ft-toggle-right'); // Code for localStorage if (typeof(Storage) !== "undefined") { localStorage.setItem("menuLocked", "true"); } } /*if( $body.data('menu') == 'vertical-menu' || $body.data('menu') == 'vertical-menu-modern'){ this.changeLogo('expand'); }*/ this.transit(function() { $body.removeClass('menu-collapsed').addClass('menu-expanded'); this.collapsed = false; this.expanded = true; }); } }, menuObj.collapse = function(defMenu) { if (this.collapsed === false) { if( $body.data('menu') == 'vertical-menu-modern' ){ $('.modern-nav-toggle').find('.toggle-icon') .removeClass('ft-toggle-right').addClass('ft-toggle-left'); // Code for localStorage if (typeof(Storage) !== "undefined") { localStorage.setItem("menuLocked", "false"); } } this.transit(function() { $body.removeClass('menu-expanded').addClass('menu-collapsed'); this.collapsed = true; this.expanded = false; }); } }, menuObj.adjustSubmenu = function( $menuItem ) { var menuHeaderHeight, menutop, topPos, winHeight, bottomOffset, subMenuHeight, popOutMenuHeight, borderWidth, scroll_theme, $submenu = $menuItem.children('ul:first'), ul = $submenu.clone(true); menuHeaderHeight = $('.main-menu-header').height(); menutop = $menuItem.position().top; winHeight = windowEl.height(); borderWidth = 0; subMenuHeight = $submenu.height(); if(parseInt($menuItem.css( "border-top" ),10) > 0){ borderWidth = parseInt($menuItem.css( "border-top" ),10); } popOutMenuHeight = winHeight - menutop - $menuItem.height() - 30; scroll_theme = ($('.main-menu').hasClass('menu-dark')) ? 'light' : 'dark'; if($body.data('menu') === 'vertical-compact-menu'){ topPos = menutop + borderWidth; popOutMenuHeight = winHeight - menutop - 30; } else if($body.data('menu') === 'vertical-content-menu'){ topPos = menutop + $menuItem.height() + borderWidth; popOutMenuHeight = winHeight - $('.content-header').height() -$menuItem.height() - menutop - 60; } else{ topPos = menutop + $menuItem.height() + borderWidth; } if($body.data('menu') == 'vertical-content-menu'){ ul.addClass('menu-popout').appendTo('.main-menu-content').css({ 'top' : topPos, 'position' : 'fixed', }); } else{ ul.addClass('menu-popout').appendTo('.main-menu-content').css({ 'top' : topPos, 'position' : 'fixed', 'max-height': popOutMenuHeight, }); $('.main-menu-content > ul.menu-content').perfectScrollbar({ theme:scroll_theme, }); } } $('.navigation-main').on('mouseenter.app.menu', 'li', function() { var $this = $(this); $('.hover', '.navigation-main').removeClass('hover'); if( ($body.hasClass('menu-collapsed') && $body.data('menu') != 'vertical-menu-modern') || ($body.data('menu') == 'vertical-compact-menu' && !$body.hasClass('vertical-overlay-menu')) ){ $('.main-menu-content').children('span.menu-title').remove(); $('.main-menu-content').children('a.menu-title').remove(); $('.main-menu-content').children('ul.menu-content').remove(); // Title var menuTitle = $this.find('span.menu-title').clone(), tempTitle, tempLink; if(!$this.hasClass('has-sub') ){ tempTitle = $this.find('span.menu-title').text(); tempLink = $this.children('a').attr('href'); if(tempTitle !== ''){ menuTitle = $("<a>"); menuTitle.attr("href", tempLink); menuTitle.attr("title", tempTitle); menuTitle.text(tempTitle); menuTitle.addClass("menu-title"); } } // menu_header_height = ($('.main-menu-header').length) ? $('.main-menu-header').height() : 0, // fromTop = menu_header_height + $this.position().top + parseInt($this.css( "border-top" ),10); var fromTop; if($this.css( "border-top" )){ fromTop = $this.position().top + parseInt($this.css( "border-top" ), 10); } else{ fromTop = $this.position().top; } if($body.data('menu') !== 'vertical-compact-menu'){ menuTitle.appendTo('.main-menu-content').css({ position:'fixed', top : fromTop, }); } // Content if($this.hasClass('has-sub') && $this.hasClass('nav-item')) { var menuContent = $this.children('ul:first'); menuObj.adjustSubmenu($this); } } $this.addClass('hover'); }).on('mouseleave.app.menu', 'li', function() { // $(this).removeClass('hover'); }).on('active.app.menu', 'li', function(e) { $(this).addClass('active'); e.stopPropagation(); }).on('deactive.app.menu', 'li.active', function(e) { $(this).removeClass('active'); e.stopPropagation(); }).on('open.app.menu', 'li', function(e) { var $listItem = $(this); $listItem.addClass('open'); menuObj.expand($listItem); // If menu collapsible then do not take any action if ($('.main-menu').hasClass('menu-collapsible')) { return false; } // If menu accordion then close all except clicked once else{ $listItem.siblings('.open').find('li.open').trigger('close.app.menu'); $listItem.siblings('.open').trigger('close.app.menu'); } e.stopPropagation(); }).on('close.app.menu', 'li.open', function(e) { var $listItem = $(this); $listItem.removeClass('open'); menuObj.collapse($listItem); e.stopPropagation(); }).on('click.app.menu', 'li', function(e) { var $listItem = $(this); if($listItem.is('.disabled')){ e.preventDefault(); } else{ if( ($body.hasClass('menu-collapsed') && $body.data('menu') != 'vertical-menu-modern') || ($body.data('menu') == 'vertical-compact-menu' && $listItem.is('.has-sub') && !$body.hasClass('vertical-overlay-menu'))){ e.preventDefault(); } else{ if ($listItem.has('ul')) { if ($listItem.is('.open')) { $listItem.trigger('close.app.menu'); } else { $listItem.trigger('open.app.menu'); } } else { if (!$listItem.is('.active')) { $listItem.siblings('.active').trigger('deactive.app.menu'); $listItem.trigger('active.app.menu'); } } } } e.stopPropagation(); }); $('.navbar-header, .main-menu').on('mouseenter',modernMenuExpand).on('mouseleave',modernMenuCollapse); function modernMenuExpand(){ if( $body.data('menu') == 'vertical-menu-modern'){ $('.main-menu, .navbar-header').addClass('expanded'); if($body.hasClass('menu-collapsed')){ var $listItem = $('.main-menu li.menu-collapsed-open'), $subList = $listItem.children('ul'); $subList.hide().slideDown(200, function() { $(this).css('display', ''); }); $listItem.addClass('open').removeClass('menu-collapsed-open'); // $.app.menu.changeLogo('expand'); } } } function modernMenuCollapse(){ if($body.hasClass('menu-collapsed') && $body.data('menu') == 'vertical-menu-modern'){ setTimeout(function(){ if($('.main-menu:hover').length === 0 && $('.navbar-header:hover').length === 0){ $('.main-menu, .navbar-header').removeClass('expanded'); if($body.hasClass('menu-collapsed')){ var $listItem = $('.main-menu li.open'), $subList = $listItem.children('ul'); $listItem.addClass('menu-collapsed-open'); $subList.show().slideUp(200, function() { $(this).css('display', ''); }); $listItem.removeClass('open'); // $.app.menu.changeLogo(); } } },1); } } $('.main-menu-content').on('mouseleave', function(){ if( $body.hasClass('menu-collapsed') || $body.data('menu') == 'vertical-compact-menu' ){ $('.main-menu-content').children('span.menu-title').remove(); $('.main-menu-content').children('a.menu-title').remove(); $('.main-menu-content').children('ul.menu-content').remove(); } $('.hover', '.navigation-main').removeClass('hover'); }); // If list item has sub menu items then prevent redirection. $('.navigation-main li.has-sub > a').on('click',function(e){ e.preventDefault(); }); $('ul.menu-content').on('click', 'li', function(e) { var $listItem = $(this); if($listItem.is('.disabled')){ e.preventDefault(); } else{ if ($listItem.has('ul')) { if ($listItem.is('.open')) { $listItem.removeClass('open'); menuObj.collapse($listItem); } else { $listItem.addClass('open'); menuObj.expand($listItem); // If menu collapsible then do not take any action if ($('.main-menu').hasClass('menu-collapsible')) { return false; } // If menu accordion then close all except clicked once else{ $listItem.siblings('.open').find('li.open').trigger('close.app.menu'); $listItem.siblings('.open').trigger('close.app.menu'); } e.stopPropagation(); } } else { if (!$listItem.is('.active')) { $listItem.siblings('.active').trigger('deactive.app.menu'); $listItem.trigger('active.app.menu'); } } } e.stopPropagation(); }); }; $scope.$on('$viewContentLoaded', function(event){ $timeout(function() { $ctrl.geragrafico(); $ctrl.geragrafico1(); $ctrl.app(); }, 500); }); }})(); <file_sep>/src/js/OLD/angular-datatables.options.js 'use strict'; angular.module('datatables.options', []) .constant('DT_DEFAULT_OPTIONS', { // Default ajax properties. See http://legacy.datatables.net/usage/options#sAjaxDataProp sAjaxDataProp: '', // Set default columns (used when none are provided) aoColumns: [] }) .constant('DT_LOADING_CLASS', 'dt-loading') .service('DTDefaultOptions', dtDefaultOptions); function dtDefaultOptions() { var options = { loadingTemplate: '<h3>Loading...</h3>', bootstrapOptions: {}, setLoadingTemplate: setLoadingTemplate, setLanguageSource: setLanguageSource, setLanguage: setLanguage, setDisplayLength: setDisplayLength, setBootstrapOptions: setBootstrapOptions, setDOM: setDOM, setOption: setOption }; return options; /** * Set the default loading template * @param loadingTemplate the HTML to display when loading the table * @returns {DTDefaultOptions} the default option config */ function setLoadingTemplate(loadingTemplate) { options.loadingTemplate = loadingTemplate; return options; } /** * Set the default language source for all datatables * @param sLanguageSource the language source * @returns {DTDefaultOptions} the default option config */ function setLanguageSource(sLanguageSource) { // HACK to resolve the language source manually instead of DT // See https://github.com/l-lin/angular-datatables/issues/356 $.ajax({ dataType: 'json', url: sLanguageSource, success: function(json) { $.extend(true, $.fn.DataTable.defaults, { language: json }); } }); return options; } /** * Set the language for all datatables * @param language the language * @returns {DTDefaultOptions} the default option config */ function setLanguage(language) { $.extend(true, $.fn.DataTable.defaults, { language: language }); return options; } /** * Set the default number of items to display for all datatables * @param displayLength the number of items to display * @returns {DTDefaultOptions} the default option config */ function setDisplayLength(displayLength) { $.extend($.fn.DataTable.defaults, { displayLength: displayLength }); return options; } /** * Set the default options to be use for Bootstrap integration. * See https://github.com/l-lin/angular-datatables/blob/dev/src/angular-datatables.bootstrap.options.js to check * what default options Angular DataTables is using. * @param oBootstrapOptions an object containing the default options for Bootstrap integration * @returns {DTDefaultOptions} the default option config */ function setBootstrapOptions(oBootstrapOptions) { options.bootstrapOptions = oBootstrapOptions; return options; } /** * Set the DOM for all DataTables. * See https://datatables.net/reference/option/dom * @param dom the dom * @returns {DTDefaultoptions} the default option config */ function setDOM(dom) { $.extend($.fn.DataTable.defaults, { dom: dom }); return options; } /** * Set global default option to all DataTables. * @param key the key of the default option * @param value the value of the default option */ function setOption(key, value) { if (angular.isString(key)) { var obj = {}; obj[key] = value; $.extend($.fn.DataTable.defaults, obj); } } } <file_sep>/src/js/directives/chartistAngularDirective.js angular .module('chartistAngularDirective', []) .directive('ngChartist', ngChartist); ngChartist.$inject = ['$compile','$timeout']; function ngChartist($compile, $timeout) { return { scope: { data: '=', options: '@', responsiveOptions: '@', type: '@', id: '@', animate: '@' }, link: link, restrict: 'EA' }; function link(scope) { //var options=JSON.stringify(scope.options); var graph = Chartist[scope.type]('#' + scope.id, scope.data, scope.options, scope.responsiveOptions); // set watcher for future data updates scope.$watch('data', function(newValue, oldValue) { if(newValue === oldValue) { return; } graph.update(scope.data, options, true); graph.on('draw', function (data) { if (data.type === 'Bar') { data.element.attr({ style: 'stroke-width: 25px', y1: 250, x1: data.x1 + 0.001 }); data.group.append(new Chartist.Svg('circle', { cx: data.x2, cy: data.y2, r: 12 }, 'ct-slice-pie')); } });// end chart.on draw graph.on('created', function(data) { var defs = data.svg.querySelector('defs') || data.svg.elem('defs'); defs.elem('linearGradient', { id: 'barGradient3', x1: 0, y1: 0, x2: 0, y2: 1 }).elem('stop', { offset: 0, 'stop-color': 'rgb(28, 120, 255)' }).parent().elem('stop', { offset: 1, 'stop-color': 'rgb(41, 188, 253)' }); return defs; }); }, true);// end watch data // set watcher for future options update scope.$watch('options', function(newValue, oldValue) { if(newValue === oldValue) { return; } graph.update(scope.options, true); }, true); } }<file_sep>/src/js/OLD/21_app-lotter.js (function () { 'use strict'; var emmefxApp = angular.module('emmefxApp', ['ui.router','ApiConnect','angular.css.injector','ultimateDataTableServices','oc.lazyLoad','chartistAngularDirective','menuToogle','ngStorage','ngResource','toastr']); emmefxApp.config(function ($stateProvider, $urlRouterProvider, $httpProvider , $ocLazyLoadProvider ) { $urlRouterProvider.otherwise('/login'); $stateProvider .state('login', { url: '/login', templateUrl: 'views/account-login.html', controller: 'loginctrl' }) .state('monitor', { url: '/monitor', templateUrl: 'views/monitor.html', controller: 'monitorCtrl' }) .state('home', { url: '/home', templateUrl: 'views/dashboard-ico.html', controller: 'homectrl' }) .state('users', { url: '/users', templateUrl: 'views/users.html', controller: 'usersctrl' }) .state('newuser', { url: '/newuser', templateUrl: 'views/newuser.html', controller: 'newuserctrl' }) .state('edituser', { url: '/edituser/:id', templateUrl: 'views/edituser.html', controller: 'edituserctrl' }) .state('accounts', { url: '/accounts', templateUrl: 'views/accounts.html', controller: 'accountsctrl' }) .state('clients', { url: '/clients', templateUrl: 'views/clients.html', controller: 'clientsctrl' }) .state('wallet', { url: '/wallet', templateUrl: 'views/wallet.html', controller: 'walletctrl' }) .state('transactions', { url: '/transactions', templateUrl: 'views/transactions.html', controller: 'transactionsctrl' }) .state('buy', { url: '/buy', templateUrl: 'views/buy-ico.html', controller: 'buyctrl' }) .state('details', { url: '/details', templateUrl: 'views/buy-details.html', controller: 'detailsctrl' }) .state('pool', { url: '/pool', templateUrl: 'views/pool.html', controller: 'poolctrl' }) }); emmefxApp.config(['$qProvider', function($qProvider){ $qProvider.errorOnUnhandledRejections(false); }]); emmefxApp.config(['$resourceProvider', function($resourceProvider) { // Don't strip trailing slashes from calculated URLs $resourceProvider.defaults.stripTrailingSlashes = true; }]); emmefxApp.run(['$rootScope', function ($rootScope) { }]); })(); <file_sep>/src/js/plugins/ultimate-datatable-3.4.0-SNAPSHOT.js /*! ultimate-datatable version 3.4.0-SNAPSHOT 2018-09-19 Ultimate DataTable is distributed open-source under CeCILL FREE SOFTWARE LICENSE. Check out http://www.cecill.info/ for more information about the contents of this license. */ "use strict"; angular.module('ultimateDataTableServices', []). factory('datatable', ['$http', '$filter', '$parse', '$window', '$q', 'udtI18n', '$timeout', '$anchorScroll', '$location', function($http, $filter, $parse, $window, $q, udtI18n, $timeout, $anchorScroll, $location) { //service to manage datatable var constructor = function(iConfig) { var datatable = { configDefault: { name: "datatable", extraHeaders: { number: 0, // Number of extra headers list: {}, //if dynamic=false dynamic: true //if dynamic=true, the headers will be auto generated }, //ex: extraHeaders:{number:2,dynamic:false,list:{0:[{"label":"test","colspan":"1"},{"label":"a","colspan":"1"}],1:[{"label":"test2","colspan":"5"}]}} columns: [], /*ex : { "header":"Code Container", //the title //used by default Messages "headerTpl":"", //html template to custom render "property":"code", //the property to bind or function used to extract the value "filter":"", angular filter to filter the value only used in read mode "render" : function() //render the column used to add style around value "editDirectives":""//Add directives to the edit element "id":'', //the column id "edit":false, //can be edited or not "convertValue":{ active:false, //True if the value have to be converted when displayed to the user displayMeasureValue:"",//The unit display to the user, mandatory if active=true saveMeasureValue:"" //The unit in database, mandatory if active=true }, "hide":true, //can be hidden or not "order":true, //can be ordered or not "type":"text"/"number"/"month"/"week"/"time"/"datetime"/"range"/"color"/"mail"/"tel"/"date", //the column type "choiceInList":false, //when the column is in edit mode, the edition is a list of choices or not "listStyle":"select"/"radio", //if choiceInList=true, listStyle="select" is a select input, listStyle="radio" is a radio input "possibleValues":null, //The list of possible choices "format" : null, //number format or date format or datetime format "extraHeaders":{"0":"Inputs"}, //the extraHeaders list "tdClass" : function with data and property as parameter than return css class or just the css class", "thClass" : function with data and property as parameter than return css class or just the css class", "position": position of the column, "group": false //if column can be used to group data "groupMethod": sum, average, countDistinct, collect "defaultValues":"" //If the value of the column is undefined or "" when the user edit, this value show up "url"://to lazy data "mergeCells":false //to enable merge cell on this column "required":true/false //to add * on column header if required " }*/ columnsUrl: undefined, //Load columns config lines: { trClass: undefined // function with data than return css class or just the css class }, search: { active: false, mode: 'remote', url: undefined }, localSearch: { active: false, highlight: true, columnMode: false, showButton: false }, pagination: { active: true, mode: 'remote', pageNumber: 0, numberPageListMax: 3, pageList: [], numberRecordsPerPage: 100, numberRecordsPerPageList: undefined, bottom:true, numberRecordsPerPageForBottomdisplay:50 }, order: { active: true, showButton: true, mode: 'remote', //or local by: undefined, reverse: false, callback: undefined, //used to have a callback after order all element. the datatable is pass to callback method and number of error columns: {} //key is the column index }, add: { active: false, showButton: false, init: function() { return {}; }, after: true }, show: { active: false, showButton: false, add: function(line) { console.log("show : add function is not defined in the controller !!!"); } }, hide: { active: true, showButton: true, byDefault:undefined, //Array with column property columns: {} //columnIndex : true / false }, edit: { active: false, withoutSelect: false, //edit all line without selected it showButton: false, showLineButton: false, // Show the edit button left of each line columnMode: false, byDefault: false, //put in edit mode when the datatable is build start: false, all: false, columns: {}, //columnIndex : {edit : true/false, value:undefined} lineMode: undefined //function used to define if line is editable. }, save: { active: false, withoutEdit: false, //usable only for active/inactive save button by default !!! keepEdit: false, //keep in edit mode after safe showButton: false, changeClass: true, //change class to success or error mode: 'remote', //or local url: undefined, //mode remote only url or function that takes the value batch: false, //for batch mode one url with all data. //mode remote only method: 'post', //mode remote only or funtion with value as parameter in batch mode an array value: undefined, //used to transform the value send to the server //mode remote only callback: undefined, //used to have a callback after save all element. the datatable is pass to callback method and number of error beforeSave: undefined, //function that will be return a promise that will be executed before save (remote or local). useful to chain two url. start: false, //if save started number: 0, //number of element in progress error: 0, newData: [], enableValidation:false }, remove: { active: false, withEdit: false, //to authorize to remove a line in edition mode showButton: false, mode: 'remote', //or local url: undefined, //function with object in parameter !!! callback: undefined, //used to have a callback after remove all element. the datatable is pass to callback method and number of error start: false, counter: 0, number: 0, //number of element in progress error: 0, ids: { errors: [], success: [] } }, select: { active: false, showButton: false, isSelectAll: false, callback: undefined // DEPRECATED in favor of mouseevents.clickCallback. }, mouseevents: { active: false, overCallback: undefined, // used to have a callback when the user passes the mouse over a row. leaveCallback: undefined, // used to have a callback when the mouse of the user leaves a row. clickCallback: undefined // used to have a callback when the user clicks on a row. }, cancel: { active: false, showButton: false }, exportCSV: { active: false, showButton: false, delimiter: ";", start: false }, otherButtons: { active: false, complex : false, //used to inject several buttons in toolbars. template: undefined }, messages: { active: false, errorClass: 'alert alert-danger', successClass: 'alert alert-success', errorKey: { save: 'datatable.msg.error.save', remove: 'datatable.msg.error.remove' }, successKey: { save: 'datatable.msg.success.save', remove: 'datatable.msg.success.remove' }, text: undefined, clazz: undefined, messagesService: udtI18n(navigator.languages || navigator.language || navigator.userLanguage), transformKey: function(key, args) { return this.messagesService.Messages(key, args); } }, group: { active: false, //group add group=true in each line of type group callback: undefined, by: undefined, showButton: true, after: true, //to position group line before or after lines showOnlyGroups: false, //to display only group line in datatable start: false, enableLineSelection: false, //used to authorized selection on group line columns: {} }, mergeCells: { active: false, rowspans: undefined }, showTotalNumberRecords: true, spinner: { start: false }, callbackEndDisplayResult : function(){}, compact: true, //mode compact pour le nom des bouttons objectsMustBeAddInGetFinalValue:{} //object used in $parse to apply function on extract value. }, config: undefined, configMaster: undefined, allResult: undefined, allGroupResult: undefined, displayResult: undefined, totalNumberRecords: 0, computeDisplayResultTimeOut: undefined, urlCache: {}, //used to cache data load from column with url attribut lastSearchParams: undefined, //used with pagination when length or page change inc: 0, //used for unique column ids configColumnDefault: { edit: false, //can be edited or not hide: true, //can be hidden or not order: true, //can be ordered or not type: "text", //the column type choiceInList: false, //when the column is in edit mode, the edition is a list of choices or not extraHeaders: {}, convertValue: { active: false } }, messages: udtI18n(navigator.languages || navigator.language || navigator.userLanguage), //i18n intern service instance //errors functions /** * Reset all the errors for a line */ resetErrors: function(index) { this.displayResult[index].line.errors = {}; }, /** * Add error data in the line index for the field key */ addErrorsForKey: function(index, data, key) { if (this.displayResult[index].line.errors === undefined) { this.displayResult[index].line.errors = {}; } this.displayResult[index].line.errors[key] = ""; for (var i = 0; angular.isArray(data[key]) && i < data[key].length; i++) { this.displayResult[index].line.errors[key] += data[key][i] + " "; } }, /** * Add errors data in the line index in the key of the data key error */ addErrors: function(index, data) { for (var key in data) { this.addErrorsForKey(index, data, key); } }, /** * External search reinit pageNumber to 0 */ search: function(params) { this.config.edit = angular.copy(this.configMaster.edit); this.config.remove = angular.copy(this.configMaster.remove); this.config.select = angular.copy(this.configMaster.select); this.config.messages = angular.copy(this.configMaster.messages); this.config.pagination.pageNumber = 0; this._search(angular.copy(params)); }, /** * local search */ localSearch : function(searchTerms) { if (this.config.localSearch.active === true) { //Set the properties "" or null to undefined because we don't want to filter this this.setSpinner(true); for (var p in searchTerms) { if (searchTerms[p] != undefined && (searchTerms[p] === undefined || searchTerms[p] === null || searchTerms[p] === "")) { searchTerms[p] = undefined; } } if(this.backupAllResult === undefined){ this.backupAllResult = angular.copy(this.allResult); }else{ this.allResult = angular.copy(this.backupAllResult); } this.allResult = $filter('filter')(this.allResult, searchTerms, false); this.totalNumberRecords = this.allResult.length; this.sortAllResult(); this.computePaginationList(); this.computeDisplayResult(); var that = this; this.computeDisplayResultTimeOut.then(function() { that.setSpinner(false); }); } }, resetLocalSearch : function(){ this.searchTerms = {}; if(this.backupAllResult !== undefined){ this.allResult = angular.copy(this.backupAllResult); this.totalNumberRecords = this.allResult.length; this.sortAllResult(); this.computePaginationList(); this.computeDisplayResult(); var that = this; this.computeDisplayResultTimeOut.then(function() { that.setSpinner(false); }); } }, _getAllResult: function() { return this.allResult; }, //search functions /** * Internal Search function to populate the datatable */ _search: function(params) { if (this.config.search.active && this.isRemoteMode(this.config.search.mode)) { this.lastSearchParams = params; var url = this.getUrlFunction(this.config.search.url); if (url) { this.setSpinner(true); var that = this; $http.get(url(), { params: this.getParams(params), datatable: this }).then(function(resp) { if(angular.isArray(resp.data)){ resp.config.datatable._setData(resp.data, resp.data.length); }else{ resp.config.datatable._setData(resp.data.data, resp.data.recordsNumber); } that.computeDisplayResultTimeOut.then(function() { that.setSpinner(false); }); }); } else { throw 'no url define for search ! '; } } else { //console.log("search is not active !!") } }, /** * Search with the last parameters */ searchWithLastParams: function() { this._search(this.lastSearchParams); }, /** * Set all data used by search method or directly when local data */ setData: function(data, recordsNumber) { this.config.edit = angular.copy(this.configMaster.edit); this.config.remove = angular.copy(this.configMaster.remove); this.config.select = angular.copy(this.configMaster.select); this.config.messages = angular.copy(this.configMaster.messages); this.config.pagination.pageNumber = 0; this._setData(data, recordsNumber); }, _setData: function(data, recordsNumber) { var configPagination = this.config.pagination; if (configPagination.active && !this.isRemoteMode(configPagination.mode)) { this.config.pagination.pageNumber = 0; } if (recordsNumber === undefined && data !== null & data !== undefined) recordsNumber = data.length; this.allResult = data; this.totalNumberRecords = recordsNumber; this.loadUrlColumnProperty(); this.computeGroup(); this.sortAllResult(); this.computePaginationList(); this.computeDisplayResult(); this._getAllResult = function() { return this.allResult; }; }, /** * Return if data */ isData: function() { return (this.allResult !== null && this.allResult !== undefined && this.allResult.length > 0) ; }, /** * Return all the data */ getData: function() { return this.allResult; }, /** * Add data */ addData: function(data) { if (!angular.isUndefined(data) && (angular.isArray(data) && data.length > 0)) { var configPagination = this.config.pagination; if (configPagination.active && !this.isRemoteMode(configPagination.mode)) { this.config.pagination.pageNumber = 0; } for (var i = 0; i < data.length; i++) { this.allResult.push(data[i]); } this.totalNumberRecords = this.allResult.length; this.loadUrlColumnProperty(); this.computeGroup(); this.sortAllResult(); this.computePaginationList(); this.computeDisplayResult(); this._getAllResult = function() { return this.allResult; }; } }, /** * Add new line in edit mode */ addBlankLine: function() { if (this.config.add.active === true) { //call inti method for the new data var newData = this.config.add.init(this); var line = { "edit": true, "selected": false, "trClass": undefined, "group": false, "new": true }; if (this.config.add.after) { this.displayResult.push({ data: newData, line: line }); } else { this.displayResult.unshift({ data: newData, line: line }); } this.config.edit.all = true; this.config.edit.start = true; } }, /** * compute the group */ computeGroup: function() { if (this.config.group.active && this.config.group.by) { var propertyGroupGetter = this.config.group.by.property; var propertyGroupGetterWithoutFormat = propertyGroupGetter + this.getFilter(this.config.group.by); var propertyGroupGetterWithFormat = propertyGroupGetterWithoutFormat + this.getFormatter(this.config.group.by); var groupContext = {"col":this.config.group.by}; groupContext = Object.assign(groupContext, this.config.objectsMustBeAddInGetFinalValue); if(this.config.group.by=="all"){ propertyGroupGetterWithFormat="all"; } var groupGetter = $parse(propertyGroupGetterWithFormat); var groupValues = this.allResult.reduce(function(array, value) { var groupValue = "all"; if(propertyGroupGetterWithFormat !== "all"){ groupValue = groupGetter(value,groupContext); if(groupValue !== null && groupValue !== undefined){ groupValue = groupValue.toString(); }else{ groupValue = ""; } } if (!array[groupValue]) { array[groupValue] = []; } array[groupValue].push(value); return array; }, {}); var groups = {}; this.allGroupResult = []; for (var key in groupValues) { var group = {}; var groupData = groupValues[key]; var keyFirstElementValue = $parse(propertyGroupGetterWithoutFormat)(groupData[0],groupContext); var that = this; $parse("group." + this.config.group.by.id).assign(group, keyFirstElementValue); var groupMethodColumns = this.getColumnsConfig().filter(function(column) { return (column.groupMethod !== undefined && column.groupMethod !== null && column.property+that.getFilter(column) != propertyGroupGetterWithoutFormat); }); //compute for each number column the sum groupMethodColumns.forEach(function(column) { if(column.id != that.config.group.by.id){ var propertyGetter = column.property; var propertyGetterWithoutFormat = propertyGetter + that.getFilter(column); var columnGetterWithoutFomat = $parse(propertyGetterWithoutFormat); var propertyGetterWithFormat = propertyGetterWithoutFormat + that.getFormatter(column); var columnGetterWithFomat = $parse(propertyGetterWithFormat); //var columnGetter = $parse(propertyGetter); var columnSetter = $parse("group." + column.id); var context = {"col":column}; context = Object.assign(context, this.config.objectsMustBeAddInGetFinalValue); if ('sum' === column.groupMethod || 'average' === column.groupMethod) { var result = groupData.reduce(function(value, element) { element.col = column; //add in experimental feature var num = columnGetterWithoutFomat(element, context); value += (num !== undefined)?num:0; element.col = undefined; return value; }, 0); if ('average' === column.groupMethod) result = result / groupData.length; if (isNaN(result)) { result = "#ERROR"; } try { columnSetter.assign(group, result); } catch (e) { console.log("computeGroup Error : " + e); } } else if ('unique' === column.groupMethod) { var result = $filter('udtUnique')(groupData, propertyGetterWithFormat, context); if (!angular.isArray(result)) { result = columnGetterWithoutFomat(result); } else if (angular.isArray(result) && result.length > 1) { result = '#MULTI'; } else if (angular.isArray(result) && result.length === 1) { result = columnGetterWithoutFomat(result[0]); } else { result = undefined; } columnSetter.assign(group, result); } else if ('countDistinct' === column.groupMethod) { var result = $filter('udtCount')(groupData, propertyGetterWithFormat,true, context); columnSetter.assign(group, result); } else if (column.groupMethod.startsWith('count')) { var params = column.groupMethod.split(":"); var distinct = (params.length === 2 && params[1] === 'true')?true:false; var result = $filter('udtCount')(groupData, propertyGetterWithFormat,distinct, context); columnSetter.assign(group, result); } else if (column.groupMethod.startsWith('collect')) { var params = column.groupMethod.split(":"); var unique = (params.length === 2 && params[1] === 'true')?true:false; //collect all value but if unique this is apply on display value (after format) not on real value because for user a unique is a final result var result = $filter('udtCollect')(groupData, propertyGetterWithoutFormat, unique, "this"+that.getFormatter(column), context); //to optimize if collect as only one value so put directly the alone result if (angular.isArray(result) && result.length === 1) { result = result[0]; } columnSetter.assign(group, result); } else { console.error("groupMethod is not managed " + column.groupMethod); } } },this); groups[key] = group; this.allGroupResult.push(group); } this.config.group.data = groups; } else { this.config.group.data = undefined; this.allGroupResult = undefined; } }, getGroupColumnValue: function(groupValue, columnProperty) { for (var i = 0; i < this.config.columns.length; i++) { if (this.config.columns[i].property === columnProperty) { var column = this.config.columns[i]; var columnGetter = $parse("group." + column.id); return columnGetter(groupValue); } } console.log("column not found for property :" + columnProperty); return undefined; }, isGroupActive: function() { return (this.config.group.active && this.config.group.start); }, /** * set the order column name * @param orderColumnName : column name */ setGroupColumn: function(column) { if (this.config.group.active) { var columnId; column === 'all' ? columnId = 'all' : columnId = column.id; if(this.config.group.by === undefined || this.config.group.by.id !== column.id){ this.config.group.start = true; if (columnId === "all") { this.config.group.by = columnId; this.config.group.columns['all'] = true; } else { this.config.group.by = column; this.config.order.groupReverse = false; this.config.group.columns[columnId] = true; if (this.config.group.columns["all"]) this.config.group.columns["all"] = false; } for (var i = 0; i < this.config.columns.length; i++) { if (this.config.columns[i].id === columnId) { this.config.group.columns[this.config.columns[i].id] = true; } else { this.config.group.columns[this.config.columns[i].id] = false; } } } else { //degroupe this.config.group.columns[columnId] = !this.config.group.columns[columnId]; if (!this.config.group.columns[columnId] || this.config.group.columns["all"]) { this.config.group.by = undefined; this.config.group.columns["all"] = false; } this.config.group.start = false; } if (this.config.edit.active && this.config.edit.start) { //TODO add a warning popup console.log("edit is active, you lost all modification !!"); this.config.edit = angular.copy(this.configMaster.edit); //reinit edit } this.computeGroup(); this.sortAllResult(); //sort all the result this.computePaginationList(); //redefined pagination this.computeDisplayResult(); //redefined the result must be displayed var that = this; this.computeDisplayResultTimeOut.then(function() { if (angular.isFunction(that.config.group.callback)) { that.config.group.callback(this); } }); } else { //console.log("order is not active !!!"); } }, updateShowOnlyGroups: function() { this.sortAllResult(); //sort all the result this.computePaginationList(); //redefined pagination this.computeDisplayResult(); //redefined the result must be displayed }, getGroupColumnClass: function(columnId) { if (this.config.group.active) { if (!this.config.group.columns[columnId]) { return 'fa fa-bars'; } else { return 'fa fa-outdent'; } } else { //console.log("order is not active !!!"); } }, addGroup: function(displayResultTmp) { var displayResult = []; var propertyGroupGetter = this.config.group.by.property; propertyGroupGetter += this.getFilter(this.config.group.by); propertyGroupGetter += this.getFormatter(this.config.group.by); if(this.config.group.by=="all"){ propertyGroupGetter="all"; } var groupGetter = $parse(propertyGroupGetter); var getGroupValue = function(value){ var groupValue = groupGetter(value); if(groupValue !== null && groupValue !== undefined){ groupValue = groupValue.toString(); }else{ groupValue = ""; } return groupValue; }; var groupConfig = this.config.group; displayResultTmp.forEach(function(element, index, array) { /* previous mode */ if (!groupConfig.after && (index === 0 || (propertyGroupGetter!=="all" && getGroupValue(element.data).toString() !== getGroupValue(array[index - 1].data).toString()))) { var line = { edit: undefined, selected: undefined, trClass: undefined, group: true, "new": false }; this.push({ data: propertyGroupGetter!=="all" ? groupConfig.data[getGroupValue(element.data).toString()]:groupConfig.data["all"], line: line }); } this.push(element); /* after mode */ if (groupConfig.after && (index === (array.length - 1) || (propertyGroupGetter!=="all" && getGroupValue(element.data).toString() !== getGroupValue(array[index + 1].data).toString()))) { var line = { "edit": undefined, "selected": undefined, "trClass": undefined, "group": true, "new": false }; this.push({ data: propertyGroupGetter!=="all" ? groupConfig.data[getGroupValue(element.data).toString()]:groupConfig.data["all"], line: line }); }; }, displayResult); return displayResult; }, /** * compute for each <td> the row span if user whant to merge cell */ computeRowSpans: function() { if (this.config.mergeCells.active === true) { this.config.mergeCells.rowspans = undefined; //init rowspans values var rowspans = undefined; rowspans = new Array(this.displayResult.length); for (var i = 0; i < this.displayResult.length; i++) { rowspans[i] = new Array(this.config.columns.length); } var currentDisplayResult = this.displayResult; var currentColumns = this.config.columns; var previousResult = undefined; var nbRowEquals = new Array(this.config.columns.length); for (var j = 0; j < nbRowEquals.length; j++) { nbRowEquals[j] = 0; } var that = this; var getColumnValue = function(column, result){ var colValue = that.getFinalValue(column, result); colValue = that.cleanColValue(column, colValue); return colValue; } currentDisplayResult.forEach(function(result, i) { currentColumns.forEach(function(column, j) { if (i > 0 && column.mergeCells) { var currentColValue = getColumnValue(column, result); var previousColValue = getColumnValue(column, previousResult); if (currentColValue === previousColValue) { rowspans[i][j] = 0; nbRowEquals[j]++; //last element if (i === (currentDisplayResult.length - 1)) { rowspans[i - (nbRowEquals[j])][j] = nbRowEquals[j] + 1; } } else { rowspans[i][j] = 1; rowspans[i - (nbRowEquals[j] + 1)][j] = nbRowEquals[j] + 1; nbRowEquals[j] = 0; } } else if (i === 0) { rowspans[i][j] = 1; } }, this); previousResult = result; }, this); this.config.mergeCells.rowspans = rowspans; } }, /** * Selected only the records will be displayed. * Based on pagination configuration */ computeDisplayResult: function() { var time = 100; if (this.computeDisplayResultTimeOut !== undefined) { $timeout.cancel(this.computeDisplayResultTimeOut); } else { time = 0; } var that = this; this.computeDisplayResultTimeOut = $timeout(function() { //to manage local pagination var configPagination = that.config.pagination; var _displayResult = []; if (that.config.group.start && that.config.group.showOnlyGroups) { _displayResult = that.allGroupResult.slice((configPagination.pageNumber * configPagination.numberRecordsPerPage), (configPagination.pageNumber * configPagination.numberRecordsPerPage + configPagination.numberRecordsPerPage)); var displayResultTmp = []; angular.forEach(_displayResult, function(value, key) { var line = { "edit": (that.config.edit.start)?true:undefined, "selected": undefined, "trClass": undefined, "group": true, "new": false }; this.push({ data: value, line: line }); }, displayResultTmp); that.displayResult = displayResultTmp; } else { if(configPagination.active && !that.isRemoteMode(configPagination.mode)){ _displayResult = $.extend(true,[],that._getAllResult().slice((configPagination.pageNumber*configPagination.numberRecordsPerPage), (configPagination.pageNumber*configPagination.numberRecordsPerPage+configPagination.numberRecordsPerPage))); }else{ //to manage all records or server pagination _displayResult = $.extend(true,[],that._getAllResult()); } var displayResultTmp = []; var id = 0; angular.forEach(_displayResult, function(value, key) { var line = { "edit": (that.config.edit.start)?true:undefined, "selected": undefined, "trClass": undefined, "group": false, "new": false, "id":id++ }; this.push({ data: value, line: line }); }, displayResultTmp); //group function that.config.mergeCells.rowspans = undefined; if (that.isGroupActive()) { that.displayResult = that.addGroup(displayResultTmp); } else { that.displayResult = displayResultTmp; that.computeRowSpans(); } if (that.config.edit.byDefault) { that.setEdit(); } if(angular.isFunction(that.config.callbackEndDisplayResult)){ that.config.callbackEndDisplayResult(); } } }, time); }, /** * Load all data for url column type */ loadUrlColumnProperty: function() { var urlColumns = this.getColumnsConfig().filter(function(column) { return (column.url !== undefined && column.url !== null); }); var displayResult = this.allResult; var urlQueries = []; var urlCache = this.urlCache = {}; urlColumns.forEach(function(column) { displayResult.forEach(function(value) { var url = $parse(column.url)(value); if (!angular.isDefined(urlCache[url])) { urlCache[url] = "in waiting data ..."; urlQueries.push($http.get(url, { url: url }).then(function(result){ urlCache[result.config.url] = result.data; },function(result){ urlCache[result.config.url] = "Error for load column property : " + result.config.url; })); } }); }); $q.all(urlQueries); }, //pagination functions /** * compute the pagination item list */ computePaginationList: function() { var configPagination = this.config.pagination; if (configPagination.active) { configPagination.pageList = []; var currentPageNumber = configPagination.pageNumber; var nbPages = Math.ceil(this.totalNumberRecords / configPagination.numberRecordsPerPage); if (this.config.group.active && this.config.group.start && this.config.group.showOnlyGroups) { nbPages = Math.ceil(this.allGroupResult.length / configPagination.numberRecordsPerPage); } if (currentPageNumber > nbPages - 1) { configPagination.pageNumber = 0; currentPageNumber = 0; } if (nbPages > 1 && nbPages <= configPagination.numberPageListMax) { for (var i = 0; i < nbPages; i++) { configPagination.pageList.push({ number: i, label: i + 1, clazz: (i != currentPageNumber) ? '' : 'active' }); } } else if (nbPages > configPagination.numberPageListMax) { var min = currentPageNumber - ((configPagination.numberPageListMax - 1) / 2); var max = currentPageNumber + ((configPagination.numberPageListMax - 1) / 2) + 1; if (min < 0) { min = 0; } else if (min > nbPages - configPagination.numberPageListMax) { min = nbPages - configPagination.numberPageListMax; } if (max < configPagination.numberPageListMax) { max = configPagination.numberPageListMax; } else if (max > nbPages) { max = nbPages; } configPagination.pageList.push({ number: 0, label: '<<', clazz: (currentPageNumber != min) ? '' : 'disabled' }); configPagination.pageList.push({ number: currentPageNumber - 1, label: '<', clazz: (currentPageNumber != min) ? '' : 'disabled' }); for (; min < max; min++) { configPagination.pageList.push({ number: min, label: min + 1, clazz: (min != currentPageNumber) ? '' : 'active' }); } configPagination.pageList.push({ number: currentPageNumber + 1, label: '>', clazz: (currentPageNumber != max - 1) ? '' : 'disabled' }); configPagination.pageList.push({ number: nbPages - 1, label: '>>', clazz: (currentPageNumber != max - 1) ? '' : 'disabled' }); } } else { //console.log("pagination is not active !!!"); } }, setSpinner: function(value) { this.config.spinner.start = value; }, /** * Set the number of records by page */ setNumberRecordsPerPage: function(numberRecordsPerPageElement) { if (this.config.pagination.active) { if (angular.isObject(numberRecordsPerPageElement)) { this.config.pagination.numberRecordsPerPage = numberRecordsPerPageElement.number; numberRecordsPerPageElement.clazz = 'active'; for (var i = 0; i < this.config.pagination.numberRecordsPerPageList.length; i++) { if (this.config.pagination.numberRecordsPerPageList[i].number != numberRecordsPerPageElement.number) { this.config.pagination.numberRecordsPerPageList[i].clazz = ''; } } if (this.config.edit.active && this.config.edit.start) { //TODO add a warning popup console.log("edit is active, you lost all modification !!"); this.config.edit = angular.copy(this.configMaster.edit); //reinit edit } //reinit to first page this.config.pagination.pageNumber = 0; if (this.isRemoteMode(this.config.pagination.mode)) { this.searchWithLastParams(); } else { this.computePaginationList(); this.computeDisplayResult(); } } } else { //console.log("pagination is not active !!!"); } }, /** * Change the page result */ setPageNumber: function(page) { if (this.config.pagination.active) { if (angular.isObject(page) && page.clazz === '') { if (this.config.edit.active && this.config.edit.start) { //TODO add a warning popup console.log("edit is active, you lost all modification !!"); this.config.edit = angular.copy(this.configMaster.edit); //reinit edit } this.config.pagination.pageNumber = page.number; if (this.isRemoteMode(this.config.pagination.mode)) { this.searchWithLastParams(); } else { this.computePaginationList(); this.computeDisplayResult(); } } } else { //console.log("pagination is not active !!!"); } }, //order functions /** * Sort all result */ sortAllResult: function() { if (this.config.order.active && !this.isRemoteMode(this.config.order.mode)) { var orderBy = []; if (this.config.group.active && this.config.group.start && this.config.group.by !== "all") { if (!this.config.group.showOnlyGroups) { var orderGroupSense = (this.config.order.groupReverse) ? '-' : '+'; orderBy.push(orderGroupSense + this.config.group.by.property); if (angular.isDefined(this.config.order.by)) { var orderProperty = this.config.order.by.property; orderProperty += (this.config.order.by.filter) ? '|' + this.config.order.by.filter : ''; var orderSense = (this.config.order.reverse) ? '-' : '+'; orderBy.push(orderSense + orderProperty); } this.allResult = $filter('orderBy')(this.allResult, orderBy); } else { if (angular.isDefined(this.config.order.by)) { var orderProperty = "group." + this.config.order.by.id; var orderSense = (this.config.order.reverse) ? '-' : '+'; orderBy.push(orderSense + orderProperty); } this.allGroupResult = $filter('orderBy')(this.allGroupResult, orderBy); } } else if (angular.isDefined(this.config.order.by)) { if (angular.isDefined(this.config.order.by)) { var orderProperty = this.config.order.by.property; orderProperty += (this.config.order.by.filter) ? '|' + this.config.order.by.filter : ''; var orderSense = (this.config.order.reverse) ? '-' : '+'; orderBy.push(orderSense + orderProperty); } this.allResult = $filter('orderBy')(this.allResult, orderBy); } } }, /** * set the order column name * @param orderColumnName : column name */ setOrderColumn: function(column) { if (this.config.order.active) { var columnId = column.id; if (angular.isDefined(this.config.group.by) && this.config.group.by.id === columnId && !this.config.group.showOnlyGroups) { this.config.order.groupReverse = !this.config.order.groupReverse; } else { if (!angular.isDefined(this.config.order.by) || this.config.order.by.id !== columnId) { this.config.order.by = column; this.config.order.reverse = false; } else { this.config.order.reverse = !this.config.order.reverse; } for (var i = 0; i < this.config.columns.length; i++) { if (this.config.columns[i].id === columnId) { this.config.order.columns[this.config.columns[i].id] = true; } else { this.config.order.columns[this.config.columns[i].id] = false; } } if (this.config.edit.active && this.config.edit.start) { //TODO add a warning popup console.log("edit is active, you lost all modification !!"); this.config.edit = angular.copy(this.configMaster.edit); //reinit edit } } if (!this.isRemoteMode(this.config.order.mode)) { this.sortAllResult(); //sort all the result this.computeDisplayResult(); //redefined the result must be displayed } else if (this.config.order.active) { this.searchWithLastParams(); } var that = this; this.computeDisplayResultTimeOut.then(function() { if (angular.isFunction(that.config.order.callback)) { that.config.order.callback(this); } }); } else { //console.log("order is not active !!!"); } }, getOrderColumnClass: function(columnId) { if (this.config.order.active) { if (angular.isDefined(this.config.group.by) && this.config.group.by.id === columnId && !this.config.group.showOnlyGroups) { if (!this.config.order.groupReverse) { return 'fa fa-sort-up'; } else { return 'fa fa-sort-down'; } } else { if (!this.config.order.columns[columnId]) { return 'fa fa-sort'; } else if (this.config.order.columns[columnId] && !this.config.order.reverse) { return 'fa fa-sort-up'; } else if (this.config.order.columns[columnId] && this.config.order.reverse) { return 'fa fa-sort-down'; } } } else { //console.log("order is not active !!!"); } }, /** * indicate if we can order the table */ canOrder: function() { return (this.config.edit.active ? !this.config.edit.start : (this.config.order.active && !this.isEmpty())); }, //show /** * show one element * work only with tab on the left */ show: function() { if (this.config.show.active && angular.isFunction(this.config.show.add)) { angular.forEach(this.displayResult, function(value, key) { if (value.line.selected) { this.config.show.add(value.data); } }, this); } else { //console.log("show is not active !"); } }, //Hide a column /** * set the hide column * @param hideColumnName : column name */ setHideColumn: function(column) { if (this.config.hide.active) { var columnId = column.id; if (!this.config.hide.columns[columnId]) { this.config.hide.columns[columnId] = true; } else { this.config.hide.columns[columnId] = false; } this.newExtraHeaderConfig(); } else { //console.log("hide is not active !"); } }, /** * Test if a column must be grouped * @param columnId : column id */ isGroup: function(columnId) { if (this.config.group.active && this.config.group.columns[columnId]) { return this.config.group.columns[columnId]; } else { return false; } }, /** * Test if a column must be hide * @param columnId : column id */ isHide: function(columnId) { if (this.config.hide.active && this.config.hide.columns[columnId]) { return this.config.hide.columns[columnId]; } else { //console.log("hide is not active !"); return false; } }, //edit /** * set Edit all column or just one * @param editColumnName : column name */ setEdit: function(column) { if (this.config.edit.active) { var that = this; this.computeDisplayResultTimeOut.then(function() { that._getAllResult = function() { return that.allResult; }; that.config.edit.columns = {}; var find = false; for (var i = 0; i < that.displayResult.length; i++) { if (that.displayResult[i].line.selected || that.config.edit.withoutSelect || that.config.edit.byDefault) { if (angular.isUndefined(that.config.edit.lineMode) || (angular.isFunction(that.config.edit.lineMode) && that.config.edit.lineMode(that.displayResult[i].data))) { that.displayResult[i].line.edit = true; find = true; } else that.displayResult[i].line.edit = false; } else { that.displayResult[i].line.edit = false; } } that.selectAll(false); if (find) { that.config.edit.start = true; if (column) { that.config.edit.all = false; var columnId = column.id; if (angular.isUndefined(that.config.edit.columns[columnId])) { that.config.edit.columns[columnId] = {}; } that.config.edit.columns[columnId].edit = true; } else that.config.edit.all = true; } }); } else { //console.log("edit is not active !"); } }, /** * Test if a column must be in edition mode * @param editColumnName : column name * @param line : the line in the table */ isEdit: function(columnId, line) { var isEdit = false; if (this.config.edit.active) { if (columnId && line) { if (angular.isUndefined(this.config.edit.columns[columnId])) { this.config.edit.columns[columnId] = {}; } var columnEdit = this.config.edit.columns[columnId].edit; isEdit = (line.edit && columnEdit) || (line.edit && this.config.edit.all); } else if (columnId) { if (angular.isUndefined(this.config.edit.columns[columnId])) { this.config.edit.columns[columnId] = {}; } var columnEdit = this.config.edit.columns[columnId].edit; isEdit = (columnEdit || this.config.edit.all); } else if (line) { isEdit = line.edit && this.config.edit.all; } else { var nbEditableColumns = $filter('filter')(this.config.columns, {"edit":true}).length; isEdit = (this.config.edit.columnMode && this.config.edit.start && nbEditableColumns > 0); } } return isEdit; }, /** * indicate if at least one line is selected */ canEdit: function() { return (this.config.edit.withoutSelect ? true : this.isSelect()); }, /** * Update all line with the same value * @param updateColumnName : column name */ updateColumn: function(columnPropertyName, columnId) { if (this.config.edit.active && this.config.edit.columns[columnId].value !== undefined) { var getter = $parse(columnPropertyName); for (var i = 0; i < this.displayResult.length; i++) { if (this.displayResult[i].line.edit) { getter.assign(this.displayResult[i].data, this.config.edit.columns[columnId].value); } } } else { //console.log("edit is not active !"); } }, //save /** * Save the selected table line */ save: function() { if (this.config.save.active && this.displayResult) { if(this.formController.$invalid){ this.config.save.enableValidation = true; }else{ this.config.save.number = 0; this.config.save.error = 0; this.config.save.start = true; this.setSpinner(true); this.config.messages.text = undefined; this.config.messages.clazz = undefined; var data = []; var valueFunction = this.getValueFunction(this.config.save.value); for (var i = 0; i < this.displayResult.length; i++) { if (this.displayResult[i].line.edit || this.config.save.withoutEdit) { //remove datatable properties to avoid this data are retrieve in the json this.resetErrors(i); this.config.save.number++; var dr = this.displayResult[i]; dr.line.trClass = undefined; dr.line.selected = undefined; data.push({ index: i, data: dr.data }); } } if(data.length === 0){ return $q.when(this.saveFinish()); }else if (!this.isRemoteMode(this.config.save.mode)) { return this.saveAllLocal(data); } else if (this.isRemoteMode(this.config.save.mode) && !this.config.save.batch) { return this.saveAllRemote(data); } else if (this.isRemoteMode(this.config.save.mode) && this.config.save.batch) { return this.saveAllBatchRemote(data); } } } else { //console.log("save is not active !"); } }, getBeforeSavePromise : function(){ var beforeSavePromise = function(context){ if(context.datatable.config.save.beforeSave === undefined || context.datatable.config.save.beforeSave === null){ return context.value; }else{ return context.datatable.config.save.beforeSave(context.value); } }; return beforeSavePromise; }, saveAllLocal: function(values) { //do not transform the value var queries = values.map(function(value){ //to backward compatibility with synchrone local save if(this.config.save.beforeSave === undefined || this.context.datatable.config.save.beforeSave === null){ this.saveLocal(value.data, value.index); this.saveFinish(); return $q.when(); }else{ var context = {datatable:this, value:value.data, index:value.index}; return $q.when(context, this.getBeforeSavePromise()).then(function(resp){ context.datatable.saveLocal(context.value, context.index); context.datatable.saveFinish(); },function(resp){ //error context.datatable.saveOnError(context.value, context.index); context.datatable.saveFinish(); }); } },this) return $q.all(queries).then(function(results) { console.log("save global ok"); },function(results){ console.log("save global error"); }); }, saveAllBatchRemote: function(values) { var nbElementByBatch = Math.ceil(values.length / 6); //6 because 6 request max in parrallel with firefox and chrome var queries = []; for (var i = 0; i < 6 && values.length > 0; i++) { queries.push(this.getSaveRemoteRequest(values.splice(0, nbElementByBatch))); } return $q.all(queries).then(function(results) { console.log("save global ok"); },function(results){ console.log("save global error"); }); }, saveAllRemote: function(values) { var queries = values.map(function(value){ return this.getSaveRemoteRequest(value.data, value.index) },this); return $q.all(queries).then(function(results) { console.log("save global ok"); },function(results){ console.log("save global error"); }); }, saveRemoteOneElement: function(status, value, index) { if (status !== 200) { this.saveOnError(value, index); this.saveFinish(); } else { this.resetErrors(index); this.saveLocal(value, index); this.saveFinish(); } }, /** * value = one value or array in batch mode */ getSaveRemoteRequest: function(value, i) { var urlFunction = this.getUrlFunction(this.config.save.url); if(urlFunction === null || urlFunction === undefined) throw 'no url define for save !'; var method = this.config.save.method; if (angular.isFunction(method)) { method = method(value); } var httpConfig = { datatable: this }; if (angular.isObject(this.config.save.httpConfig)) { angular.merge(httpConfig, this.config.save.httpConfig); } var valueFunction = this.getValueFunction(this.config.save.value); if (this.config.save.batch) { var context = {datatable:this, value:value}; return $q.when(context, this.getBeforeSavePromise()) .then(function(){ $http[method](urlFunction(value), value.map(function(v){return {index:v.index,data:valueFunction(v.data)};}), httpConfig). then(function(resp) { angular.forEach(resp.data, function(value, key) { this.datatable.saveRemoteOneElement(value.status, value.data, value.index); },resp.config); return resp; }, function(resp) { //resp.data must contain an array of map of errors angular.forEach(resp.data, function(value, key) { this.datatable.saveRemoteOneElement(resp.status, value.data, value.index); },resp.config); return resp; }); },function(resp){ angular.forEach(context.value, function(v, key) { //can be improve because we don't have any error message console.log("error on beforeSave"); this.saveRemoteOneElement("500", v.data, v.index); },context.datatable); }); } else { httpConfig.index = i; var context = {datatable:this, value:value, index:i}; return $q.when(context, this.getBeforeSavePromise()) .then(function(){ return $http[method](urlFunction(value), valueFunction(value), httpConfig). then(function(resp) { resp.config.datatable.saveRemoteOneElement(resp.status, resp.data, resp.config.index); return resp; }, function(resp) { //resp.data must contain a map of errors resp.config.datatable.saveRemoteOneElement(resp.status, resp.data, resp.config.index); return resp; }); },function(){ //can be improve because we don't have any error message console.log("error on beforeSave"); context.datatable.saveRemoteOneElement("500", context.value, context.index); }); } }, saveOnError: function(value, index){ if (this.config.save.changeClass) { this.displayResult[index].line.trClass = "danger"; } this.displayResult[index].line.edit = true; this.addErrors(index, value); this.config.save.error++; this.config.save.number--; }, /** * Call after save to update the records property */ saveLocal: function(data, i) { if (this.config.save.active) { if (data) { this.displayResult[i].data = data; } //update in the all result table if (!this.displayResult[i].line["new"]) { var j = i; if (this.config.pagination.active && !this.isRemoteMode(this.config.pagination.mode)) { j = i + (this.config.pagination.pageNumber * this.config.pagination.numberRecordsPerPage); } this.allResult[j] = $.extend(true,{},this.displayResult[i].data); } else { this.config.save.newData.push(data); } if (!this.config.save.keepEdit) { this.displayResult[i].line.edit = undefined; } else { this.displayResult[i].line.edit = true; } if (this.config.save.changeClass) { this.displayResult[i].line.trClass = "success"; } this.config.save.number--; } else { //console.log("save is not active !"); } }, /** * Call when a save local or remote is finish */ saveFinish: function() { if (this.config.save.number === 0) { if (this.config.save.error > 0) { this.config.messages.clazz = this.config.messages.errorClass; this.config.messages.text = this.config.messages.transformKey(this.config.messages.errorKey.save, this.config.save.error); } else { this.config.messages.clazz = this.config.messages.successClass; this.config.messages.text = this.config.messages.transformKey(this.config.messages.successKey.save); } if (angular.isFunction(this.config.save.callback)) { this.config.save.callback(this, this.config.save.error); } if (!this.config.save.keepEdit && this.config.save.error === 0) { this.config.edit.start = false; } this.config.save.error = 0; this.config.save.start = false; //insert new data create by addBlank in result if (this.config.save.newData.length > 0) { this.addData(this.config.save.newData); } this.config.save.newData = []; this.config.save.enableValidation = false; this.setSpinner(false); } }, /** * Test if save mode can be enable */ canSave: function() { if (this.config.edit.active && !this.config.save.withoutEdit && !this.config.save.start) { return this.config.edit.start; } else if (this.config.edit.active && this.config.save.withoutEdit && !this.config.save.start) { return true; } else { return false; } }, //remove /** * Remove the selected table lines */ remove: function() { if (this.config.remove.active && !this.config.remove.start) { var r = $window.confirm(this.messages.Messages("datatable.remove.confirm")); if (r) { this.setSpinner(true); this.config.messages.text = undefined; this.config.messages.clazz = undefined; this.config.remove.counter = 0; this.config.remove.start = true; this.config.remove.number = 0; this.config.remove.error = 0; this.config.remove.ids = { errors: [], success: [] }; for (var i = 0; i < this.displayResult.length; i++) { if (this.displayResult[i].line.selected && (!this.displayResult[i].line.edit || this.config.remove.withEdit)) { if (this.isRemoteMode(this.config.remove.mode)) { this.config.remove.number++; this.removeRemote(this.displayResult[i].data, i); } else { this.config.remove.ids.success.push(i); } } } if (!this.isRemoteMode(this.config.remove.mode)) { this.removeFinish(); } } } else { //console.log("remove is not active !"); } }, /** * Call after save to update the records property */ removeLocal: function(i) { if (this.config.remove.active && this.config.remove.start) { //update in the all result table var j; if (this.config.pagination.active && !this.isRemoteMode(this.config.pagination.mode)) { j = (i + (this.config.pagination.pageNumber * this.config.pagination.numberRecordsPerPage)) - this.config.remove.counter; } else { j = i - this.config.remove.counter; } this.allResult.splice(j, 1); this.config.remove.counter++; this.totalNumberRecords--; } else { //console.log("remove is not active !"); } }, removeRemote: function(value, i) { var url = this.getUrlFunction(this.config.remove.url); if (url) { return $http['delete'](url(value), { datatable: this, index: i, value: value }) .then(function(resp) { resp.config.datatable.config.remove.ids.success.push(resp.config.index); resp.config.datatable.config.remove.number--; resp.config.datatable.removeFinish(); return resp; }, function(resp) { resp.config.datatable.config.remove.ids.errors.push(resp.config.value); resp.config.datatable.config.remove.error++; resp.config.datatable.config.remove.number--; resp.config.datatable.removeFinish(); return resp; }); } else { throw 'no url define for save !'; } }, /** * Call when a remove is done */ removeFinish: function() { if (this.config.remove.number === 0) { this.config.remove.ids.success.sort(function(a, b) { return a - b; }).forEach(function(i) { this.removeLocal(i); }, this); if (this.config.remove.error > 0) { this.config.messages.clazz = this.config.messages.errorClass; this.config.messages.text = this.config.messages.transformKey(this.config.messages.errorKey.remove, this.config.remove.error); } else { this.config.messages.clazz = this.config.messages.successClass; this.config.messages.text = this.config.messages.transformKey(this.config.messages.successKey.remove); } if (angular.isFunction(this.config.remove.callback)) { this.config.remove.callback(this, this.config.remove.error); } this.computePaginationList(); this.computeDisplayResult(); var that = this; this.computeDisplayResultTimeOut.then(function() { if (that.config.remove.ids.errors.length > 0) { that.displayResult.every(function(value, index) { var errors = that.config.remove.ids.errors; for (var i = 0; i < errors.length; i++) { if (angular.equals(value.data, errors[i])) { value.line.trClass = "danger"; errors.splice(i, 1); break; } } if (errors.length === 0) { return false; } else { return true; } }, that); } that.config.select.isSelectAll = false; that.config.remove.error = 0; that.config.remove.start = false; that.config.remove.counter = 0; that.config.remove.ids = { error: [], success: [] }; that.setSpinner(false); }); }; }, /** * indicate if at least one line is selected and not in edit mode */ canRemove: function() { if (this.config.remove.active && !this.config.remove.start) { for (var i = 0; this.displayResult && i < this.displayResult.length; i++) { if (this.displayResult[i].line.selected && (!this.displayResult[i].line.edit || this.config.remove.withEdit)) return true; } } else { //console.log("remove is not active !"); return false; } }, //select /** * Select or unselect all line * value = true or false */ selectAll: function(value) { if (this.config.select.active && this.displayResult) { this.config.select.isSelectAll = value; for (var i = 0; i < this.displayResult.length; i++) { if (value) { if (!this.displayResult[i].line.group) { this.displayResult[i].line.selected = true; this.displayResult[i].line.trClass = "info"; } else if (this.displayResult[i].line.group && this.config.group.enableLineSelection) { this.displayResult[i].line.groupSelected = true; this.displayResult[i].line.trClass = "info"; } } else { if (!this.displayResult[i].line.group) { this.displayResult[i].line.selected = false; this.displayResult[i].line.trClass = undefined; } else if (this.displayResult[i].line.group && this.config.group.enableLineSelection) { this.displayResult[i].line.groupSelected = false; this.displayResult[i].line.trClass = undefined; } } if (angular.isFunction(this.config.select.callback)) { console.warning('select.callback is deprecated. Use mouseevents.clickCallback instead.'); this.config.select.callback(this.displayResult[i].line, this.displayResult[i].data); } else if (angular.isFunction(this.config.mouseevents.clickCallback)) { this.config.mouseevents.clickCallback(this.displayResult[i].line, this.displayResult[i].data); } } } else { //console.log("select is not active"); } }, /** * Return all selected element and unselect the data */ getSelection: function(unselect) { var selection = []; for (var i = 0; i < this.displayResult.length; i++) { if (this.displayResult[i].line.selected) { //unselect selection if (unselect) { this.displayResult[i].line.selected = false; this.displayResult[i].line.trClass = undefined; } selection.push($.extend(true,{},this.displayResult[i].data)); } else if (this.displayResult[i].line.groupSelected) { //unselect selection if (unselect) { this.displayResult[i].line.groupSelected = false; this.displayResult[i].line.trClass = undefined; } selection.push($.extend(true,{},this.displayResult[i].data)); } } if (unselect) { this.config.select.isSelectAll = false; } return selection; }, /** * indicate if at least one line is selected */ isSelect: function() { for (var i = 0; this.displayResult && i < this.displayResult.length; i++) { if (this.displayResult[i].line.selected) return true; } return false; }, isSelectGroup: function() { for (var i = 0; this.displayResult && i < this.displayResult.length; i++) { if (this.displayResult[i].line.groupSelected) return true; } return false; }, /** * cancel edit, hide and selected lines only */ cancel: function() { if (this.config.cancel.active) { /*cancel only edit and hide mode */ this.config.edit = angular.copy(this.configMaster.edit); this.config.edit.byDefault = false; this.config.save = angular.copy(this.configMaster.save); this.config.hide = angular.copy(this.configMaster.hide); this.config.remove = angular.copy(this.configMaster.remove); this.config.select = angular.copy(this.configMaster.select); this.config.messages = angular.copy(this.configMaster.messages); this.totalNumberRecords = this.allResult.length; this.setHideColumnByDefault(); this.newExtraHeaderConfig(); this.computePaginationList(); this.computeDisplayResult(); } }, //template helper functions isShowToolbar: function() { return (this.isShowToolbarButtons() || this.isShowToolbarPagination() || this.isShowToolbarResults()); }, isShowToolbarBottom: function() { return (this.isShowToolbarPagination() && this.config.pagination.bottom && this.config.pagination.numberRecordsPerPage >= this.config.pagination.numberRecordsPerPageForBottomdisplay); }, isShowToolbarButtons: function() { return (this.isShowCRUDButtons() || this.isShowHideButtons() || this.isShowAddButtons() || this.isShowShowButtons() || this.isShowExportCSVButton() || this.isShowOtherButtons()); }, isShowCRUDButtons: function() { return ((this.config.edit.active && this.config.edit.showButton) || (this.config.save.active && this.config.save.showButton) || (this.config.remove.active && this.config.remove.showButton)); }, isShowAddButtons: function() { return (this.config.add.active && this.config.add.showButton); }, isShowShowButtons: function() { return (this.config.show.active && this.config.show.showButton); }, isShowHideButtons: function() { return (this.config.hide.active && this.config.hide.showButton && this.getHideColumns().length > 0); }, isShowOtherButtons: function() { return (this.config.otherButtons.active && this.config.otherButtons.template !== undefined); }, isShowToolbarPagination: function() { return this.config.pagination.active; }, isShowPagination: function() { return (this.config.pagination.active && this.config.pagination.pageList.length > 0); }, isShowToolbarResults: function() { return this.config.showTotalNumberRecords; }, isCompactMode: function() { return this.config.compact; }, isEmpty: function() { return (this.allResult === undefined || this.allResult === null || this.allResult.length === 0); }, goToAnchor : function(hash){ $anchorScroll.yOffset = 50; if ($location.hash() !== hash) { // set the $location.hash to `newHash` and // $anchorScroll will automatically scroll to it $location.hash(hash); } else { // call $anchorScroll() explicitly, // since $location.hash hasn't changed $anchorScroll(); } }, /** * Function to show (or not) the "CSV Export" button */ isShowExportCSVButton: function() { return (this.config.exportCSV.active && this.config.exportCSV.showButton); }, isShowButton: function(configParam, column) { if (column) { return (this.config[configParam].active && ((this.config[configParam].showButtonColumn !== undefined && this.config[configParam].showButtonColumn) || this.config[configParam].showButton) && column[configParam]); } else { return (this.config[configParam].active && this.config[configParam].showButton); } }, isShowLineEditButton: function() { return this.config.edit.active && this.config.edit.showLineButton; }, setShowButton: function(configParam, value) { if (this.config[configParam].active) { this.config[configParam].showButton = value; } }, /** * Add pagination parameters if needed */ getParams: function(params) { if (angular.isUndefined(params)) { params = {}; } params.datatable = true; if (this.config.pagination.active) { params.paginationMode = this.config.pagination.mode; if (this.isRemoteMode(this.config.pagination.mode)) { params.pageNumber = this.config.pagination.pageNumber; params.numberRecordsPerPage = this.config.pagination.numberRecordsPerPage; } } if (this.config.order.active && this.isRemoteMode(this.config.order.mode) && angular.isDefined(this.config.order.by)) { params.orderBy = this.config.order.by.property; params.orderSense = (this.config.order.reverse) ? "-1" : "1"; } return params; }, /** * Return an url from play js object or string */ getUrlFunction: function(url) { if (angular.isObject(url)) { if (angular.isDefined(url.url)) { return function(value) { return url.url; }; } } else if (angular.isString(url)) { return function(value) { return url; }; } else if (angular.isFunction(url)) { return url; } return undefined; }, /** * Return a function to transform value if exist or the default mode */ getValueFunction: function(valueFunction) { if (angular.isFunction(valueFunction)) { return valueFunction; } return function(value) { return value; }; }, /** * test is remote mode */ isRemoteMode: function(mode) { if (mode && mode === 'remote') { return true; } else { return false; } }, setHideColumnByDefault: function(){ if(this.config.hide.active && angular.isDefined(this.config.hide.byDefault)){ if(!angular.isArray(this.config.hide.byDefault))this.config.hide.byDefault = [this.config.hide.byDefault]; angular.forEach(this.config.columns, function(column, key){ angular.forEach(this.config.hide.byDefault,function(value, key){ if(value === column.property){ this.setHideColumn(column); } },this); }, this); } }, /** * Set columns configuration */ setColumnsConfig: function(columns) { if (angular.isDefined(columns)) { var initPosition = 1000000; for (var i = 0; i < columns.length; i++) { if (!columns[i].type || columns[i].type.toLowerCase() === "string") { columns[i].type = "text"; } else { columns[i].type = columns[i].type.toLowerCase(); } if (columns[i].type === "img" || columns[i].type === "image") { if (!columns[i].format) console.log("missing format for " + columns[i].property); if (!columns[i].width) columns[i].width = '100%'; } columns[i].id = this.generateColumnId(); /* if(columns[i].hide && !this.config.hide.active){ columns[i].hide = false; } if(columns[i].order && !this.config.order.active){ columns[i].order = false; } if(columns[i].edit && !this.config.edit.active){ columns[i].edit = false; } if(columns[i].mergeCells && !this.config.mergeCells.active){ columns[i].mergeCells = false; } */ //TODO: else{Error here ?} if (columns[i].choiceInList && !angular.isDefined(columns[i].listStyle)) { columns[i].listStyle = "select"; } if (columns[i].choiceInList && !angular.isDefined(columns[i].possibleValues)) { columns[i].possibleValues = []; } if (this.config.group.active && angular.isDefined(this.config.group.by) && (columns[i].property === this.config.group.by || columns[i].property === this.config.group.by.property)) { this.config.group.by = columns[i]; this.config.group.start=true; this.config.group.columns[columns[i].id] = true; columns[i].group = true; } else { this.config.group.columns[columns[i].id] = false; } if (this.config.order.active && angular.isDefined(this.config.order.by) && (columns[i].property === this.config.order.by || columns[i].property === this.config.order.by.property)) { this.config.order.by = columns[i]; this.config.order.columns[columns[i].id] = true; columns[i].order = true; } else { this.config.order.columns[columns[i].id] = false; } //ack to keep the default order in chrome if (null === columns[i].position || undefined === columns[i].position) { columns[i].position = initPosition++; } if (columns[i].convertValue !== undefined && columns[i].convertValue !== null && columns[i].convertValue.active === true && (columns[i].convertValue.displayMeasureValue === undefined || columns[i].convertValue.saveMeasureValue === undefined)) { throw "Columns config error: " + columns[i].property + " convertValue=active but convertValue.displayMeasureValue or convertValue.saveMeasureValue is missing"; } if(null === columns[i].localSearch || undefined === columns[i].localSearch){ columns[i].localSearch = false; } if(null === columns[i].edit || undefined === columns[i].edit){ columns[i].edit = false; } if(null === columns[i].headerTpl || undefined === columns[i].headerTpl){ columns[i].headerTpl = '<span class="header" ng-model="udtTable" ng-bind="udtHelpers.messages.Messages(column.header)"/>'; } } var settings = $.extend(true, [], this.configColumnDefault, columns); settings = $filter('orderBy')(settings, 'position'); this.config.columns = angular.copy(settings); this.configMaster.columns = angular.copy(settings); this.setHideColumnByDefault(); this.newExtraHeaderConfig(); if(this.allResult){ this.computeGroup(); this.sortAllResult(); this.computePaginationList(); this.computeDisplayResult(); } } }, setColumnsConfigWithUrl: function() { $http.get(this.config.columnsUrl, { datatable: this }).then(function(resp) { resp.config.datatable.setColumnsConfig(resp.data); return resp; }); }, getColumnsConfig: function() { return this.config.columns; }, getConfig: function() { return this.config; }, setConfig: function(config) { var settings = $.extend(true, {}, this.configDefault, config); this.config = angular.copy(settings); if(this.config.filter !== undefined){ this.config.localSearch = this.config.filter; this.config.filter = undefined; console.log("config filter is deprecated used localSearch"); } if(!this.config.pagination.numberRecordsPerPageList){ this.config.pagination.numberRecordsPerPageList = [{ number: 10, clazz: '' }, { number: 25, clazz: '' }, { number: 50, clazz: '' }, { number: 100, clazz: '' }]; } this.configMaster = angular.copy(settings); if (this.config.columnsUrl) { this.setColumnsConfigWithUrl(); } else { this.setColumnsConfig(this.config.columns); } if (this.displayResult && this.displayResult.length > 0) { this.computePaginationList(); this.computeDisplayResult(); } }, /** * Return column with hide */ getHideColumns: function() { var c = []; for (var i = 0; i < this.config.columns.length; i++) { if (this.config.columns[i].hide) { c.push(this.config.columns[i]); } } return c; }, /** * Return column with group */ getGroupColumns: function() { var c = []; for (var i = 0; i < this.config.columns.length; i++) { if (this.config.columns[i].group) { c.push(this.config.columns[i]); } } return c; }, /** * Return column with edit */ getEditColumns: function() { var c = []; for (var i = 0; i < this.config.columns.length; i++) { if (this.config.columns[i].edit) c.push(this.config.columns[i]); } return c; }, generateColumnId: function() { this.inc++; return "p" + this.inc; }, newColumn: function(header, property, edit, hide, order, type, choiceInList, possibleValues, extraHeaders) { var column = {}; column.id = this.generateColumnId(); column.header = header; column.property = property; column.edit = edit; column.hide = hide; column.order = order; column.type = type; column.choiceInList = choiceInList; if (possibleValues != undefined) { column.possibleValues = possibleValues; } if (extraHeaders != undefined) { column.extraHeaders = extraHeaders; } return column; }, /** * Add a new column to the table with the <th>title</th> * at position */ addColumn: function(position, column) { if (position >= 0) { column.position = position; } this.config.columns.push(column); this.setColumnsConfig(this.config.columns); this.newExtraHeaderConfig(); }, /** * Remove a column at position */ deleteColumn: function(position) { this.config.columns.splice(position, 1); this.newExtraHeaderConfig(); }, addToExtraHeaderConfig: function(pos, header) { if (!angular.isDefined(this.config.extraHeaders.list[pos])) { this.config.extraHeaders.list[pos] = []; } this.config.extraHeaders.list[pos].push(header); }, getExtraHeaderConfig: function() { return this.config.extraHeaders.list; }, newExtraHeaderConfig: function() { if (this.config.extraHeaders.dynamic === true) { this.config.extraHeaders.list = {}; var lineUsed = false; // If we don't have label in a line, we don't want to show the line var count = 0; //Number of undefined extraHeader column beetween two defined ones //Every level of header for (var i = 0; i < this.config.extraHeaders.number; i++) { lineUsed = false; //re-init because new line var header = undefined; //Every column for (var j = 0; j < this.config.columns.length; j++) { if (!this.isHide(this.config.columns[j].id)) { //if the column have a extra header for this level if (this.config.columns[j].extraHeaders !== undefined && this.config.columns[j].extraHeaders[i] !== undefined) { lineUsed = true; if (count > 0) { //adding the empty header of undefined extraHeader columns this.addToExtraHeaderConfig(i, { "label": "", "colspan": count }); count = 0; //Reset the count to 0 } //The first time the header will be undefined if (header === undefined) { //create the new header with colspan 0 (the current column will be counted) header = { "label": this.config.columns[j].extraHeaders[i], "colspan": 0 }; } //if two near columns have the same header if (this.config.columns[j].extraHeaders[i] === header.label) { header.colspan += 1; } else { //We have a new header //adding the current one this.addToExtraHeaderConfig(i, header); //and create the new one with colspan 1 //colspan = 1 because we're already on the first column who have this header header = { "label": this.config.columns[j].extraHeaders[i], "colspan": 1 }; } } else if (header !== undefined) { lineUsed = true; //If we find a undefined column, we add the old header this.addToExtraHeaderConfig(i, header); //and increment the count var count++; //The old header is added header = undefined; } else { //No header to add, the previous one was a undefined column //increment the count var count++; } } } //At the end of the level loop //If we have undefined column left //And the line have at least one item if (count > 0 && (lineUsed === true || header !== undefined)) { this.addToExtraHeaderConfig(i, { "label": "", "colspan": count }); count = 0; } //If we have defined column left if (header !== undefined) { this.addToExtraHeaderConfig(i, header); } } } }, getFinalValue : function(column, result){ var filter = this.getFilter(column); var formatter = this.getFormatter(column); var context = {"col":column}; context = Object.assign(context, this.config.objectsMustBeAddInGetFinalValue); var colValue = undefined; if (!result.line.group && (column.url === undefined || column.url === null)) { var getter = $parse(column.property+filter); var v = getter(result.data, context); if(!angular.isArray(v)){ //so work for sum, average, unique and collect if one element colValue = $parse("this"+formatter)(v); }else { colValue = v.map(function(v){return $parse("this"+formatter)(v);}); } } else if (result.line.group) { var v = $parse("group."+column.id)(result.data, context); //if error in group function if(angular.isDefined(v) && angular.isString(v) && v.charAt(0) === "#"){ colValue = v; }else if(angular.isDefined(v)){ if(!angular.isArray(v)){ //so work for sum, average, unique and collect if one element colValue = $parse("this"+formatter)(v); }else { colValue = v.map(function(v){return $parse("this"+formatter)(v);}); } } } else if (!result.line.group && column.url !== undefined && column.url !== null) { var url = $parse(column.url)(result.data, context); var v = $parse(column.property+filter)(this.urlCache[url]); if(!angular.isArray(v)){ //so work for sum, average, unique and collect if one element colValue = $parse("this"+formatter)(v); }else { colValue = v.map(function(v){return $parse("this"+formatter)(v);}); } } return colValue; }, //clean data before put in CSV cleanColValue : function(column, colValue){ if(colValue === null)colValue = undefined; if (column.type === "number" && colValue !== undefined && !angular.isArray(colValue)) { colValue = colValue.replace(/\u00a0/g, ""); }else if(column.type === "number" && angular.isArray(colValue)){ colValue = colValue.map(function(colValue){return colValue.replace(/\u00a0/g, "");}); }else if(column.type === "boolean" && (colValue === undefined || (angular.isArray(colValue) && colValue.length === 0))){ colValue = this.messages.Messages('datatable.export.no'); } else if (column.type === "boolean" && colValue !== undefined) { if(!angular.isArray(colValue)){ colValue = [colValue]; } colValue = colValue.map(function(colValue){ if (colValue === true) { return this.messages.Messages('datatable.export.yes'); } else { return this.messages.Messages('datatable.export.no'); }},this); colValue = '"'+colValue.join()+'"'; }else if((column.type === "string" || column.type === "text" || column.type === "textarea") && colValue !== undefined){ if(!angular.isArray(colValue)){ colValue = [colValue]; } colValue = '"'+colValue.join()+'"'; }else if(column.type === "img" || column.type === "image" || column.type === "file"){ colValue = undefined; } return colValue; }, /** * Function to export data in a CSV file */ exportCSV: function(exportType) { if (this.config.exportCSV.active) { this.config.exportCSV.start = true; var delimiter = this.config.exportCSV.delimiter, lineValue = "", that = this; //calcule results ( code extracted from method computeDisplayResult() ) var displayResultTmp = []; if (this.isGroupActive()) { var orderProperty = this.config.group.by.property; orderProperty += (this.config.group.by.filter) ? '|' + this.config.group.by.filter : ''; var orderSense = (this.config.order.reverse) ? '-' : '+'; this.allResult = $filter('orderBy')(this.allResult, orderSense + orderProperty); } angular.forEach(this.allResult, function(value, key) { var line = { "edit": undefined, "selected": undefined, "trClass": undefined, "group": false, "new": false }; this.push({ data: value, line: line }); }, displayResultTmp); if (this.isGroupActive()) { displayResultTmp = this.addGroup(displayResultTmp); } //manage results if (displayResultTmp) { var columnsToPrint = this.config.columns; //header columnsToPrint.forEach(function(column) { if (!that.config.hide.columns[column.id]) { var header = column.header; if (angular.isFunction(header)) { header = header(); }else{ header = that.config.messages.transformKey(header); } if (that.isGroupActive() && column.property!=that.config.group.by.property) { if (column.groupMethod === "sum") { header = header + this.messages.Messages('datatable.export.sum'); } else if (column.groupMethod === "average") { header = header + this.messages.Messages('datatable.export.average'); } else if (column.groupMethod === "unique") { header = header + this.messages.Messages('datatable.export.unique'); } else if (column.groupMethod === "countDistinct" || column.groupMethod === "count:true") { header = header + this.messages.Messages('datatable.export.countDistinct'); } else if (column.groupMethod === "count" || column.groupMethod =="count:false" ) { header = header + this.messages.Messages('datatable.export.count'); } else if (column.groupMethod === "collect" || column.groupMethod === "collect:false") { header = header + this.messages.Messages('datatable.export.collect'); } else if (column.groupMethod === "collect:true") { header = header + this.messages.Messages('datatable.export.collectDistinct'); } } lineValue = lineValue + header + delimiter; } }, this); lineValue = lineValue.substr(0, lineValue.length - 1) + "\n"; //data displayResultTmp.forEach(function(result) { columnsToPrint.forEach(function(column) { if (!that.config.hide.columns[column.id] && (exportType !== 'groupsOnly' || (exportType === 'groupsOnly' && result.line.group))) { var colValue = that.getFinalValue(column, result); colValue = that.cleanColValue(column, colValue); lineValue = lineValue + ((colValue) ? colValue : "") + delimiter; } }, this); if ((exportType === 'all') || ((exportType === 'groupsOnly') && result.line.group)) { lineValue = lineValue.substr(0, lineValue.length - 1) + "\n"; } }, this); displayResultTmp = undefined; //fix for the accents in Excel : add BOM (byte-order-mark) var fixedstring = "\ufeff" + lineValue; //save var blob = new Blob([fixedstring], { type: "text/plain;charset=utf-8" }); var currdatetime = $filter('date')(new Date(), 'yyyyMMdd_HHmmss'); var text_filename = (this.config.name || this.configDefault.name) + "_" + currdatetime; saveAs(blob, text_filename + ".csv"); } else { alert("No data to print. Select the data you need"); } this.config.exportCSV.start = false; } }, /** * Sub-function use by (not only) exportCSV() */ getFormatter: function(col) { var format = ""; if (col && col.type) if (col.type === "date") { format += " | date:'" + (col.format ? col.format : this.messages.Messages("date.format")) + "'"; } else if (col.type === "datetime") { format += " | date:'" + (col.format ? col.format : this.messages.Messages("datetime.format")) + "'"; } else if (col.type === "number") { format += " | number" + (col.format ? ':' + col.format : ''); } return format; }, getFilter: function(col) { var filter = ''; if (col.convertValue !== undefined && col.convertValue !== null && col.convertValue.active === true && col.convertValue.saveMeasureValue != col.convertValue.displayMeasureValue) { filter += '|udtConvert:' + JSON.stringify(col.convertValue); } if (col.filter) { return filter + '|' + col.filter; } return filter; }, /** * Function to enable/disable the "CSV Export" button */ canExportCSV: function() { if (this.config.exportCSV.active && !this.config.exportCSV.start && !this.isEmpty()) { if (this.config.edit.active && this.config.edit.start) { return false; } else { return true; } } else { return false; } }, onDrop: function(e, draggedCol, droppedCol, datatable, alReadyInTheModel) { var posDrop = droppedCol.position; var posDrag = draggedCol.position; for (var i = 0; i < datatable.config.columns.length; i++) { if (posDrag < posDrop && datatable.config.columns[i].position > posDrag && datatable.config.columns[i].position < posDrop && datatable.config.columns[i].id !== draggedCol.id) { datatable.config.columns[i].position--; } if (posDrag > posDrop && datatable.config.columns[i].position > posDrop && datatable.config.columns[i].position < posDrag && datatable.config.columns[i].id !== draggedCol.id) { datatable.config.columns[i].position++; } if (datatable.config.columns[i].id === draggedCol.id) { datatable.config.columns[i].position = posDrop - 1; } } datatable.setColumnsConfig(datatable.config.columns); } }; if (arguments.length === 2) { iConfig = arguments[1]; console.log("used bad constructor for datatable, only one argument is required the config"); } datatable.setConfig(iConfig); return datatable; }; return constructor; }]); ;angular.module('ultimateDataTableServices'). //If the select or multiple choices contain 1 element, this directive select it automaticaly //EXAMPLE: <select ng-model="x" ng-option="x as x for x in x" udtAutoselect>...</select> directive('udtAutoSelect',['$parse', function($parse) { var OPTIONS_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w\d]*)|(?:\(\s*([\$\w][\$\w\d]*)\s*,\s*([\$\w][\$\w\d]*)\s*\)))\s+in\s+(.*)$/; return { require: 'ngModel', link: function(scope, element, attrs, ngModel) { var valOption = undefined; var multiple = false; if(attrs.ngOptions){ valOption = attrs.ngOptions; }else if(attrs.btOptions){ valOption = attrs.btOptions; } if(attrs.multiple === true || attrs.multiple === "true"){ multiple = true; } if(valOption != undefined){ var match = valOption.match(OPTIONS_REGEXP); var getModelValue = $parse(match[1].replace(match[4]+'.','')); scope.$watch(match[7], function(value){ if(value){ if(value.length === 1 && (ngModel.$modelValue === undefined || ngModel.$modelValue === '' || ngModel.$modelValue === null)){ var value = (multiple)?[getModelValue(value[0])]:getModelValue(value[0]); ngModel.$setViewValue(value); ngModel.$render(); } } }); }else{ console.log("ng-options or bt-options required"); } } }; }]);; angular.module('ultimateDataTableServices') .directive('udtBase64Img', [function () { return { restrict: 'A', require: 'ngModel', link: function (scope, elem, attrs, ngModel) { var nbFiles = 0, counter = 0, files; var onload = function (e) { if(e.target.result!= undefined && e.target.result != ""){ var udtBase64Img = {}; udtBase64Img._type = "img"; udtBase64Img.fullname = e.target.file.name; //console.log("udtBase64Img.fullname "+udtBase64Img.fullname); //Get the extension var matchExtension = e.target.file.type.match(/^image\/(.*)/); if(matchExtension && matchExtension.length > 1){ udtBase64Img.extension = matchExtension[1]; //Get the base64 without the extension feature var matchBase64 = e.target.result.match(/^.*,(.*)/); udtBase64Img.value = matchBase64[1]; //Load image from the base64 to get the width and height var img = new Image(); img.src = e.target.result; img.onload = function(){ counter++; udtBase64Img.width = img.width; udtBase64Img.height = img.height; files.push(udtBase64Img); onloadend(); }; }else{ counter++; alert("This is not an image..."+udtBase64Img.fullname); elem[0].value = null; } } }; var onloadend = function(){ if(nbFiles === counter){ if(attrs.multiple){ scope.$apply(function(scope){ngModel.$setViewValue(files);}); }else{ scope.$apply(function(scope){ngModel.$setViewValue(files[0]);}); } } }; elem.on('change', function() { nbFiles = 0, counter = 0; files = []; if(attrs.multiple){ nbFiles = elem[0].files.length angular.forEach(elem[0].files, function(inputFile){ var reader = new FileReader(); reader.file = inputFile; reader.onload = onload; //reader.onloadend = onloadend; reader.readAsDataURL(inputFile); }); }else{ var reader = new FileReader(); nbFiles = elem[0].files.length reader.file = elem[0].files[0]; reader.onload = onload; //reader.onloadend = onloadend; reader.readAsDataURL(elem[0].files[0]); } }); elem.on('click', function() { elem[0].value=null; }); } }; }]).directive('udtBase64File', [function () { return { restrict: 'A', require: 'ngModel', link: function (scope, elem, attrs, ngModel) { var nbFiles = 0, counter = 0, files; var onload = onload = function (e) { if(e.target.result!= undefined && e.target.result != ""){ var udtBase64File = {}; udtBase64File.fullname = e.target.file.name; //Get the extension //console.log("File type "+e.target.file.type); var matchExtension = e.target.file.type.match(/^application\/(.*)/); var matchExtensionText = e.target.file.type.match(/^text\/(.*)/); if(matchExtension && matchExtension.length > 1){ udtBase64File.extension = matchExtension[1]; }else if(matchExtensionText && matchExtensionText.length > 1){ udtBase64File.extension = matchExtensionText[1]; } if(udtBase64File.extension != undefined){ udtBase64File._type = "file"; //Get the base64 without the extension feature var matchBase64 = e.target.result.match(/^.*,(.*)/); udtBase64File.value = matchBase64[1]; files.push(udtBase64File); }else{ alert("This is not an authorized file : "+udtBase64File.fullname); } counter++; } } var onloadend = function(e){ if(nbFiles === counter){ if(attrs.multiple){ scope.$apply(function(scope){ngModel.$setViewValue(files);}); }else{ scope.$apply(function(scope){ngModel.$setViewValue(files[0]);}); } } }; elem.on('change', function() { nbFiles = 0, counter = 0; files = []; if(attrs.multiple){ nbFiles = elem[0].files.length angular.forEach(elem[0].files, function(inputFile){ var reader = new FileReader(); reader.file = inputFile; reader.onload = onload; reader.onloadend = onloadend; reader.readAsDataURL(inputFile); }); }else{ var reader = new FileReader(); nbFiles = elem[0].files.length reader.file = elem[0].files[0]; reader.onload = onload; reader.onloadend = onloadend; reader.readAsDataURL(elem[0].files[0]); } }); elem.on('click', function() { elem[0].value=null; }); } }; }]);;angular.module('ultimateDataTableServices'). directive('udtBtselect', ['$parse', '$document', '$window', '$filter', function($parse,$document, $window, $filter) { //0000111110000000000022220000000000000000000000333300000000000000444444444444444000000000555555555555555000000066666666666666600000000000000007777000000000000000000088888 var BT_OPTIONS_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w]*))\s+in\s+([\s\S]+?)$/; // jshint maxlen: 100 return { restrict: 'A', replace:false, scope:true, template:'<div ng-switch on="isEdit()">' +'<div ng-switch-when="false">' +'<ul class="list-unstyled">' +'<li ng-repeat-start="item in getItems()" ng-if="groupBy(item, $index)" ng-bind="itemGroupByLabel(item)" style="font-weight:bold"></li>' +'<li ng-repeat-end ng-if="item.selected" ng-bind="itemLabel(item)" style="padding-left: 15px;"></li>' +'</ul>' +'</div>' +'<div class="dropdown" ng-switch-when="true">' +'<div class="input-group">' +'<input type="text" style="background:white" ng-class="inputClass" ng-model="selectedLabels" placeholder="{{placeholder}}" title="{{placeholder}}" readonly/>' +'<div class="input-group-btn">' +'<button tabindex="-1" data-toggle="dropdown" class="btn btn-default btn-sm dropdown-toggle" type="button" ng-disabled="isDisabled()" ng-click="open()">' +'<span class="caret"></span>' +'</button>' +'<ul class="dropdown-menu dropdown-menu-right" role="menu">' +'<li ng-if="filter"><input ng-class="inputClass" type="text" ng-click="inputClick($event)" ng-model="filterValue" ng-change="setFilterValue(filterValue)"/></li>' +'<li ng-repeat-start="item in getItems()" ng-if="groupBy(item, $index)" class="divider"></li>' +'<li class="dropdown-header" ng-if="groupBy(item, $index)" ng-bind="itemGroupByLabel(item)"></li>' +'<li ng-repeat-end ng-click="selectItem(item, $event)">' +'<a href="#">' +'<i class="fa fa-check pull-right" ng-show="item.selected"></i>' +'<span class="text" ng-bind="itemLabel(item)" style="margin-right:30px;"></span>' +'</a></li>' +'</ul>' +'</div>' +'</div>' +'</div>' +'</div>' , require: ['?ngModel'], link: function(scope, element, attr, ctrls) { //if ngModel is not defined, we don't need to do anything if (!ctrls[0]) return; scope.inputClass = element.attr("class"); scope.placeholder = attr.placeholder; element.attr("class",''); //remove custom class var ngModelCtrl = ctrls[0], multiple = attr.multiple || false, btOptions = attr.btOptions, editMode = (attr.ngEdit)?$parse(attr.ngEdit):undefined, filter = attr.filter || false; var optionsConfig = parseBtsOptions(btOptions); var items = []; var groupByLabels = {}; var filterValue; var ngFocus = attr.ngFocus; function parseBtsOptions(input){ var match = input.match(BT_OPTIONS_REGEXP); if (!match) { throw new Error( "Expected typeahead specification in form of '_modelValue_ (as _label_)? for _item_ in _collection_'" + " but got '" + input + "'."); } return { itemName:match[4], sourceKey:match[5], source:$parse(match[5]), viewMapper:match[2] || match[1], modelMapper:match[1], groupBy:match[3], groupByGetter:match[3]?$parse(match[3].replace(match[4]+'.','')):undefined }; }; scope.filter = filter; scope.setFilterValue = function(value){ filterValue = value }; scope.open = function(){ if(ngFocus){ $parse(ngFocus)(scope); } }; scope.isDisabled = function(){ return (attr.ngDisabled)?scope.$parent.$eval(attr.ngDisabled):false; }; scope.isEdit = function(){ return (editMode)?editMode(scope):true; }; scope.getItems = function(){ if(scope.isEdit() && scope.filter){ var filter = {}; var getter = $parse(optionsConfig.viewMapper.replace(optionsConfig.itemName+'.','')); getter.assign(filter, filterValue); return $filter('limitTo')($filter('filter')(items, filter), 20); }else{ return items; } }; scope.groupBy = function(item, index){ if(index === 0){ //when several call groupByLabels = {}; } if(optionsConfig.groupByGetter && scope.isEdit()){ if(index === 0 || (index > 0 && optionsConfig.groupByGetter(items[index-1]) !== optionsConfig.groupByGetter(item))){ return true; } }else if(optionsConfig.groupByGetter && !scope.isEdit()){ if(item.selected && !groupByLabels[optionsConfig.groupByGetter(item)]){ groupByLabels[optionsConfig.groupByGetter(item)] = true; return true; } } return false; }; scope.itemGroupByLabel = function(item){ return optionsConfig.groupByGetter(item); } scope.itemLabel = function(item){ return $parse(optionsConfig.viewMapper.replace(optionsConfig.itemName+'.',''))(item); }; scope.itemValue = function(item){ return $parse(optionsConfig.modelMapper.replace(optionsConfig.itemName+'.',''))(item); }; scope.selectItem = function(item, $event){ if(multiple){ var selectedValues = ngModelCtrl.$viewValue || []; var newSelectedValues = []; var itemValue = scope.itemValue(item); var find = false; for(var i = 0; i < selectedValues.length; i ++){ if(selectedValues[i] !== itemValue){ newSelectedValues.push(selectedValues[i]); }else{ find = true; } } if(!find){ newSelectedValues.push(itemValue); } selectedValues = newSelectedValues; ngModelCtrl.$setViewValue(selectedValues); ngModelCtrl.$render(); $event.preventDefault(); $event.stopPropagation(); }else{ if(scope.itemValue(item) !== ngModelCtrl.$viewValue){ ngModelCtrl.$setViewValue(scope.itemValue(item)); }else{ ngModelCtrl.$setViewValue(null); } ngModelCtrl.$render(); } }; scope.inputClick = function($event){ $event.preventDefault(); $event.stopPropagation(); }; scope.$watch(optionsConfig.sourceKey, function(newValue, oldValue){ if(newValue && newValue.length > 0){ items = angular.copy(newValue); render(); } }); ngModelCtrl.$render = render; function render() { var selectedLabels = []; var modelValues = ngModelCtrl.$modelValue || []; if(!angular.isArray(modelValues)){ modelValues = [modelValues]; } if(items.length > 0){ for(var i = 0; i < items.length; i++){ var item = items[i]; item.selected = false; for(var j = 0; j < modelValues.length; j++){ var modelValue = modelValues[j]; if(scope.itemValue(item) === modelValue){ item.selected = true; selectedLabels.push(scope.itemLabel(item)); } } } } scope.selectedLabels = selectedLabels; }; } }; }]);;angular.module('ultimateDataTableServices'). directive("udtCell", function(){ return { restrict: 'A', replace:true, templateUrl:'udt-cell.html', link: function(scope, element, attr) { } }; }).directive("udtEditableCell", function(){ return { restrict: 'A', replace:true, templateUrl:'udt-editableCell.html', link: function(scope, element, attr) { } }; }).directive("udtCellHeader", function(){ return { restrict: 'A', replace:true, templateUrl:'udt-cellHeader.html', link: function(scope, element, attr) { } }; }) .directive("udtCellFilter", function(){ return { restrict: 'A', replace:true, templateUrl:'udt-cellFilter.html', link: function(scope, element, attr) { } }; }) .directive("udtCellEdit", function(){ return { restrict: 'A', replace:true, templateUrl:'udt-cellEdit.html', link: function(scope, element, attr) { } }; }).directive("udtCellRead", ["$parse", function($parse){ return { restrict: 'A', replace:true, templateUrl:'udt-cellRead.html' , link: function(scope, element, attr) { var getDisplayValue = function(column, value, currentScope){ if(column.watch === true && !value.line.group && (column.url === undefined || column.url === null)){ var filter = currentScope.udtTable.getFilter(column); var formatter = currentScope.udtTable.getFormatter(column); scope.$watch("value.data."+column.property+filter+formatter, function(newValue, oldValue) { if ( newValue !== oldValue ) { scope.cellValue = newValue; } }); }else if(column.url != undefined || column.url != null){ var url = $parse(column.url)(value.data); var watchValue = "udtTable.urlCache['"+url+"']."+column.property+filter+formatter; scope.$watch("udtTable.urlCache['"+url+"']", function(newValue, oldValue) { if ( newValue !== oldValue ) { scope.cellValue = currentScope.udtTable.getFinalValue(column, value); } }); } return currentScope.udtTable.getFinalValue(column, value); }; var getDisplayFunction = function(col){ if(angular.isFunction(col.property)){ return col.property(scope.value.data); }else{ return getDisplayValue(col, scope.value, scope); } }; scope.cellValue = getDisplayFunction(scope.col); } }; }]);;angular.module('ultimateDataTableServices'). directive('udtChange', function() { return { require: 'ngModel', link: function(scope, element, attr, ngModelController) { scope.$watch(attr.ngModel, function(newValue, oldValue){ if(newValue !== oldValue){ scope.$evalAsync(attr.udtChange); } }); } }; });;angular.module('ultimateDataTableServices'). directive('udtCompile', ['$compile', function($compile) { // directive factory creates a link function return { restrict: 'A', link: function(scope, element, attrs) { var value = scope.$eval(attrs.udtCompile); element.html(value); $compile(element.contents())(scope); } }; }]);;angular.module('ultimateDataTableServices'). //This directive convert the ngModel value to a view value and then the view value to the ngModel unit value //The value passed to the directive must be an object with displayMeasureValue and saveMeasureValue directive('udtConvertvalue',['udtConvertValueServices','$filter', '$parse', function(udtConvertValueServices, $filter, $parse) { return { priority:1100, require: 'ngModel', link: function(scope, element, attrs, ngModelController) { //init service var convertValues = udtConvertValueServices(); var property = undefined; if(attrs.udtConvertvalue){ property = $parse(attrs.udtConvertvalue)(scope); } ngModelController.$formatters.push(function(value) { var convertedValue = convertValues.convertValue(value, property.saveMeasureValue, property.displayMeasureValue); return convertedValue; }); //view to model ngModelController.$parsers.push(function(value) { value = convertValues.parse(value); if(property != undefined){ value = convertValues.convertValue(value, property.displayMeasureValue, property.saveMeasureValue); } return value; }); } }; }]);;angular.module('ultimateDataTableServices'). //Convert the date in format(view) to a timestamp date(model) directive('udtDateTimestamp', ['$filter', function($filter) { return { require: 'ngModel', link: function(scope, element, attrs, ngModelController) { ngModelController.$formatters.push(function(data) { var convertedData = data; convertedData = $filter('date')(convertedData, Messages("date.format")); return convertedData; }); ngModelController.$parsers.push(function(data) { var convertedData = data; if(moment && convertedData !== ""){ convertedData = moment(data, Messages("date.format").toUpperCase()).valueOf(); }else{ convertedData = null; console.log("mission moment library to convert string to date"); } return convertedData; }); } } }]);;angular.module('ultimateDataTableServices'). //Write in an input or select in a list element the value passed to the directive when the list or the input ngModel is undefined or empty //EXAMPLE: <input type="text" default-value="test" ng-model="x"> directive('udtDefaultValue',['$parse', function($parse) { return { priority:1200, require: 'ngModel', link: function(scope, element, attrs, ngModelController) { var _col = $parse(attrs.udtDefaultValue)(scope); var currentValue = $parse(attrs.ngModel)(scope); //inspire by ngModel.NgModelController.$isEmpty. //not used directly this function because not work in case of inputCheckBox //see ngModel.NgModelController.$isEmpty documentation var isEmpty = function(value) { return (angular.isUndefined(value) || value === '' || value === null); }; var setDefaultValue = function(){ if(_col != null && isEmpty(currentValue)){ if(_col.type === "boolean"){ if(_col.defaultValues === "true" || _col.defaultValues === true){ ngModelController.$setViewValue(true); ngModelController.$render(); }else if(_col.defaultValues === "false" || _col.defaultValues === false){ ngModelController.$setViewValue(true); // hack to insert false value ngModelController.$setViewValue(false); ngModelController.$render(); } }else if(!angular.isFunction(_col.defaultValues)){ ngModelController.$setViewValue(_col.defaultValues); ngModelController.$render(); }else{ var defaultValue = _col.defaultValues(scope.value.data, _col); ngModelController.$setViewValue(defaultValue); ngModelController.$render(); } } } if(_col){ setDefaultValue(); if(angular.isFunction(_col.defaultValues)){ //only watch when function to limit watching scope.$watch(attrs.udtDefaultValue+".defaultValues(value.data,col)", function(newValue, oldValue){ if(newValue !== oldValue){ setDefaultValue(); } }); } } } }; }]);;angular.module('ultimateDataTableServices'). directive('udtForm', function(){ return { restrict: 'A', replace:true, transclude:true, templateUrl:'udt-form.html', link: function(scope, element, attr) { } }; });;angular.module('ultimateDataTableServices').directive('udtHighlight', function() { var component = function(scope, element, attrs) { if (!attrs.highlightClass) { attrs.highlightClass = 'udt-highlight'; } if (!attrs.active) { scope.active = true; } var replacer = function(match, item) { return '<span class="'+attrs.highlightClass+'">'+match+'</span>'; } var tokenize = function(keywords) { keywords = keywords.replace(new RegExp(',$','g'), '').split(','); var i; var l = keywords.length; for (i=0;i<l;i++) { keywords[i] = keywords[i].replace(new RegExp('^ | $','g'), ''); } return keywords; } scope.$watch('keywords', function(newValue, oldValue) { if (!newValue || newValue === '' || !scope.active) { if(scope.udtHighlight !== undefined && scope.udtHighlight !== null) element.html(scope.udtHighlight.replace(/\n/g, '<br />').toString()); return false; } var tokenized = tokenize(newValue); var regex = new RegExp(tokenized.join('|'), 'gmi'); // Find the words var html = scope.udtHighlight.replace(/\n/g, '<br />').toString().replace(regex, replacer); element.html(html); }, true); } return { link: component, replace: false, scope: { active: '=', udtHighlight: '=', keywords: '=' } }; });;angular.module('ultimateDataTableServices'). directive("udtHtmlFilter", function($filter, udtI18n) { return { priority:1000, require: 'ngModel', link: function(scope, element, attrs, ngModelController) { var messagesService = udtI18n(navigator.languages || navigator.language || navigator.userLanguage); ngModelController.$formatters.push(function(data) { var convertedData = data; if(attrs.udtHtmlFilter === "datetime"){ convertedData = $filter('date')(convertedData, messagesService.Messages("datetime.format")); }else if(attrs.udtHtmlFilter === "date"){ convertedData = $filter('date')(convertedData, messagesService.Messages("date.format")); }else if(attrs.udtHtmlFilter === "number"){ convertedData = $filter('number')(convertedData); } return convertedData; }); ngModelController.$parsers.push(function(data) { var convertedData = data; if(attrs.udtHtmlFilter === "number" && null !== convertedData && undefined !== convertedData && angular.isString(convertedData)){ convertedData = convertedData.replace(",",".").replace(/[\u00a0|\s]/g,""); if(!isNaN(convertedData) && convertedData !== ""){ convertedData = convertedData*1; }else if( isNaN(convertedData) || convertedData === ""){ convertedData = null; } }else if(attrs.udtHtmlFilter === "date" && null !== convertedData && undefined !== convertedData && angular.isString(convertedData)){ if(moment && convertedData !== ""){ convertedData = moment(data, messagesService.Messages("date.format").toUpperCase()).valueOf(); }else{ convertedData = null; console.log("mission moment library to convert string to date"); } } //TODO GA date and datetime quiz about timestamps return convertedData; }); } }; });;angular.module('ultimateDataTableServices'). directive('udtMessages', function(){ return { restrict: 'A', replace:true, templateUrl:'udt-messages.html', link: function(scope, element, attr) { } }; });;angular.module('ultimateDataTableServices'). directive('udtTable', function(){ return { restrict: 'A', replace:true, templateUrl:'udt-table.html', link: function(scope, element, attr) { if(scope.udtTable && scope["datatableForm"]){ scope.udtTable.formController = scope["datatableForm"]; } scope.$watch("udtTable", function(newValue, oldValue) { if(newValue && newValue !== oldValue && scope["datatableForm"]){ scope.udtTable.formController = scope["datatableForm"]; } }); var udtTableHelpers = { //todo in udtCell setImage : function(imageData, imageName, imageFullSizeWidth, imageFullSizeHeight) { scope.udtModalImage = {}; scope.udtModalImage.modalImage = imageData; scope.udtModalImage.modalTitle = imageName; var margin = 25; var zoom = Math.min((document.body.clientWidth - margin) / imageFullSizeWidth, 1); scope.udtModalImage.modalWidth = imageFullSizeWidth * zoom; scope.udtModalImage.modalHeight = imageFullSizeHeight * zoom; // in order to scope.udtModalImage.modalLeft = (document.body.clientWidth - scope.udtModalImage.modalWidth)/2; scope.udtModalImage.modalTop = (window.innerHeight - scope.udtModalImage.modalHeight)/2; scope.udtModalImage.modalTop = scope.udtModalImage.modalTop - 50; // height of header and footer }, getTrClass : function(data, line, currentScope){ var udtTable = scope.udtTable; if(line.trClass){ return line.trClass; } else if(angular.isFunction(udtTable.config.lines.trClass)){ return udtTable.config.lines.trClass(data, line); } else if(angular.isString(udtTable.config.lines.trClass)){ return currentScope.$eval(udtTable.config.lines.trClass) || udtTable.config.lines.trClass; } else if(line.group && !udtTable.config.group.showOnlyGroups){ return "active"; } else{ return ''; } }, getTdClass : function(data, col, currentScope){ if(angular.isFunction(col.tdClass)){ return col.tdClass(data); } else if(angular.isString(col.tdClass)){ return currentScope.$eval(col.tdClass) || col.tdClass; }else{ return ''; } }, getThClass : function(col, currentScope){ var clazz = ''; if(col && angular.isFunction(col.thClass)){ clazz = col.thClass(col); } else if(col && angular.isString(col.thClass)){ //we try to evaluation the string against the scope clazz = currentScope.$eval(col.thClass) || col.thClass; } if((col && col.required != undefined && col.required != null) && ((angular.isFunction(col.required) && col.required()) || col.required === true || (angular.isString(col.required) && scope.$eval(col.required)))){ clazz = clazz +' required'; } return clazz; }, select : function(data, line){ var udtTable = scope.udtTable; if(line){ if(udtTable.config.select.active){ //separation of line type group and normal to simplify backward compatibility and avoid bugs //selected is used with edit, remove, save and show button if(!line.group){ if(!line.selected){ line.selected=true; line.trClass="info"; } else{ line.selected=false; line.trClass=undefined; } }else if(line.group && udtTable.config.group.enableLineSelection){ if(!line.groupSelected){ line.groupSelected=true; line.trClass="info"; } else{ line.groupSelected=false; line.trClass=undefined; } } } if (udtTable.config.select.active && angular.isFunction(udtTable.config.select.callback)) { console.warning('select.callback is deprecated. Use mouseevents.clickCallback instead.'); udtTable.config.select.callback(line, data); } else if (udtTable.config.mouseevents.active && angular.isFunction(udtTable.config.mouseevents.clickCallback)) { udtTable.config.mouseevents.clickCallback(line, data); } } }, mouseover : function(data, line){ var udtTable = scope.udtTable; if (udtTable.config.mouseevents.active) { var cb = udtTable.config.mouseevents.overCallback; if (angular.isFunction(cb)) { cb(line, data); } } }, mouseleave : function(data, line){ var udtTable = scope.udtTable; if (udtTable.config.mouseevents.active) { var cb = udtTable.config.mouseevents.leaveCallback; if (angular.isFunction(cb)) { cb(line, data); } } }, getRowSpanValue : function(i,j){ var udtTable = scope.udtTable; if(udtTable.config.mergeCells.active && udtTable.config.mergeCells.rowspans !== undefined){ return udtTable.config.mergeCells.rowspans[i][j]; }else{ return 1; } }, isShowCell : function(col, i, j){ var udtTable = scope.udtTable; var value = !udtTable.isHide(col.id); if(udtTable.config.mergeCells.active && value && udtTable.config.mergeCells.rowspans !== undefined){ value = (udtTable.config.mergeCells.rowspans[i][j] !== 0) } return value; } } scope.udtTableHelpers = udtTableHelpers; } }; });;angular.module('ultimateDataTableServices'). directive("udtTbody", function(){ return { restrict: 'A', link: function(scope, element, attr) { var getEditProperty = function(col, header, filter){ if(header){ return "udtTable.config.edit.columns."+col.id+".value"; } else if(filter){ return "udtTable.searchTerms."+col.property; } else if(angular.isString(col.property)){ return "value.data."+col.property; } else { throw "Error property is not editable !"; } }; var getConvertDirective = function(col, header){ if(col.convertValue !== undefined && col.convertValue !== null && col.convertValue.active === true && col.convertValue.saveMeasureValue !== col.convertValue.displayMeasureValue){ return 'udt-convertvalue="col.convertValue"'; } return ""; } var getOptions = function(col){ if(angular.isString(col.possibleValues)){ return col.possibleValues; }else{ //function return 'col.possibleValues'; } }; var getGroupBy = function(col){ if(angular.isString(col.groupBy)){ return 'group by opt.'+col.groupBy; }else{ return ''; } }; var udtTbodyHelpers = { getEditElement : function(col, header, filter){ var editElement = ''; var ngChange = '"'; var defaultValueDirective = ""; if(header){ //we need used udt-change when we used typehead directive ngChange = '" udt-change="udtTable.updateColumn(col.property, col.id)"'; }else if(filter){ ngChange = '" udt-change="udtTable.localSearch(udtTable.searchTerms)"'; }else if(col.defaultValues){ defaultValueDirective = 'udt-default-value="col"'; }else if(col.choiceInList){ defaultValueDirective= " udt-auto-select"; } var userDirectives = ""; if(col.editDirectives !== undefined){ userDirectives = col.editDirectives; if(angular.isFunction(userDirectives)){ userDirectives = userDirectives(); } } var requiredDirective = ""; if(col.required != undefined && col.required != null && !header){ if(angular.isFunction(col.required) && col.required() || col.required === true){ requiredDirective = 'name="'+col.id+'" ng-required=true'; }else if(angular.isString(col.required)){ requiredDirective = 'name="'+col.id+'" ng-required="'+col.required+'"'; } }else{ requiredDirective = "name='"+col.id+"' "; } if(col.editTemplate){ editElement = col.editTemplate.replace(/#ng-model/g, 'ng-model="'+getEditProperty(col, header, filter)+ngChange+' '+requiredDirective); }else if(col.type === "boolean"){ editElement = '<input class="form-control"' +defaultValueDirective+'type="checkbox" class="input-small" ng-model="'+getEditProperty(col, header, filter)+ngChange+'/>'; }else if (col.type === "textarea") { editElement = '<textarea class="form-control"' + defaultValueDirective + userDirectives + 'ng-model="' + getEditProperty(col, header, filter) + ngChange + '></textarea>'; }else if(col.type === "img"){ editElement= '<input type="file" class="form-control" udt-base64-img ng-model="'+getEditProperty(col, header, filter)+'" id="{{\''+col.id+'_\'+value.line.id}}" '+requiredDirective+' ng-if="'+getEditProperty(col, header, filter)+' === undefined" />' +'<div ng-click="udtTableHelpers.setImage('+getEditProperty(col, header, filter)+'.value,' +getEditProperty(col, header, filter)+'.fullname,' +getEditProperty(col, header, filter)+'.width,' +getEditProperty(col, header, filter)+'.height)" ' +' class="thumbnail" ng-if="'+getEditProperty(col, header, filter)+' !== undefined" >' +' <div data-target="#udtModalImage" role="button" data-toggle="modal" >' +' <a href="#">' +' <img ng-src="data:image/{{'+getEditProperty(col, header, filter)+'.extension}};base64,{{'+getEditProperty(col, header, filter)+'.value}}" width="{{'+getEditProperty(col, header, filter)+'.width*0.1}}" height="{{'+getEditProperty(col, header, filter)+'.height*0.1}}" />' +' </a>' +' </div>' +' </div>' +' <button ng-if="'+getEditProperty(col, header, filter)+' !== undefined" class="btn btn-default btn-xs" ng-click="'+getEditProperty(col, header, filter)+' = undefined" >' +' <i class="fa fa-trash-o"></i>' +' </button>'; if(header){ editElement = ''; } } else if(col.type === "file"){ editElement= '<input ng-if="'+getEditProperty(col, header, filter)+' === undefined" type="file" class="form-control" udt-base64-file ng-model="'+getEditProperty(col, header, filter)+'" id="{{\''+col.id+'_\'+value.line.id}} '+requiredDirective+' />' +'<div ng-if="'+getEditProperty(col, header, filter)+' !== undefined" >' +'<a target="_blank" ng-href="data:application/{{'+getEditProperty(col, header, filter)+'.extension}};base64,{{'+getEditProperty(col, header, filter)+'.value}}">' +'{{'+getEditProperty(col, header, filter)+'.fullname}}' +'</a>' +' </div>' +' <button ng-if="'+getEditProperty(col, header, filter)+' !== undefined" class="btn btn-default btn-xs" ng-click="'+getEditProperty(col, header, filter)+' = undefined" ><i class="fa fa-trash-o"></i>' +' </button>'; if(header){ editElement = ''; } }else if(!col.choiceInList){ //TODO: type='text' because html5 autoformat return a string before that we can format the number ourself editElement = '<input class="form-control" '+requiredDirective+' '+defaultValueDirective+' '+getConvertDirective(col, header)+' udt-html-filter="{{col.type}}" type="text" class="input-small" ng-model="'+getEditProperty(col,header,filter)+ngChange+userDirectives+'/>'; }else if(col.choiceInList){ switch (col.listStyle) { case "radio": editElement = '<label class="radio-inline" ng-repeat="opt in '+getOptions(col)+' track by $index" '+userDirectives+'>' +'<input udt-html-filter="{{col.type}}" type="radio" ng-model="'+getEditProperty(col,header,filter)+ngChange+' ng-value="{{opt.code}}"> {{opt.name}}' +'</label>'; break; case "multiselect": editElement = '<select class="form-control" multiple="true" '+requiredDirective+' '+defaultValueDirective+' ng-options="opt.code '+scope.udtTable.getFormatter(col)+' as opt.name '+getGroupBy(col)+' for opt in '+getOptions(col)+'" '+' ng-model="'+getEditProperty(col,header,filter)+ngChange+userDirectives+'></select>'; break; case "bt-select": editElement = '<div udt-html-filter="{{col.type}}" class="form-control" udt-btselect '+requiredDirective+' '+defaultValueDirective+' placeholder="" bt-dropdown-class="dropdown-menu-right" bt-options="opt.code as opt.name '+getGroupBy(col)+' for opt in '+getOptions(col)+'" '+' ng-model="'+getEditProperty(col,header,filter)+ngChange+userDirectives+'></div>'; break; case "bt-select-filter": editElement = '<div udt-html-filter="{{col.type}}" class="form-control" filter="true" udt-btselect '+requiredDirective+' '+defaultValueDirective+' placeholder="" bt-dropdown-class="dropdown-menu-right" bt-options="opt.code as opt.name '+getGroupBy(col)+' for opt in '+getOptions(col)+'" '+' ng-model="'+getEditProperty(col,header,filter)+ngChange+userDirectives+'></div>'; break; case "bt-select-multiple": editElement = '<div class="form-control" '+requiredDirective+' '+defaultValueDirective+' udt-btselect multiple="true" bt-dropdown-class="dropdown-menu-right" placeholder="" bt-options="opt.code as opt.name '+getGroupBy(col)+' for opt in '+getOptions(col)+'" '+' ng-model="'+getEditProperty(col,header,filter)+ngChange+userDirectives+'></div>'; break; default: editElement = '<select udt-html-filter="{{col.type}}" class="form-control" '+requiredDirective+' '+defaultValueDirective+' ng-options="opt.code '+scope.udtTable.getFormatter(col)+' as opt.name '+getGroupBy(col)+' for opt in '+getOptions(col)+'" '+' ng-model="'+getEditProperty(col,header,filter)+ngChange+userDirectives+'>' + '<option></option>' + '</select>'; break; } }else{ editElement = "Edit Not Defined for col.type !"; } //return '<div class="form-group" ng-class="{\'has-error\': value.line.errors[\''+col.property+'\'] !== undefined}">'+editElement+'<span class="help-block" ng-if="value.line.errors[\''+col.property+'\'] !== undefined">{{value.line.errors["'+col.property+'"]}}<br></span></div>'; return '<div class="form-group" ng-class="udtTbodyHelpers.getValidationClass(\'subForm\'+value.line.id, col)">'+editElement+'<span class="help-block" ng-if="value.line.errors[\''+col.property+'\'] !== undefined">{{value.line.errors["'+col.property+'"]}}<br></span></div>'; }, getValidationClass : function(formName, col){ if(scope.udtTable.config.save.enableValidation && scope.datatableForm[formName] && scope.datatableForm[formName][col.id] && scope.datatableForm[formName][col.id].$invalid){ return 'has-error'; }else{ return undefined; } }, getDisplayElement : function(col){ if(angular.isDefined(col.render) && col.render !== null){ if(angular.isFunction(col.render)){ return '<span udt-compile="udtTable.config.columns[$index].render(value.data, value.line)"></span>'; }else if(angular.isString(col.render)){ return '<span udt-compile="udtTable.config.columns[$index].render"></span>'; } }else{ if(col.type !== "boolean" && col.type !== "img" && col.type !=="file"){ //return '<span udt-highlight="cellValue" keywords="udtTable.searchTerms.$" active="udtTable.config.localSearch.highlight"></span>'; return '<span ng-bind="cellValue"></span>' }else if(col.type === "boolean"){ return '<div ng-switch on="cellValue"><i ng-switch-when="true" class="fa fa-check-square-o"></i><i ng-switch-default class="fa fa-square-o"></i></div>'; }else if(col.type==="img"){ return '<div ng-click="udtTableHelpers.setImage(cellValue.value,cellValue.fullname,cellValue.width,cellValue.height)" class="thumbnail" ng-if="cellValue !== undefined" >' +'<div data-target="#udtModalImage" role="button" data-toggle="modal" ><a href="#"><img ng-src="data:image/{{cellValue.extension}};base64,{{cellValue.value}}" width="{{cellValue.width*0.1}}" height="{{cellValue.height*0.1}}"/></a></div></div>'; }else if(col.type==="file"){ return '<a ng-href="data:application/{{cellValue.extension}};base64,{{cellValue.value}}" download="{{cellValue.fullname}}">' +'{{cellValue.fullname}}' +'</a>'; } else{ return '' } } } }; scope.udtTbodyHelpers = udtTbodyHelpers; } }; });;angular.module('ultimateDataTableServices'). directive('udtTextareaResize', function(){ return { restrict: 'A', require: 'ngModel', replace: false, template: '', link: function(scope, element, attr, ngModel) { var rows = 3; var cols = 35; scope.$watch(ngModel.$modelValue, function() { var value = ngModel.$modelValue; if (value) { var lines = value.split('\n'); rows = Math.max(lines.length, rows); lines.forEach(function(line) { cols = Math.max(cols, line.length); }); attr.$set('cols', cols); attr.$set('rows', rows); } }); } }; }); ;angular.module('ultimateDataTableServices'). directive('udtToolbar', function(){ return { restrict: 'A', replace:true, templateUrl:'udt-toolbar.html' , link: function(scope, element, attr) { } }; }) .directive('udtToolbarBottom', function(){ return { restrict: 'A', replace:true, templateUrl:'udt-toolbar-bottom.html' , link: function(scope, element, attr) { } }; });;angular.module('ultimateDataTableServices'). directive('ultimateDatatable', ['$parse', '$q', '$timeout','$templateCache', function($parse, $q, $timeout, $templateCache){ return { restrict: 'A', replace:true, scope:true, transclude:true, templateUrl:'ultimate-datatable.html', link: function(scope, element, attr) { if(!attr.ultimateDatatable) return; scope.udtTable = $parse(attr.ultimateDatatable)(scope); scope.$watch(attr.ultimateDatatable, function(newValue, oldValue) { if(newValue && (newValue !== oldValue || !scope.udtTable)){ scope.udtTable = newValue; } }); var udtHelpers = { messages : { Messages : function(message,arg){ if(angular.isFunction(message)){ message = message(); } if(arg==null || arg==undefined){ return scope.udtTable.config.messages.transformKey(message); }else{ return scope.udtTable.config.messages.transformKey(message, arg); } } }, getTotalNumberRecords : function(){ if(scope.udtTable.config.group.active && scope.udtTable.config.group.start && !scope.udtTable.config.group.showOnlyGroups){ return scope.udtTable.totalNumberRecords + " - "+scope.udtTable.allGroupResult.length; }else if(scope.udtTable.config.group.active && scope.udtTable.config.group.start && scope.udtTable.config.group.showOnlyGroups){ return (scope.udtTable.allGroupResult)?scope.udtTable.allGroupResult.length:0; }else{ return scope.udtTable.totalNumberRecords; } } }; scope.udtHelpers = udtHelpers; if(!scope.udtTableFunctions){scope.udtTableFunctions = {};} scope.udtTableFunctions.setNumberRecordsPerPage = function(elt){ scope.udtTable.setSpinner(true); $timeout(function(){scope.udtTable.setNumberRecordsPerPage(elt)}).finally(function(){ if(!scope.udtTable.isRemoteMode(scope.udtTable.config.pagination.mode)){ scope.udtTable.computeDisplayResultTimeOut.finally(function(){ scope.udtTable.setSpinner(false); }); } }); }; scope.udtTableFunctions.setPageNumber = function(page){ scope.udtTable.setSpinner(true); $timeout(function(){scope.udtTable.setPageNumber(page)}).finally(function(){ if(!scope.udtTable.isRemoteMode(scope.udtTable.config.pagination.mode)){ scope.udtTable.computeDisplayResultTimeOut.finally(function(){ scope.udtTable.setSpinner(false); }); } }); }; scope.udtTableFunctions.setOrderColumn = function(column){ scope.udtTable.setSpinner(true); $timeout(function(){scope.udtTable.setOrderColumn(column)}).finally(function(){ if(!scope.udtTable.isRemoteMode(scope.udtTable.config.order.mode)){ scope.udtTable.computeDisplayResultTimeOut.finally(function(){ scope.udtTable.setSpinner(false); }); } }); }; scope.udtTableFunctions.setGroupColumn = function(column){ scope.udtTable.setSpinner(true); $timeout(function(){scope.udtTable.setGroupColumn(column)}).finally(function(){ scope.udtTable.computeDisplayResultTimeOut.finally(function(){ scope.udtTable.setSpinner(false); }); }); }; scope.udtTableFunctions.updateShowOnlyGroups = function(){ scope.udtTable.setSpinner(true); $timeout(function(){scope.udtTable.updateShowOnlyGroups()}).finally(function(){ scope.udtTable.computeDisplayResultTimeOut.finally(function(){ scope.udtTable.setSpinner(false); }); }); }; scope.udtTableFunctions.cancel = function(){ scope.udtTable.setSpinner(true); $timeout(function(){scope.udtTable.cancel()}).finally(function(){ scope.udtTable.computeDisplayResultTimeOut.finally(function(){ scope.udtTable.setSpinner(false); }); }); }; scope.udtTableFunctions.setEdit = function(column){ scope.udtTable.setSpinner(true); $timeout(function(){scope.udtTable.setEdit(column)}).finally(function(){ scope.udtTable.setSpinner(false); }); }; scope.udtTableFunctions.setHideColumn = function(column){ scope.udtTable.setSpinner(true); $timeout(function(){scope.udtTable.setHideColumn(column)}).finally(function(){ scope.udtTable.setSpinner(false); }); }; scope.udtTableFunctions.exportCSV = function(exportType){ scope.udtTable.setSpinner(true); $timeout(function(){scope.udtTable.exportCSV(exportType)}).finally(function(){ scope.udtTable.setSpinner(false); }); }; } }; }]);;angular.module('ultimateDataTableServices'). filter('udtCollect', ['$parse','$filter',function($parse,$filter) { return function(array, key, unique, keyUnique, context) { if (!array || array.length === 0)return undefined; if (!angular.isArray(array) && (angular.isObject(array) || angular.isNumber(array) || angular.isString(array) || angular.isDate(array))) array = [array]; else if(!angular.isArray(array)) throw "input is not an array, object, number or string !"; if(key && !angular.isString(key))throw "key is not valid, only string is authorized"; var possibleValues = []; angular.forEach(array, function(element){ if (angular.isObject(element)) { var currentValue = $parse(key)(element, context); if(undefined !== currentValue && null !== currentValue){ //Array.prototype.push.apply take only arrays if(angular.isArray(currentValue)){ possibleValues = possibleValues.concat(currentValue); }else{ possibleValues.push(currentValue); } } }else if (!key && angular.isObject(value)){ throw "missing key !"; } }); if(unique){ possibleValues = $filter('udtUnique')(possibleValues, keyUnique, context); } return possibleValues; }; }]);;angular.module('ultimateDataTableServices'). filter('udtConvert', ['udtConvertValueServices', function(udtConvertValueServices){ return function(input, property){ var convertValues = udtConvertValueServices(); if(property != undefined){ input = convertValues.convertValue(input, property.saveMeasureValue, property.displayMeasureValue); } return input; } }]);;angular.module('ultimateDataTableServices'). filter('udtCount', ['$parse',function($parse) { return function(array, key, distinct, context) { if (!array || array.length === 0)return undefined; if (!angular.isArray(array) && (angular.isObject(array) || angular.isNumber(array) || angular.isString(array) || angular.isDate(array))) array = [array]; else if(!angular.isArray(array)) throw "input is not an array, object, number or string !"; if(key && !angular.isString(key))throw "key is not valid, only string is authorized"; var possibleValues = []; angular.forEach(array, function(element){ if (angular.isObject(element)) { var currentValue = $parse(key)(element, context); if(angular.isArray(currentValue) && currentValue.length === 1)currentValue = currentValue[0]; if(distinct && undefined !== currentValue && null !== currentValue && possibleValues.indexOf(currentValue) === -1){ possibleValues.push(currentValue); }else if(!distinct && undefined !== currentValue && null !== currentValue){ possibleValues.push(currentValue); } }else if (!key && angular.isObject(value)){ throw "missing key !"; } }); return possibleValues.length; }; }]);;angular.module('ultimateDataTableServices'). filter('udtUnique', ['$parse', function($parse) { return function (collection, property, context) { var isDefined = angular.isDefined, isUndefined = angular.isUndefined, isFunction = angular.isFunction, isString = angular.isString, isNumber = angular.isNumber, isObject = angular.isObject, isArray = angular.isArray, forEach = angular.forEach, extend = angular.extend, copy = angular.copy, equals = angular.equals; if(!isArray(collection) && !isObject(collection)){ return collection; } /** * get an object and return array of values * @param object * @returns {Array} */ function toArray(object) { var i = -1, props = Object.keys(object), result = new Array(props.length); while(++i < props.length) { result[i] = object[props[i]]; } return result; } collection = (angular.isObject(collection)) ? toArray(collection) : collection; if (isUndefined(property)) { return collection.filter(function (elm, pos, self) { return self.indexOf(elm) === pos; }) } //store all unique members var uniqueItems = [], get = $parse(property); return collection.filter(function (elm) { var prop = get(elm, context); if(some(uniqueItems, prop)) { return false; } uniqueItems.push(prop); return true; }); //checked if the unique identifier is already exist function some(array, member) { /* if(isUndefined(member)) { return false; } */ return array.some(function(el) { return equals(el, member); }); } } }]);;angular.module('ultimateDataTableServices'). factory('udtConvertValueServices', [function() { var constructor = function($scope){ var udtConvertValueServices = { //Convert the value in inputUnit to outputUnit if the units are different convertValue : function(value, inputUnit, outputUnit, precision){ if(inputUnit !== outputUnit && !isNaN(value) && null !== value){ var convert = this.getConversion(inputUnit,outputUnit); if(convert != undefined && !angular.isFunction(convert)){ value = value * convert; if(precision !== undefined){ value = value.toPrecision(precision); } }else if(convert === undefined || convert === null){ throw "Error: Unknown Conversion "+inputUnit+" to "+outputUnit; return undefined; } } return value; }, //Get the multiplier to convert the value getConversion : function(inputUnit, outputUnit){ if((inputUnit === '\u00B5g' && outputUnit === 'ng') || (inputUnit === 'ml' && outputUnit === '\u00B5l') || (inputUnit === 'pM' && outputUnit === 'nM')){ return (1/1000); }else if((inputUnit === 'ng' && outputUnit === '\u00B5g') || (inputUnit === '\u00B5l' && outputUnit === 'ml') || (inputUnit === 'nM' && outputUnit === 'pM')){ return 1000; }else if ((inputUnit === 'mM' && outputUnit === 'nM')){ return 1000000; }else if ((inputUnit === 'nM' && outputUnit === 'mM')){ return 1/1000000; } return undefined; }, parse : function(value){ var valueToConvert = value; if(valueToConvert !== null && valueToConvert !== undefined && !angular.isNumber(valueToConvert)){ var valueConverted = value.replace(/\s+/g,"").replace(',','.'); valueConverted = parseFloat(valueConverted); return valueConverted; } return value; } }; return udtConvertValueServices; }; return constructor; }]);;angular.module('ultimateDataTableServices'). /* A I18n service, that manage internal translation in udtI18n * follow the http://tools.ietf.org/html/rfc4646#section-2.2.4 spec * preferedLanguageVar can be a string or an array of string * https://developer.mozilla.org/en-US/docs/Web/API/NavigatorLanguage */ factory('udtI18n', [function() { var constructor = function(preferedLanguageVar) { var udtI18n = { init: function() { this.preferedLanguage = 'en'; // If preferedLanguageVar is undefined we keep the defaultLanguage if(!preferedLanguageVar) { return false; } var preferedLanguage = []; if(!Array.isArray(preferedLanguageVar)) { preferedLanguage.push(preferedLanguageVar); } else { preferedLanguage = preferedLanguageVar.slice(); } preferedLanguage.some(function(language) { // We first try to find the entire language string // Primary Language Subtag with Extended Language Subtags if(this.translationExist(language)) { this.preferedLanguage = language; return true; } // Then we try with only Primary Language Subtag var splitedLanguages = language.split('-'); if(splitedLanguages.length > 1) { var primaryLanguageSubtag = splitedLanguages[0]; if(this.translationExist(primaryLanguageSubtag)) { this.preferedLanguage = primaryLanguageSubtag; return true; } } }, this); }, translationExist: function(language) { return this.translateTable[language] !== undefined; }, translateTable : { "fr": { "result":"R\u00e9sultats", "date.format":"dd/MM/yyyy", "datetime.format":"dd/MM/yyyy HH:mm:ss", "datatable.button.selectall":"Tout s\u00e9lectionner (page courante)", "datatable.button.unselectall" :"Tout d\u00e9lectionner (page courante)", "datatable.button.cancel":"Annuler", "datatable.button.hide":"Cacher", "datatable.button.show":"Afficher D\u00e9tails", "datatable.button.edit":"Editer", "datatable.button.sort":"Trier", "datatable.button.save":"Sauvegarder", "datatable.button.add":"Ajouter", "datatable.button.remove":"Supprimer", "datatable.button.localSearch":"Rechercher", "datatable.button.resetLocalSearch":"Annuler", "datatable.button.length" : "Taille ({0})", "datatable.totalNumberRecords" : "{0} R\u00e9sultat(s)", "datatable.button.exportCSV" : "Export CSV", "datatable.msg.success.save" : "Toutes les sauvegardes ont r\u00e9ussi.", "datatable.msg.error.save" : "Il y a {0} sauvegarde(s) en erreur.", "datatable.msg.success.remove" : "Toutes les suppressions ont r\u00e9ussi.", "datatable.msg.error.remove":" Il y a {0} suppression(s) en erreur.", "datatable.remove.confirm" : "Pouvez-vous confirmer la suppression ?", "datatable.export.sum" : "(Somme)", "datatable.export.average" : "(Moyenne)", "datatable.export.unique" :"(Valeur uniq.)", "datatable.export.count" : "(Nb. valeurs)", "datatable.export.countDistinct" :"(Nb. valeurs diff\u00e9rentes)", "datatable.export.collect" :"(Liste valeurs)", "datatable.export.collectDistinct" :"(Liste valeurs diff\u00e9rentes)", "datatable.export.yes" : "Oui", "datatable.export.no" : "Non", "datatable.button.group" : "Grouper / D\u00e9grouper", "datatable.button.generalGroup" : "Grouper toute la s\u00e9lection", "datatable.button.basicExportCSV" : "Exporter toutes les lignes", "datatable.button.groupedExportCSV" : "Exporter les lignes group\u00e9es", "datatable.button.showOnlyGroups" : "Voir uniquement les groupes", "datatable.button.top" : "Aller au d\u00e9but du tableau" }, "en": { "result":"Results", "date.format":"MM/dd/yyyy", "datetime.format":"MM/dd/yyyy HH:mm:ss", "datatable.button.selectall":"Select all (current page)", "datatable.button.unselectall" :"Deselect all (current page)", "datatable.button.cancel":"Cancel", "datatable.button.hide":"Hide", "datatable.button.show":"Show Details", "datatable.button.edit":"Edit", "datatable.button.sort":"Order", "datatable.button.save":"Save", "datatable.button.add":"Add", "datatable.button.remove":"Remove", "datatable.button.localSearch":"Search", "datatable.button.resetLocalSearch":"Cancel", "datatable.button.length" : "Size ({0})", "datatable.totalNumberRecords" : "{0} Result(s)", "datatable.button.exportCSV" : "CSV Export", "datatable.msg.success.save" : "All backups are successful.", "datatable.msg.error.save" : "There are {0} backup(s) in error.", "datatable.msg.success.remove" : "All the deletions are successful.", "datatable.msg.error.remove":" There are {0} deletion(s) in error.", "datatable.remove.confirm" : "Can you confirm the delete ?", "datatable.export.sum" : "(Sum)", "datatable.export.average" : "(Average)", "datatable.export.unique" :"(Single value)", "datatable.export.count" : "(Nb. of values)", "datatable.export.countDistinct" :"(Num. of distinct occurrence)", "datatable.export.collect" :"(List of values)", "datatable.export.collectDistinct" :"(List of different values)", "datatable.export.yes" : "Yes", "datatable.export.no" : "No", "datatable.button.group" : "Group / Ungroup", "datatable.button.generalGroup" : "Group All selected lines", "datatable.button.basicExportCSV" : "Export all lines", "datatable.button.groupedExportCSV" : "Export only grouped lines", "datatable.button.showOnlyGroups" : "See only group", "datatable.button.top" : "Go to the top" }, "nl": { "result": "Resultaten", "date.format": "dd/MM/yyyy", "datetime.format": "dd/MM/yyyy HH:mm:ss", "datatable.button.selectall": "Selecteer alles", "datatable.button.unselectall": "Deselecteer alles", "datatable.button.cancel": "Annuleren", "datatable.button.hide": "Verberg", "datatable.button.show": "Toon details", "datatable.button.edit": "Bewerk", "datatable.button.sort": "Sorteer", "datatable.button.save": "Opslaan", "datatable.button.add": "Toevoegen", "datatable.button.remove": "Verwijderen", "datatable.button.localSearch": "Zoek", "datatable.button.resetLocalSearch": "Annuleer", "datatable.button.length": "Grote ({0})", "datatable.totalNumberRecords": "{0} Resultaten", "datatable.button.exportCSV": "CSV Export", "datatable.msg.success.save": "Opslag is succesvol", "datatable.msg.error.save": "Er zijn {0} backup(s) met een fout.", "datatable.msg.success.remove": "Alles is succesvol verwijderd.", "datatable.msg.error.remove": " Er zijn {0} verwijderingen met een fout.", "datatable.remove.confirm": "Bevestigd u de verwijdering?", "datatable.export.sum": "(Som)", "datatable.export.average": "(Gemiddeld)", "datatable.export.unique":"(Enkele waarde)", "datatable.export.count" : "(Aantal waarden)", "datatable.export.countDistinct": "(Aantal unieke waarden)", "datatable.export.collect" :"(Lijst met waarden)", "datatable.export.collectDistinct" :"(Lijst met verschillende waarden)", "datatable.export.yes": "Ja", "datatable.export.no": "Nee", "datatable.button.group": "Groeperen / Degroeperen", "datatable.button.generalGroup": "Groepeer alle geselecteerde regels", "datatable.button.basicExportCSV": "Exporteer alle regels", "datatable.button.groupedExportCSV": "Exporteer alleen de gegroepeerde regels", "datatable.button.showOnlyGroups": "Toon alleen de groep", "datatable.button.top" : "Ga naar de top" } }, //Translate the key with the correct language Messages : function(key) { var translatedString = this.translateTable[this.preferedLanguage][key]; if(translatedString === undefined) { return key; } for (var i = 1; i < arguments.length; i++) { translatedString = translatedString.replace("{"+(i-1)+"}", arguments[i]); } return translatedString; } }; udtI18n.init(); return udtI18n; }; return constructor; }]); ;"use strict"; angular.module('ultimateDataTableServices'). run(['$templateCache', function($templateCache) { $templateCache.put('ultimate-datatable.html', '<div name="datatable" class="datatable" ng-if="udtTable">' + '<div ng-transclude/>' + '<div id="udt-top-{{udtTable.config.name}}"/>' + '<div udt-toolbar ng-if="udtTable.isShowToolbar()"/>' + '<div udt-messages ng-if="udtTable.config.messages.active"/>' + '<div udt-table/>' + '<div udt-toolbar-bottom ng-show="udtTable.isShowToolbarBottom()"/>' +'</div>'); }]) .run(['$templateCache', function($templateCache) { $templateCache.put('udt-table.html', '<div name="udt-table" class="row">' + '<div class="col-md-12 col-lg-12">' + '<div class="inProgress" ng-if="udtTable.config.spinner.start">' + '<button class="btn btn-primary btn-lg">' + '<i class="fa fa-spinner fa-spin fa-5x"></i>' + '</button>' + '</div>' + '<form name="datatableForm" class="form-inline">' + '<table class="table table-condensed table-hover table-bordered">' + '<thead>' + '<tr ng-repeat="(key,headers) in udtTable.getExtraHeaderConfig()">' + '<th colspan="{{header.colspan}}" ng-repeat="header in headers" class="xheader">' + '<span ng-bind="udtHelpers.messages.Messages(header.label)"/>' + '</th>' + '</tr>' + '<tr>' + '<th ng-if="udtTable.isShowLineEditButton()" ng-class="udtTableHelpers.getThClass(column, this)"><!-- Edit button column --></th>' + '<th id="{{column.id}}" ng-repeat="column in udtTable.getColumnsConfig()" ng-model="column" ng-if="!udtTable.isHide(column.id)" ng-class="udtTableHelpers.getThClass(column, this)">' + '<div udt-compile="column.headerTpl" class="pull-left"></div>' + '<div class="btn-group pull-right">' + '<button class="btn btn-xs" ng-click="udtTableFunctions.setEdit(column)" ng-if="udtTable.isShowButton(\'edit\', column)" ng-disabled="!udtTable.canEdit()" data-toggle="tooltip" title="{{udtHelpers.messages.Messages(\'datatable.button.edit\')}}"><i class="fa fa-edit"></i></button>' + '<button class="btn btn-xs" ng-click="udtTableFunctions.setOrderColumn(column)" ng-if="udtTable.isShowButton(\'order\', column)" ng-disabled="!udtTable.canOrder()" data-toggle="tooltip" title="{{udtHelpers.messages.Messages(\'datatable.button.sort\')}}"><i ng-class="udtTable.getOrderColumnClass(column.id)"></i></button>' + '<button class="btn btn-xs" ng-click="udtTableFunctions.setGroupColumn(column)" ng-if="udtTable.isShowButton(\'group\', column)" ng-disabled="udtTable.isEmpty()" data-toggle="tooltip" title="{{udtHelpers.messages.Messages(\'datatable.button.group\')}}"><i ng-class="udtTable.getGroupColumnClass(column.id)"></i></button>' + '<button class="btn btn-xs" ng-click="udtTableFunctions.setHideColumn(column)" ng-if="udtTable.isShowButton(\'hide\', column)" data-toggle="tooltip" title="{{udtHelpers.messages.Messages(\'datatable.button.hide\')}}"><i class="fa fa-eye-slash"></i></button>' + '</div>' + '</th>' + '</tr>' + '</thead>' + '<tbody udt-tbody>' + '<tr ng-if="udtTable.config.localSearch.columnMode && !udtTable.config.edit.start" class="filter">' + '<td ng-repeat="col in udtTable.config.columns" ng-if="!udtTable.isHide(col.id)">' + '<div ng-if="col.localSearch" udt-cell-filter/>' + '</td>' + '</tr>' + '<tr ng-if="udtTable.isEdit()" class="editParent">' + '<td ng-repeat="col in udtTable.config.columns" ng-if="!udtTable.isHide(col.id)">' + '<div udt-cell-header/>' + '</td>' + '</tr>' + '<tr ng-form name="subForm{{value.line.id}}" ng-repeat="value in udtTable.displayResult" ng-click="udtTableHelpers.select(value.data, value.line)" ng-mouseover="udtTableHelpers.mouseover(value.data, value.line)" ng-mouseleave="udtTableHelpers.mouseleave(value.data, value.line)" ng-class="udtTableHelpers.getTrClass(value.data, value.line, this)">' + '<td ng-if="udtTable.isShowLineEditButton()">' + '<button class="btn btn-default ng-scope" ng-click="udtTable.setEdit()" ng-show="!udtTable.isEdit(null, value.line)" ng-disabled="!udtTable.canEdit()" data-toggle="tooltip" title="Edit"><i class="fa fa-edit"></i></button>' + '<button class="btn btn-default ng-scope" ng-click="udtTable.save()" ng-show="udtTable.isEdit(null, value.line)" ng-disabled="!udtTable.canSave()" data-toggle="tooltip" title="Save"><i class="fa fa-save"></i></button>' + '</td>' + '<td ng-repeat="col in udtTable.config.columns" ng-if="udtTableHelpers.isShowCell(col, $parent.$index, $index)" ng-class="udtTableHelpers.getTdClass(value.data, col, this)" rowspan="{{udtTableHelpers.getRowSpanValue($parent.$parent.$index, $parent.$index)}}">' + '<div udt-cell/>' + '</td>' + '</tr>' + '</tbody>' + '</table>' + '</form>' + '</div>' +'<div id="udtModalImage" class="modal fade" tabindex="-1" role="dialog"' +' aria-labelledby="modalImageLabel" aria-hidden="true">' +' <div class="modal-dialog" style="margin-left:{{udtModalImage.modalLeft}}px">' +' <div class="modal-content" style="width:{{udtModalImage.modalWidth+2}}px">' +' <div class="modal-header">' +' <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>' +' <h3 class="modal-title">{{udtModalImage.modalTitle}}</h3> ' +' </div>' +' <div class="modal-body" style="padding:0px">' +' <img ng-src="data:image/png;base64,{{udtModalImage.modalImage}}" style="width:{{udtModalImage.modalWidth}}px; height:{{udtModalImage.modalHeight}}px;" />' +' </div>' +' <div class="modal-footer">' +' </div>' +' </div>' +' </div>' +'</div>' +'</div>'); }]) .run(['$templateCache', function($templateCache) { $templateCache.put('udt-cell.html', '<div ng-switch on="col.edit">' + '<div ng-switch-when="true" udt-editable-cell></div>' + '<div ng-switch-default udt-cell-read></div>' +'</div>'); }]) .run(['$templateCache', function($templateCache) { $templateCache.put('udt-editableCell.html', '<div ng-switch on="udtTable.isEdit(col.id, value.line)">' + '<div ng-switch-when="true" >' + '<div udt-cell-edit></div>' + '</div>' + '<div ng-switch-default udt-cell-read></div>' +'</div>'); }]) .run(['$templateCache', function($templateCache) { $templateCache.put('udt-cellRead.html', '<div udt-compile="udtTbodyHelpers.getDisplayElement(col)"></div>'); }]) .run(['$templateCache', function($templateCache) { $templateCache.put('udt-cellEdit.html', '<div udt-compile="udtTbodyHelpers.getEditElement(col)"></div>'); }]) .run(['$templateCache', function($templateCache) { $templateCache.put('udt-cellFilter.html', '<div udt-compile="udtTbodyHelpers.getEditElement(col, false, true)"></div>'); }]) .run(['$templateCache', function($templateCache) { $templateCache.put('udt-cellHeader.html', '<div ng-if="col.edit" ng-switch on="udtTable.isEdit(col.id)">' + '<div ng-switch-when="true" udt-compile="udtTbodyHelpers.getEditElement(col, true)"></div>' + '<div ng-switch-default></div>' +'</div>'); }]) .run(['$templateCache', function($templateCache) { $templateCache.put('udt-messages.html', '<div name="udt-messages" class="row">' + '<div class="col-md-12 col-lg-12">' + '<div ng-class="udtTable.config.messages.clazz" ng-if="udtTable.config.messages.text !== undefined">' + '<strong>{{udtTable.config.messages.text}}</strong>' + '</div>' + '</div>' +'</div>'); }]) .run(['$templateCache', function($templateCache) { $templateCache.put('udt-form.html', '<div name="udt-form" class="row"><div class="col-md-12 col-lg-12" ng-transclude/></div>'); }]) .run(['$templateCache', function($templateCache) { $templateCache.put('udt-toolbar.html', '<div name="udt-toolbar" class="row margin-bottom-3">' + '<div class="col-md-12 col-lg-12">' + '<div class="btn-toolbar pull-left" name="udt-toolbar-buttons" ng-if="udtTable.isShowToolbarButtons()">' + '<div class="btn-group" ng-switch on="udtTable.config.select.isSelectAll">' + '<button class="btn btn-default" ng-disabled="udtTable.isEmpty()" ng-click="udtTable.selectAll(true)" ng-show="udtTable.isShowButton(\'select\')" ng-switch-when="false" data-toggle="tooltip" title="{{udtHelpers.messages.Messages(\'datatable.button.selectall\')}}">' + '<i class="fa fa-check-square"></i>' + '<span ng-if="!udtTable.isCompactMode()"> {{udtHelpers.messages.Messages(\'datatable.button.selectall\')}}</span>' + '</button>' + '<button class="btn btn-default" ng-disabled="udtTable.isEmpty()" ng-click="udtTable.selectAll(false)" ng-show="udtTable.isShowButton(\'select\')" ng-switch-when="true" data-toggle="tooltip" title="{{udtHelpers.messages.Messages(\'datatable.button.unselectall\')}}">' + '<i class="fa fa-square"></i>' + '<span ng-if="!udtTable.isCompactMode()"> {{udtHelpers.messages.Messages(\'datatable.button.unselectall\')}}</span>' + '</button>' + '<button class="btn btn-default" ng-click="udtTableFunctions.cancel()" ng-if="udtTable.isShowButton(\'cancel\')" data-toggle="tooltip" title="{{udtHelpers.messages.Messages(\'datatable.button.cancel\')}}">' + '<i class="fa fa-undo"></i>' + '<span ng-if="!udtTable.isCompactMode()"> {{udtHelpers.messages.Messages(\'datatable.button.cancel\')}}</span>' + '</button>' + '<button class="btn btn-default" ng-click="udtTable.show()" ng-disabled="!udtTable.isSelect()" ng-if="udtTable.isShowButton(\'show\')" data-toggle="tooltip" title="{{udtHelpers.messages.Messages(\'datatable.button.show\')}}">' + '<i class="fa fa-thumb-tack"></i>' + '<span ng-if="!udtTable.isCompactMode()"> {{udtHelpers.messages.Messages(\'datatable.button.show\')}}</span>' + '</button>' + '</div>' + '<div class="btn-group" ng-if="udtTable.isShowCRUDButtons()">' + '<button class="btn btn-default" ng-click="udtTableFunctions.setEdit()" ng-disabled="!udtTable.canEdit()" ng-if="udtTable.isShowButton(\'edit\')" data-toggle="tooltip" title="{{udtHelpers.messages.Messages(\'datatable.button.edit\')}}">' + '<i class="fa fa-edit"></i>' + '<span ng-if="!udtTable.isCompactMode()"> {{udtHelpers.messages.Messages(\'datatable.button.edit\')}}</span>' + '</button>' + '<button class="btn btn-default" ng-click="udtTable.save()" ng-disabled="!udtTable.canSave()" ng-if="udtTable.isShowButton(\'save\')" data-toggle="tooltip" title="{{udtHelpers.messages.Messages(\'datatable.button.save\')}}" >' + '<i class="fa fa-save"></i>' + '<span ng-if="!udtTable.isCompactMode()"> {{udtHelpers.messages.Messages(\'datatable.button.save\')}}</span>' + '</button>' + '<button class="btn btn-default" ng-click="udtTable.remove()" ng-disabled="!udtTable.canRemove()" ng-if="udtTable.isShowButton(\'remove\')" data-toggle="tooltip" title="{{udtHelpers.messages.Messages(\'datatable.button.remove\')}}">' + '<i class="fa fa-trash-o"></i>' + '<span ng-if="!udtTable.isCompactMode()"> {{udtHelpers.messages.Messages(\'datatable.button.remove\')}}</span>' + '</button>' + '</div>' + '<div class="btn-group" ng-if="udtTable.config.add.active && udtTable.config.add.showButton">' + '<button class="btn btn-default" ng-click="udtTable.addBlankLine()" title="{{udtHelpers.messages.Messages(\'datatable.button.add\')}}">' + '<i class="fa fa-plus"></i>' + '<span ng-if="!udtTable.isCompactMode()"> {{udtHelpers.messages.Messages(\'datatable.button.add\')}}</span>' + '</button>' + '</div>' + '<div class="btn-group" ng-if="udtTable.isShowExportCSVButton()" ng-switch on="udtTable.config.group.active">' + '<button ng-switch-when="false" class="btn btn-default" ng-click="udtTableFunctions.exportCSV(\'all\')" ng-disabled="!udtTable.canExportCSV()" data-toggle="tooltip" title="{{udtHelpers.messages.Messages(\'datatable.button.exportCSV\')}}">' + '<i class="fa fa-file-text-o"></i>' + '<span ng-if="!udtTable.isCompactMode()"> {{udtHelpers.messages.Messages(\'datatable.button.basicExportCSV\')}}</span>' + '</button>' + '<button ng-switch-when="true" class="btn btn-default dropdown-toggle" data-toggle="dropdown" ng-disabled="!udtTable.canExportCSV()" title="{{udtHelpers.messages.Messages(\'datatable.button.exportCSV\')}}">' + '<i class="fa fa-file-text-o"></i> ' + '<span ng-if="!udtTable.isCompactMode()"> {{udtHelpers.messages.Messages(\'datatable.button.exportCSV\')}}</span>' + '<span class="caret"/>' + '</button>' + '<ul class="dropdown-menu" ng-switch-when="true">' + '<li>' + '<a href="" ng-click="udtTableFunctions.exportCSV(\'all\')">' + '<i class="fa fa-file-text-o"></i> {{udtHelpers.messages.Messages(\'datatable.button.basicExportCSV\')}}' + '</a>' + '</li>' + '<li>' + '<a href="" ng-click="udtTableFunctions.exportCSV(\'groupsOnly\')">' + '<i class="fa fa-file-text-o"></i> {{udtHelpers.messages.Messages(\'datatable.button.groupedExportCSV\')}}' + '</a>' + '</li>' + '</ul>' + '</div>' + '<div class="btn-group" ng-if="udtTable.isShowButton(\'group\')">' + '<button data-toggle="dropdown" class="btn btn-default dropdown-toggle" ng-disabled="udtTable.isEmpty()" data-toggle="tooltip" title="{{udtHelpers.messages.Messages(\'datatable.button.group\')}}">' + '<i class="fa fa-bars"></i> ' + '<span ng-if="!udtTable.isCompactMode()"> {{udtHelpers.messages.Messages(\'datatable.button.group\')}} </span>' + '<span class="caret" />' + '</button>' + '<ul class="dropdown-menu">' + '<li ng-repeat="column in udtTable.getGroupColumns()">' + '<a href="" ng-click="udtTableFunctions.setGroupColumn(column)" ng-switch on="!udtTable.isGroup(column.id)">' + '<i class="fa fa-bars" ng-switch-when="true"></i>' + '<i class="fa fa-outdent" ng-switch-when="false"></i> ' + '<span ng-bind="udtHelpers.messages.Messages(column.header)"/>' + '</a>' + '</li>' + '<li class="divider"></li>' + '<li>' + '<a href="" ng-click="udtTable.setGroupColumn(\'all\')" ng-switch on="!udtTable.isGroup(\'all\')">' + '<i class="fa fa-bars" ng-switch-when="true"></i>' + '<i class="fa fa-outdent" ng-switch-when="false"></i> ' + '<span ng-bind="udtHelpers.messages.Messages(\'datatable.button.generalGroup\')"/>' + '</a>' + '</li>' + '<li class="dropdown-header" style="font-size:12px;color:#333">' + '<div class="checkbox">' + '<label>' + '<input type="checkbox" ng-model="udtTable.config.group.showOnlyGroups" ng-click="udtTableFunctions.updateShowOnlyGroups()"/>{{udtHelpers.messages.Messages(\'datatable.button.showOnlyGroups\')}}' + '</label>' + '</div>' + '</li>' + '</ul>' + '</div>' + '<div class="btn-group" ng-if="udtTable.isShowHideButtons()">' + '<button data-toggle="dropdown" class="btn btn-default dropdown-toggle" data-toggle="tooltip" title="{{udtHelpers.messages.Messages(\'datatable.button.hide\')}}">' + '<i class="fa fa-eye-slash"></i> ' + '<span ng-if="!udtTable.isCompactMode()"> {{udtHelpers.messages.Messages(\'datatable.button.hide\')}} </span>' + '<span class="caret"></span>' + '</button>' + '<ul class="dropdown-menu">' + '<li ng-repeat="column in udtTable.getHideColumns()">' + '<a href="" ng-click="udtTableFunctions.setHideColumn(column)" ng-switch on="udtTable.isHide(column.id)">' + '<i class="fa fa-eye" ng-switch-when="true"></i>' + '<i class="fa fa-eye-slash" ng-switch-when="false"></i> ' + '<span ng-bind="udtHelpers.messages.Messages(column.header)"/>' + '</a>' + '</li>' + '</ul>' + '</div>' + '<div class="btn-group" ng-if="udtTable.isShowOtherButtons() && !udtTable.config.otherButtons.complex" udt-compile="udtTable.config.otherButtons.template"></div>' + '<div style="display:inline-block; margin-left:5px" ng-if="udtTable.isShowOtherButtons() && udtTable.config.otherButtons.complex" udt-compile="udtTable.config.otherButtons.template"></div>' + '</div>' + '<div class="col-xs-2 .col-sm-3 col-md-3 col-lg-3" name="udt-toolbar-filter" ng-if="udtTable.config.localSearch.active === true">' + '<div class="col-xs-12 .col-sm-6 col-md-7 col-lg-8 input-group" ng-if="udtTable.isCompactMode()">' + '<input class="form-control input-compact" udt-change="udtTable.localSearch(udtTable.searchTerms)" type="text" ng-model="udtTable.searchTerms.$" ng-keydown="$event.keyCode==13 ? udtTable.localSearch(udtTable.searchTerms) : \'\'">' + '<span class="input-group-btn">' + '<button ng-if="udtTable.config.localSearch.active === true" class="btn btn-default search-button" ng-click="udtTable.localSearch(udtTable.searchTerms)" title="{{udtHelpers.messages.Messages(\'datatable.button.localSearch\')}}">' + '<i class="fa fa-search"></i>' + '</button>' + '<button ng-if="udtTable.config.localSearch.active === true" class="btn btn-default search-button" ng-click="udtTable.resetLocalSearch()" title="{{udtHelpers.messages.Messages(\'datatable.button.resetLocalSearch\')}}">' + '<i class="fa fa-times"></i>' + '</button>' + '</span>' + '</div>' + '<div class="col-xs-12 .col-sm-12 col-md-12 col-lg-12 input-group" ng-if="!udtTable.isCompactMode()">' + '<input class="form-control" utd-change="udtTable.localSearch(udtTable.searchTerms)" type="text" ng-model="udtTable.searchTerms.$">' + '<span class="input-group-btn">' + '<button ng-if="udtTable.config.localSearch.active === true" class="btn btn-default search-button" ng-click="udtTable.localSearch(udtTable.searchTerms)" title="{{udtHelpers.messages.Messages(\'datatable.button.localSearch\')}}">' + '<i class="fa fa-search"></i>' + '<span> {{udtHelpers.messages.Messages(\'datatable.button.localSearch\')}} </span>' + '</button>' + '<button ng-if="udtTable.config.localSearch.active === true" class="btn btn-default search-button" ng-click="udtTable.searchTerms={};udtTable.localSearch()" title="{{udtHelpers.messages.Messages(\'datatable.button.resetLocalSearch\')}}">' + '<i class="fa fa-times"></i>' + '<span> {{udtHelpers.messages.Messages(\'datatable.button.resetLocalSearch\')}} </span>' + '</button>' + '</span>' + '</div>' + '</div>' + '<div class="btn-toolbar pull-right" name="udt-toolbar-results" ng-if="udtTable.isShowToolbarResults()">' + '<button class="btn btn-info" disabled="disabled" ng-if="udtTable.config.showTotalNumberRecords">{{udtHelpers.messages.Messages(\'datatable.totalNumberRecords\', udtHelpers.getTotalNumberRecords())}}</button>' + '</div>' + '<div class="btn-toolbar pull-right" name="udt-toolbar-pagination" ng-if="udtTable.isShowToolbarPagination()">' + '<div class="btn-group" ng-if="udtTable.isShowPagination()">' + '<ul class="pagination">' + '<li ng-repeat="page in udtTable.config.pagination.pageList" ng-class="page.clazz">' + '<a href="" ng-click="udtTableFunctions.setPageNumber(page);" ng-bind="page.label"></a>' + '</li>' + '</ul>' + '</div>' + '<div class="btn-group">' + '<button data-toggle="dropdown" class="btn btn-default dropdown-toggle">' + '{{udtHelpers.messages.Messages(\'datatable.button.length\', udtTable.config.pagination.numberRecordsPerPage)}} <span class="caret"></span>' + '</button>' + '<ul class="dropdown-menu">' + '<li ng-repeat="elt in udtTable.config.pagination.numberRecordsPerPageList" class={{elt.clazz}}>' + '<a href="" ng-click="udtTableFunctions.setNumberRecordsPerPage(elt)">{{elt.number}}</a>' + '</li>' + '</ul>' + '</div>' + '</div>' + '</div>' +'</div>'); }]).run(['$templateCache', function($templateCache) { $templateCache.put('udt-toolbar-bottom.html', '<div name="udt-toolbar-bottom" class="row margin-bottom-3">' + '<div class="col-md-12 col-lg-12">' + '<div class="btn-toolbar pull-right" name="udt-toolbar-pagination" ng-if="udtTable.isShowToolbarPagination()">' + '<div class="btn-group" ng-if="udtTable.isShowPagination()">' + '<ul class="pagination">' + '<li ng-repeat="page in udtTable.config.pagination.pageList" ng-class="page.clazz">' + '<a href="" ng-click="udtTableFunctions.setPageNumber(page);" ng-bind="page.label"></a>' + '</li>' + '</ul>' + '</div>' + '<button class="btn btn-default" ng-click="udtTable.goToAnchor(\'udt-top-\'+udtTable.config.name)" title="{{udtHelpers.messages.Messages(\'datatable.button.top\')}}">' + '<i class="fa fa-chevron-up"></i>' + '<span ng-if="!udtTable.isCompactMode()"> {{udtHelpers.messages.Messages(\'datatable.button.show\')}} </span>' + '</button>' + '</div>' + '</div>' +'</div>'); }]);<file_sep>/README.md # Emmefx Backoffice ## Requirements 1. Install [NPM](https://nodejs.org/en/) 2. Install [Bower](https://bower.io/) ## Project setup Run `npm install` and `bower install` to install project dependencies. ## Build Run `gulp build` to build the poject for distribution. To build the project for development purposes (i.e., files are bundled but not minified), run `gulp build-dev`. Both commands will build the project to a 'dist' folder. ## Starting the Application Run `gulp start` to start the application at [http://localhost:3000] <file_sep>/src/js/directives/sidebar.js var app = angular.module('menuToogle', []); app.directive('sidebarToggle',sidebarToggle); sidebarToggle.$inject = ['$window','$compile']; function sidebarToggle($window, $compile, $timeout) { return { restrict: 'AE', link: link }; function link(scope,iElement) { scope.element = iElement[0]; scope.body = angular.element('#menulot'); scope.element.addEventListener("click", function() { if (scope.body.hasClass('menu-hide')){ scope.body.removeClass('menu-hide'); scope.body.removeClass('vertical-overlay-menu'); scope.body.addClass('menu-open'); scope.body.addClass('vertical-compact-menu'); }else{ scope.body.removeClass('menu-open'); scope.body.removeClass('vertical-compact-menu'); scope.body.addClass('menu-hide'); scope.body.addClass('vertical-overlay-menu'); } }); } }; app.directive('sidebarToggleMobile',sidebarToggleMobile); sidebarToggleMobile.$inject = ['$window','$compile']; function sidebarToggleMobile($window, $compile, $timeout) { return { restrict: 'AE', link: link }; function link(scope,iElement) { scope.element = iElement[0]; scope.body = angular.element('#menulot'); scope.element.addEventListener("click", function() { if (scope.body.hasClass('menu-hide')){ scope.body.removeClass('menu-hide'); scope.body.removeClass('vertical-compact-menu'); scope.body.addClass('menu-open'); scope.body.addClass('vertical-overlay-menu'); }else{ scope.body.removeClass('menu-open'); scope.body.removeClass('vertical-overlay-menu'); scope.body.addClass('menu-hide'); scope.body.addClass('vertical-compact-menu'); } }); } }; app.directive('resize', resize); resize.$inject = ['$window','$compile']; function resize($window,$compile) { return { link: link, restrict: 'A' }; function link(scope, element, attrs){ scope.body = angular.element('#menulot'); scope.width = $window.innerWidth; if($window.innerWidth <768){ scope.body.removeClass('menu-open'); scope.body.addClass('menu-hide'); scope.body.removeClass('vertical-compact-menu'); scope.body.addClass('vertical-overlay-menu'); } angular.element($window).bind('resize', function(){ if($window.innerWidth <768){ scope.body.removeClass('menu-open'); scope.body.addClass('menu-hide'); scope.body.removeClass('vertical-compact-menu'); scope.body.addClass('vertical-overlay-menu'); } if($window.innerWidth >=768){ scope.body.removeClass('menu-hide'); scope.body.addClass('menu-open'); scope.body.removeClass('vertical-overlay-menu'); scope.body.addClass('vertical-compact-menu'); } }); } }; app.directive('ajustebody', ajustebody); ajustebody.$inject = ['$window','$compile']; function ajustebody($window,$compile) { return { link: link, restrict: 'E' }; function link(scope, element, attrs){ scope.body = angular.element('#menulot'); scope.body.removeClass('1-column'); scope.body.addClass('2-columns'); scope.body.removeClass('bg-full-screen-image'); //scope.body.addClass('menu-open'); scope.body.removeClass('blank-page'); scope.body.addClass('fixed-navbar'); scope.body.attr('data-col','2-columns'); if($window.innerWidth >=768){ scope.body.addClass('menu-open'); } } }; app.directive('search', search); search.$inject = ['$window','$compile']; function search($window,$compile) { return { link: link, restrict: 'AE' }; function link(scope,iElement) { scope.element = iElement[0]; scope.input = angular.element('#search'); scope.element.addEventListener("click", function() { if (scope.input.hasClass('open')){ scope.input.removeClass('open'); }else{ scope.input.addClass('open'); } }); } }; app.directive('countdown', countdown); countdown.$inject = ['Util','$interval']; function countdown (Util, $interval) { return { restrict: 'A', link: function (scope,element) { var future; future = 20; scope.timer = angular.element('#timer15'); contador = $interval(function () { //var diff; //diff = Math.floor(future); future = future - 1; if(future <=15){ scope.timer.removeClass('badge-success'); scope.timer.addClass('badge-danger'); } if(future <=0){ $interval.cancel(contador); } return element.text(Util.dhms(future)); }, 1000); } }; }; app.factory('Util', [function () { return { dhms: function (t) { var days, hours, minutes, seconds,msg; days = Math.floor(t / 86400); t -= days * 86400; hours = Math.floor(t / 3600) % 24; t -= hours * 3600; minutes = Math.floor(t / 60) % 60; t -= minutes * 60; seconds = t % 60; if(seconds<=9){seconds ='0'+seconds;} msg = minutes+':'+seconds; if(t <=0){ msg = 'Timeout';} return [ msg ].join(' '); } }; }]); <file_sep>/src/js/OLD/16_angular-api-connect.js (function (window, angular, undefined) { 'use strict'; angular.module('ApiConnect', ['Authentication']) .service('$api', ['$http','$authentication', '$MessageGlogalService', function ($http, $authentication, $MessageGlogalService) { var apiService = this; apiService.loading = false; apiService.requests = {}; apiService.totalRequest = function () { var total = 0; angular.forEach(apiService.requests, function () { total++; }); return total; }; apiService.clearRequests = function () { apiService.requests = {}; return apiService; }; apiService.deleteRequest = function ($endpoint) { delete apiService.requests[$endpoint]; apiService.loading = false; return apiService; }; apiService.addRequest = function ($endpoint, $parametros, $callback) { var $request = apiService.requests[$endpoint] = {}; $request['parametros'] = $parametros; $request['callback'] = $callback; return apiService; }; apiService.request = function ($endpoint, $parametros, $callBack) { apiService.loading = true; if (!apiService.totalRequest()) { console.log("Api connect: não existe requisições."); return; } /* xsrfHeaderName – {string} – Name of HTTP header to populate with the XSRF token. xsrfCookieName */ var $requests = apiService.requests; this.clearRequests(); var $data = {'data':{}}; angular.forEach($requests, function ($infoRequest, $endpoint) { $data['data'][$endpoint] = $infoRequest['parametros']; }); var $url = config.api.path; try { $http({method: 'POST', url: $url, params: "", data: $data, /*xsrfHeaderName: 'XSRF-TOKEN', xsrfCookieName: 'XSRF-TOKEN', */withCredentials: true}). success(function (data, status, headers, config, statusText) { apiService.processReceiveData($requests, data, status, headers, config, statusText); apiService.loading = false; }). error(function (data, status, headers, config, statusText) { apiService.processReceiveData($requests, data, status, headers, config, statusText); apiService.loading = false; }); }catch (err) { apiService.loading = false; } }; apiService.processReceiveData = function (requests, data, status, headers, config, statusText) { switch (status) { default: //ERROR CONEXAO if (typeof $storage.loginInformation != "undefined") { window.history.back(); } $MessageGlogalService.add('Please, try again.', 'error', false); //$authentication.logout(true); // $scope.$broadcast('addMessageGlobal', {msg: "No internet connection.", tipo: "error"}); break; case 200: //ok console.log('API Request:',requests,'API Response:',data); angular.forEach(data['data'],function ($data, $endpoint) { requests[$endpoint]['callback']($data,requests[$endpoint]['parametros']); }); break; case 403: //proibido $authentication.logout(true); return; break; case 400: //bad case 500: //internal error //$authentication.logout(true); break; } angular.forEach(data['data'],function ($data, $endpoint) { delete apiService.requests[$endpoint]; }); //console.log(data); console.log(status); //DEBUG }; }]); })(window, window.angular); <file_sep>/src/js/OLD/22_datatables.js (function () { 'use strict'; angular.module('emmefxApp') .controller('datactrl', datactrl) function datactrl($resource) { var vm = this; $resource('/js/data.json').query().$promise.then(function(persons) { vm.persons = persons; console.log(vm.persons); }); } })(); <file_sep>/src/js/OLD/33_emmefx.config.js 'use strict'; angular.module('emmefxApp') .constant('apiUrl', 'https://api.xprocapital.com/api') .constant('mocksPath', '/service/json-complete') .constant('userInfoRequestRate', 120) // In seconds .constant('smLoader', "../images/loading.gif") // smallLoader .constant('lgLoader', "../images/loader.gif") // large loader<file_sep>/src/js/plugins/angular-datatables.instances.js 'use strict'; angular.module('datatables.instances', ['datatables.util']) .factory('DTInstanceFactory', dtInstanceFactory); function dtInstanceFactory() { var DTInstance = { reloadData: reloadData, changeData: changeData, rerender: rerender }; return { newDTInstance: newDTInstance, copyDTProperties: copyDTProperties }; function newDTInstance(renderer) { var dtInstance = Object.create(DTInstance); dtInstance._renderer = renderer; return dtInstance; } function copyDTProperties(result, dtInstance) { dtInstance.id = result.id; dtInstance.DataTable = result.DataTable; dtInstance.dataTable = result.dataTable; } function reloadData(callback, resetPaging) { /*jshint validthis:true */ this._renderer.reloadData(callback, resetPaging); } function changeData(data) { /*jshint validthis:true */ this._renderer.changeData(data); } function rerender() { /*jshint validthis:true */ this._renderer.rerender(); } }
8344355965cd003bd4868eab021fa6b5e7c2805c
[ "Markdown", "JavaScript" ]
13
Markdown
zegitz/emmefx-frontend
4dbbbffce16da8c09b2cd46cf1689236f04c868b
8fa9d1a67895f99b382dfe62d970a86e470f7468
refs/heads/master
<file_sep># How to run it - Create an *errorfile* (a file with an sentence containing a mistake in every line). Errors are marked with the following format [error|correction]. Eg: ``` Roug[ez|issez]-vous quelquefois? ``` - Then run the programming with **cabal run** passing as an argument the error file. ```bash cabal run <errorfile> ``` <file_sep>-- Initial improvemyfrench.cabal generated by cabal init. For further -- documentation, see http://haskell.org/cabal/users-guide/ name: improvemyfrench version: 0.1.0.0 synopsis: Tool to help learning french -- description: homepage: http://github.com/txominpelu/improvemyfrench -- license: license-file: LICENSE author: <NAME> maintainer: <EMAIL> -- copyright: category: Language build-type: Simple -- extra-source-files: cabal-version: >=1.10 executable improvemyfrench main-is: Main.hs -- other-modules: default-extensions: NoMonomorphismRestriction build-depends: base >=4.6 && <4.7, parsec >= 3.1.5, split >= 0.1.2.3, random-fu >= 0.2.6.2, random-extras >= 0.17, random-source >= 0.3.0.6 -- hs-source-dirs: default-language: Haskell2010 <file_sep>-- -- Copyright (c) 2006 <NAME> - http://www.cse.unsw.edu.au/~dons/ -- GPL version 2 or later (see http://www.gnu.org/copyleft/gpl.html) -- import System.Environment import PardonMyFrench.FrenchParser import PardonMyFrench.CorrectMistakes import Text.Parsec import Data.Either import Data.List import Data.Random import Data.Random.List import Data.Random.Source.DevRandom import qualified Data.Random.Extras errorsFile = "errors.csv" batchQuestionsSize = 3 readMistakes :: String => IO [Sentence] readMistakes file = do content <- readFile file let linesOfFiles = lines content parsed = map (\l -> parse sentence "" l) linesOfFiles return (rights parsed) correctMistakes :: [Sentence] => IO () correctMistakes mistakes = do tries <- mapM (askTillRight []) mistakes mapM logTries tries let totalNumTries = foldl1' (+) (map length tries) putStrLn $ "Total tries: (" ++ show totalNumTries ++ "/" ++ show (length mistakes) ++ ")" repl :: [Sentence] => String => IO () repl mistakes "mistakes" = do batchMistakes <- runRVar (Data.Random.Extras.sample batchQuestionsSize mistakes) DevRandom correctMistakes batchMistakes repl mistakes "main" repl mistakes "quit" = do putStrLn "Bye" repl mistakes any = do putStrLn "$>" line <- getLine repl mistakes line -- | 'main' runs the main program main :: IO () main = do mistakes <- readMistakes errorsFile repl mistakes "main" <file_sep>module PardonMyFrench.CorrectMistakes where import PardonMyFrench.FrenchParser import Data.List.Split import Data.List logPath = "events.log" logJson :: String => String => String logJson eventType sentence = "{ \"type\": \"" ++ eventType ++ "\", \"sentence\": \"" ++ sentence ++ "\"}\n" successLog :: String => String successLog sentence = logJson "success" sentence errorLog :: String => String errorLog sentence = logJson "error" sentence beginSession = "+++\n" logTries :: [String] => IO () logTries tries = do appendFile logPath beginSession mapM_ (appendFile logPath) tries askTillRight :: [String] => Sentence => IO [String] askTillRight tries sentence = do let wSentence = (wrongSentence sentence) putStrLn $ show (length tries) ++ ">" ++ (intercalate " " wSentence) input <- getLine if (splitOn " " input) == (correctSentence sentence) then do return $ tries ++ [successLog input] else do askTillRight (tries ++ [(errorLog input)]) sentence <file_sep>constraints: array ==0.4.0.1, base ==4.6.0.1, bytestring ==0.10.0.2, deepseq ==1.3.0.1, ghc-prim ==0.3.0.0, improvemyfrench ==0.1.0.0, integer-gmp ==0.5.0.0, mtl ==2.2.1, parsec ==3.1.9, rts ==1.0, split ==0.2.2, text ==1.2.0.4, transformers ==0.4.3.0 <file_sep>module PardonMyFrench.FrenchParser where import Text.ParserCombinators.Parsec -- data ErroredWord = Alternative String String deriving (Show) data Word = Correct String | ErroredWord String String instance Show Word where show (ErroredWord error correct) = "[" ++ error ++ "|" ++ correct ++ "]" show (Correct word) = word correctWord :: Word => String correctWord (Correct x) = x correctWord (ErroredWord w c) = c wrongWord :: Word => String wrongWord (Correct x) = x wrongWord (ErroredWord w c) = w correctSentence :: Sentence => [String] correctSentence (Sentence s) = map correctWord s wrongSentence :: Sentence => [String] wrongSentence (Sentence s) = map wrongWord s data Sentence = Sentence [Word] deriving (Show) sentence :: Parser Sentence sentence = do result <- mword eof return (Sentence result) -- Each cell contains 0 or more characters, which must not be a comma or -- EOL mword :: Parser [Word] mword = (sepBy ( choice [(try erroredWord), (fmap Correct (many1 frenchAlphaNum))] ) (many space)) frenchAlphaNum :: Parser Char frenchAlphaNum = oneOf "'-?" <|> letter erroredWord :: Parser Word erroredWord = do prefix <- many frenchAlphaNum char '[' w1 <- many1 frenchAlphaNum char '|' w2 <- many1 frenchAlphaNum char ']' postfix <- many frenchAlphaNum return (ErroredWord (prefix ++ w1 ++ postfix) (prefix ++ w2 ++ postfix))
20f45c4a35fdd5acb175035b70308af49c4b100a
[ "Markdown", "Cabal Config", "Haskell" ]
6
Markdown
txominpelu/pardonmyfrench
df83013f56e05c63fd5351cf154092d894b2d13b
984b2fdc6ef43bcb61c3e1471e77b97153725951
refs/heads/master
<repo_name>ArthurMatthys/prologin_train<file_sep>/2015/qualification/lv2.py a = int(input()) it = int(input()) for i in range(it): if a % 2: a = a * 3 + 1 else: a /= 2 print(int(a)) <file_sep>/2015/regional/lv3_2.py size = int(input()) pyramid = [] for _ in range(size): pyramid.append([int(e) for e in input().split(' ')]) timing = [] for i, tab in enumerate(pyramid): new_tab = [] for j, time in enumerate(tab): if i == 0: new_tab.append(time) else: if j == 0: new_tab.append(timing[-1][j] + time) elif j < i: new_tab.append(min(timing[-1][j], timing[-1][j-1]) + time) else: new_tab.append(timing[-1][j-1] + time) timing.append(new_tab) print(max(timing[-1])) <file_sep>/2015/regional/lv2_2.py def crenau(nbr, h): tot = 0 for _ in range(nbr-1): print(" _ ", end="") tot += 4 print(" _ ") tot += 3 for _ in range(nbr - 1): print("| |_", end="") print("| |") for _ in range(h-2): print("|", end="") for _ in range(tot - 2): print(" ", end="") print("|") print("|", end="") for _ in range(tot - 2): print("_", end="") print("|") nbr = int(input()) h = int(input()) crenau(nbr, h) <file_sep>/2015/regional/lv4_1.py h, l = [int(e) for e in input().split(' ')] x, y = [int(e) for e in input().split(' ')] plate = [list(map(int, input().split(' '))) for _ in range(h)] stack = set() stack.add((x, y)) origin = plate[x][y] nbr = 0 l_of = [[1,0], [-1,0], [0,1], [0,-1]] while len(stack): ax, ay = stack.pop() color = plate[ax][ay] for of in l_of: if (0 <= ax + of[0] < h) and (0 <= ay + of[1] < l): if plate[ax+of[0]][ay+of[1]] == origin: stack.add((ax+of[0], ay+of[1])) plate[ax+of[0]][ay+of[1]] = 5 elif plate[ax+of[0]][ay+of[1]] == 2: plate[ax+of[0]][ay+of[1]] = 5 nbr +=1 print(nbr) <file_sep>/2015/regional/lv5_1.py import heapq h, l = [int(e) for e in input().split()] map1 = [list(input()) for _ in range(h)] map2 = [list(input()) for _ in range(h)] maps = [map1] + [map2] def manhattan(start, end): return abs(end[1] - start[1]) + abs(end[0] - start[0]) + (start[2] != end[2]) dd = [[1,0,0], [-1,0,0], [0,1,0], [0,-1,0], [0,0,1], [0,0,-1]] def astar(maps, start, end): heap = [(manhattan(start, end), start, 0)] heapq.heapify(heap) visited = set() while len(heap): a = heapq.heappop(heap) visited.add(a[1]) dist = a[0] pos = a[1] path = a[2] if pos == end: return path else: for op in dd: dx = op[0] dy = op[1] dz = op[2] x = pos[0] + dx y = pos[1] + dy z = pos[2] + dz if (z == 0 or z == 1) and (0 <= x < h) and (0 <= y < l) and ((x,y,z) not in visited): if maps[z][x][y] != '#': heapq.heappush(heap, path + (manhattan((x,y,z), end), (x,y,z), path+1)) return 0 for i in range(h): if 'a' in maps[0][i]: end = (i, maps[0][i].index('a'), 0) if 'd' in maps[0][i]: st = (i, maps[0][i].index('d'), 0) print(astar(maps, st, end)) <file_sep>/2015/regional/lv4_2.py h, l = [int(e) for e in input().split(' ')] height = dict() mount = [list(map(int, input().split(' '))) for _ in range(h)] for i in mount: for e in i: height[e] = 0 dd = [[1,0],[-1,0],[0,1],[0,-1]] def flood(mount, dic, x, y): new_h = mount[x][y] mount[x][y] = -1 nbr = 0 heap = [(x, y)] while len(heap): xx, xy = heap.pop() nbr += 1 for d in dd: dx = d[0] dy = d[1] new_x = xx + dx new_y = xy + dy if 0 <= new_x < h and 0 <= new_y < l and mount[new_x][new_y] == new_h: mount[new_x][new_y] = -1 heap.append((new_x, new_y)) if dic[new_h] < nbr: dic[new_h] = nbr for i in range(h): for j in range(l): if mount[i][j] != -1: flood(mount, height, i, j) print(max(height.values())) <file_sep>/2015/regional/lv6_01.py n = int(input()) group = [int(e) for e in input().split()] links = [set() for _ in range(n)] for i, value in enumerate(group): links[i].add(value) links[value].add(i) nbr = 0 def remove_elem(elem, links, add=False): for i, tab in enumerate(links): if elem in tab: links[i].remove(elem) if add and links[i] == set([]): links[i] = set([-1]) while sum([len(i) for i in links]): l = [len(i) if i != set([]) else float('inf') for i in links] a = l.index(min(l)) nbr += 1 remove_elem(a, links) cpy = set(links[a]) for i in cpy: if links[i] != set([]) and links[i] != set([-1]): links[i] = set([]) remove_elem(i, links, True) links[a] = set([]) free = len(list(filter(lambda e: e == set([-1]), links))) nbr += free links = list(map(lambda e: set([]) if e == set([-1]) else e, links)) print(nbr) <file_sep>/2015/regional/lv1_2.py input() temp = [int(e) for e in input().split(' ')] tmp = [temp[0]] for index, i in enumerate(temp[1:]): tmp.append(i-temp[index]) for i in tmp: print(f"{i} ", end="") <file_sep>/2015/regional/lv5_0.py n = int(input()) adj = [[] for _ in range(n)] times = [-1 for _ in range(n)] for i in range(n): a = [int(e) for e in input().split(' ')] if a[0] == 0: continue index = 1 while index < len(a): adj[i].append((a[index], a[index+1])) index += 2 def calc_rec(adj, times, i): if times[i] != -1: return times[i] if adj[i] == []: return 0 a = 0 for j in adj[i]: a = max(a, calc_rec(adj, times, j[0]) + j[1]) times[i] = a return a for i in range(n): calc_rec(adj, times, i) print(max(times)) <file_sep>/2015/qualification/lv4.py import heapq N, M, R = [int(e) for e in input().split(' ')] adj = [[float('inf') for _ in range(N)] for _ in range(N)] paths = [{} for _ in range(N)] for _ in range(M): x, y, l = [int(e) for e in input().split(' ')] paths[x-1][y-1] = l def dji(start): h = [(0, start)] while len(h): size, node = heapq.heappop(h) for (new_node, weight) in paths[node].items(): if size + weight < adj[start][new_node]: adj[start][new_node] = size + weight heapq.heappush(h, (size + weight, new_node)) for _ in range(R): start, end = map(int, input().split(' ')) if adj[start - 1][end - 1] == float('inf'): dji(start - 1) print(adj[start - 1][end - 1]) <file_sep>/2015/qualification/lv3.py import cmath import math r = [int(e) for e in input().split(' ')] nbr = int(input()) out = [] points = [] def norm(a): return (a[0] ** 2 + a[1] ** 2) ** (1/2) for i in range(nbr): x, y = [int(e) for e in input().split(' ')] points.append(f"{x} {y}") x -= r[0] y -= r[1] if y == 0 and x < 0: out.append(math.pi) else: tmp = cmath.phase(complex(x, y)) out.append(tmp) res = [] for i in out[1:]: an = i - out[0] if an < 0: an += 2 * math.pi res.append(an) #print(out) #print(res) print(points[res.index(min(res)) + 1]) <file_sep>/2015/qualification/lv1.py a = int(input()) tot = [i for i in range(1, a+1)] print(sum(tot)) <file_sep>/2015/regional/lv2_1.py input() line = input().split(' ') input() rem = [int(e) for e in input().split(' ')] for index, word in enumerate(line): if index + 1 in rem: for _ in range(len(word)): print('*', end="") else: print(word, end="") print(' ', end="") <file_sep>/2015/regional/lv6_0.py n = int(input()) group = [int(e) for e in input().split()] def dp(lst, eat, group, index): if index == n: return len(lst) if group[index] in lst: return dp(lst, eat, group, index+1) if index in eat: return dp(lst, eat ,group, index+1) else: return max(dp(lst + [index], eat + [group[index]], group, index + 1), dp(lst, eat, group, index+1)) a = dp([], [], group, 0) print(a) <file_sep>/2015/regional/lv3_1.py nbr, size = [int(e) for e in input().split(' ')] first = [] second = [] for _ in range(nbr): first.append([int(e) for e in input().split(' ')]) for _ in range(nbr): second.append([int(e) for e in input().split(' ')]) def get_fastest(lst): time = [] for i in lst: if i[1] == 0: time.append(float('inf')) continue time.append((size - i[0]) / i[1]) return time.index(min(time)) def run(first, second): i1 = 0 i2 = 0 while 1: if len(first) == 0: print(2 * nbr - len(second) + 1) break if len(second) == 0: print(nbr - len(first) + 1) break x1, v1 = first[0] x2, v2 = second[0] if v2 == 0: second.pop(0) i2 += 1 continue elif v1 == 0: first.pop(0) i1 += 1 continue else: t1 = x2 / v1 t2 = x1 / v2 if t1 <= t2: second.pop(0) i2 += 1 continue else: first.pop(0) i1 += 1 continue run(first, second) <file_sep>/2015/regional/lv1_1.py import math nbr = int(input()) length = int(input()) speed = [int(e) for e in input().split()] start = [int(e) for e in input().split()] times = [] for index, i in enumerate(speed): s = start[index] new_dist = length - s if new_dist <= 0: times.append(0) else: times.append(math.ceil(new_dist/i)) print(times.index(min(times)))
c40f41ed286e7743ef2ce8f10bb2eb7de4f68e37
[ "Python" ]
16
Python
ArthurMatthys/prologin_train
a32ac3aaf5f9ba6c67f0f589a53ef7a2e268bc47
f4de775c2f6257e65bb832bc9d108d29c800ddf1
refs/heads/master
<repo_name>farrelNZL/industrialProject<file_sep>/src/projet.cpp #include <iostream> #include <fstream> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/calib3d/calib3d.hpp> #include <opencv2/imgproc/imgproc.hpp> // Maths methods #define max(a, b) ((a) > (b) ? (a) : (b)) #define min(a, b) ((a) < (b) ? (a) : (b)) #define abs(x) ((x) > 0 ? (x) : -(x)) #define sign(x) ((x) > 0 ? 1 : -1) double euclideanDist(cv::Point2f & p, cv::Point2f & q) { cv::Point2f diff = p - q; return cv::sqrt(diff.x*diff.x + diff.y*diff.y); } ///////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////// //Calculer le barycentre d'un vecteur de points cv::Point2f calc_bary(std::vector<cv::Point2f> v) { int bary_i = 0 ; int bary_j = 0 ; for(int k=0;k<v.size();k++) { bary_i += v[k].y; bary_j += v[k].x; } bary_i /= v.size(); bary_j /= v.size(); return cv::Point2f(bary_j,bary_i); } ///////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////// //Calculer la coordonnée i du point de la droite (aj+b) void calc_point(double a, double b, int j, cv::Point2f & p) { int i = a*j+b; p.y = i; p.x = j; } ///////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////// // Calculer les coefficient a et b de la droite passant par (i1,j1) et (i2,j2) void calc_droite(int i1,int j1,int i2,int j2,std::vector<double> & d) { double a = (double)(i1-i2)/(double)(j1-j2); double b = i1-a*j1; d.push_back(a); d.push_back(b); } ///////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////// // Calculer les coefficient a et b de la droite perpendiculaire a la droite passant par (i1,j1) et (i2,j2) void calc_droite_perp(int i1,int j1,int i2,int j2,std::vector<double> & d) { double a_perp = -(double)(j1-j2)/(double)(i1-i2); double b_perp = i1-a_perp*j1; d.push_back(a_perp); d.push_back(b_perp); } ///////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////// // renvoit un vecteur contenant les coordonnées des points détectés dans l'image std::vector<cv::Point2f> find_red(cv::Mat W,int h, int w, int val_min,int rayon_zone,int seuil_nbPixel) { //dilater les points cv::Mat I = W; //rechercher les pixels rouges std::vector<cv::Point2f> v;//ensemble des pixels rouges d'une zone std::vector<cv::Point2f> reds;//ensemble des barycentres d'une zone de pixel rouge for(int j=0;j<w;j++) { for(int i=0;i<h;i++) { if(I.at<unsigned char>(i,j) > val_min) //pixel rouge détecté { //on regarde si il y a d'autres pixels autour if(i+rayon_zone < h && j+rayon_zone < w)//conditions au bords { int nbPixel = 0; for(int k=0;k<rayon_zone;k++) { if(I.at<unsigned char>(i+k,j) > val_min) {nbPixel++;} if(I.at<unsigned char>(i,j+k) > val_min) {nbPixel++;} if(I.at<unsigned char>(i+k,j+k) > val_min) {nbPixel++;} } if(nbPixel >seuil_nbPixel && reds.size() < 2) //point détecté ! { for(int k1=max(0,i-rayon_zone);k1<min(i+rayon_zone,h);k1++) { for(int k2=max(0,j-rayon_zone);k2<min(w,j+rayon_zone);k2++) { if(I.at<unsigned char>(k1,k2) > val_min) { I.at<unsigned char>(k1,k2) =0; cv::Point2f p(k2,k1); v.push_back(p); } } } cv::Point2f bary = calc_bary(v) ; reds.push_back(bary); v.clear(); } } } } } return reds; } ///////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////// // trouver les points blanc en fonction des rouges void find_white(cv::Mat & Ig,int i,int j, double a, double b, int w, int h, int rayon_zone, int val_min, double dist_min_red, double dist_max_red, int seuil_nbPixel,std::vector<cv::Point2f> & p_whites) { /* Ir,Ig,Ib = channels RGB i,j = point rouge de la droite a,b = parametres de la droite : i = aj+b w,h = taille de l'image r = taille de la zone de recherche */ std::vector<cv::Point2f> v; cv::Point2f p1(j,i) ; cv::Point2f P(0,0); bool add = false; for(int jw = j-rayon_zone; jw<j+rayon_zone ; jw++) { //calculer le point de la droite cv::Point2f p; calc_point(a,b,jw,p); //verifier qu'il est dans l'image if(p.y >= 0 && p.y < h) { //Définir une zone de recherche int i_min = max(0,p1.y+dist_min_red); int i_max = min(p1.y+dist_max_red,h); //tester les points de la zone for(int iw=i_min ; iw<i_max;iw++) { cv::Point2f P(jw,iw); if((int)Ig.at<unsigned char>(iw,jw) > val_min) { //on regarde si il y a d'autres pixels autour if(iw+rayon_zone < h && jw+rayon_zone < w)//conditions au bords { int nbPixel = 0; for(int k=0;k<rayon_zone;k++) { if(Ig.at<unsigned char>(iw+k,jw) > val_min) {nbPixel++;} if(Ig.at<unsigned char>(iw,jw+k) > val_min) {nbPixel++;} if(Ig.at<unsigned char>(iw+k,jw+k) > val_min) {nbPixel++;} } if(nbPixel >seuil_nbPixel && !add ) //point détecté ! { for(int k1=max(0,iw-rayon_zone);k1<min(iw+rayon_zone,h);k1++) { for(int k2=max(0,jw-rayon_zone);k2<min(w,jw+rayon_zone);k2++) { if(Ig.at<unsigned char>(k1,k2) > val_min) { Ig.at<unsigned char>(k1,k2) =0; cv::Point2f p(k2,k1); v.push_back(p); } } } cv::Point2f bary = calc_bary(v) ; p_whites.push_back(bary); add=true; v.clear(); } } } } } } } void find_p(cv::Mat * composante_imgOriginal, cv::Mat * composante_imgred, std::vector<cv::Point2f> & points, int rayon_zone_red, int seuil_nbPixel_red, int val_min_red, double coeff_min_white, double coeff_max_white,int rayon_zone_white, int seuil_nbPixel_white, int val_min_white) { int w = composante_imgOriginal[2].cols; int h = composante_imgOriginal[2].rows; bool flag=true; ///////////////// Chercher les points rouges ////////////////////// points = find_red(composante_imgred[2],h,w,val_min_red,rayon_zone_red,seuil_nbPixel_red); // Liste des points rouges detéctés int nbPointsDetec = points.size(); if(nbPointsDetec != 2) { //////////////// si les rouges ne sont pas trouvés, ou qu'il y a plus de 2 points détéctés ////////////////////////////// std::cout << "Erreur : nombre LED rouges déctecté = " << nbPointsDetec << " != 2)" << std::endl; } if(flag) { //////////////// les points rouges sont trouvés, chercher les droites pour definir une zone de recherche ///////////////////// int i1 = points[0].y ; int j1 = points[0].x ; int i2 = points[1].y ; int j2 = points[1].x ; cv::inRange(composante_imgOriginal[1], cv::Scalar(255), cv::Scalar(255), composante_imgOriginal[1]); cv::Mat kernel = cv::getStructuringElement(2, cv::Size(5,5)); cv::erode(composante_imgOriginal[1], composante_imgOriginal[1], kernel); cv::dilate(composante_imgOriginal[1], composante_imgOriginal[1], kernel); std::vector<double> d ; std::vector<double> dperp1; std::vector<double> dperp2; calc_droite(i1,j1,i2,j2,d); calc_droite_perp(i1,j1,i2,j2,dperp1); calc_droite_perp(i2,j2,i1,j1,dperp2); cv::Point2f p1; cv::Point2f p2; cv::Point2f pstart_perp1; cv::Point2f pend_perp1; cv::Point2f pstart_perp2; cv::Point2f pend_perp2; calc_point(d[0],d[1],j1,p1); calc_point(d[0],d[1],j2,p2); cv::Point2f pstart; cv::Point2f pend; calc_point(d[0], d[1], 0, pstart); calc_point(d[0], d[1], w, pend); calc_point(dperp1[0],dperp1[1],0,pstart_perp1); calc_point(dperp1[0],dperp1[1],w,pend_perp1); calc_point(dperp2[0],dperp2[1],0,pstart_perp2); calc_point(dperp2[0],dperp2[1],w,pend_perp2); //calculer la distance entre les leds rouges cv::Point2f p01(j1,i1); cv::Point2f p02(j2,i2); double dist_red = euclideanDist(p01,p02); double dist_min_red = coeff_min_white * dist_red; double dist_max_red = coeff_max_white * dist_red; //Rechercher les points blancs find_white(composante_imgOriginal[1],i1,j1, dperp1[0], dperp1[1], w, h, rayon_zone_white,val_min_white,dist_min_red,dist_max_red,seuil_nbPixel_white,points); find_white(composante_imgOriginal[1],i2,j2, dperp2[0], dperp2[1], w, h, rayon_zone_white,val_min_white,dist_min_red,dist_max_red,seuil_nbPixel_white,points); } } void solvePNP (std::vector<cv::Point3f> objPoints, std::vector<cv::Point2f> imgPoints, cv::Mat cam, cv::Mat distorsion, cv::Mat output) { cv::Mat rvec_init = cv::Mat::zeros(3, 1, CV_64FC1); cv::Mat tvec_init = cv::Mat::zeros(3, 1, CV_64FC1); cv::solvePnP(objPoints,imgPoints,cam,distorsion,rvec_init,tvec_init,CV_EPNP); //init avec EPNP cv::Mat rvec = rvec_init; cv::Mat tvec = tvec_init; cv::solvePnP(objPoints,imgPoints,cam,distorsion,rvec,tvec,CV_ITERATIVE); cv::Mat rmat; cv::Rodrigues(rvec,rmat); hconcat(rmat,tvec,output); } void readFileToMat(cv::Mat & m, const char* filename) { std::ifstream fin(filename); if(!fin) { std::cout<<"File Not Opened"<<std::endl; return; } for(int i=0; i<m.rows; i++) { for(int j=0; j<m.cols; j++) { fin>>m.at<double>(i,j); } } fin.close(); } int projet(double cable, int min, int max, int rayon_zone_red, int seuil_nbPixel_red, int val_min_red, double coeff_min_white, double coeff_max_white, int rayon_zone_white, int seuil_nbPixel_white, int val_min_white, bool affichage, std::string video_path, std::vector<cv::Point3f> & objPoints, const char* calibration_path, const char* distorsion_path ) { //chargement des fichiers de calibration de la camera cv::Mat cam = cv::Mat::zeros(3, 3, CV_64FC1); cv::Mat distorsion = cv::Mat::zeros(1, 5, CV_64FC1); readFileToMat(cam,calibration_path); readFileToMat(distorsion,distorsion_path); cv::VideoCapture cap(video_path); if ( !cap.isOpened() ) { std::cout << "Cannot open the web cam" << std::endl; return -1; } //points dans le repere camera std::vector<cv::Point2f> imgPoints; std::vector<cv::Point2f> imgPoints_old; imgPoints_old.push_back(cv::Point2f(0,0)); imgPoints_old.push_back(cv::Point2f(0,0)); imgPoints_old.push_back(cv::Point2f(0,0)); imgPoints_old.push_back(cv::Point2f(0,0)); cv::Mat imgOriginal; cv::Mat imgFinal; if(affichage) { cv::namedWindow("Original", CV_WINDOW_AUTOSIZE ); cv::moveWindow("Original",10,10); cv::namedWindow("final", CV_WINDOW_AUTOSIZE ); cv::moveWindow("final",440,10); } //faire boucle sur video while (true) { bool bSuccess = cap.read(imgOriginal); // read a new frame from video if (!bSuccess) //if not success, break loop { std::cout << "Cannot read a frame from video stream" << std::endl; break; } if(affichage) { cv::imshow("Original", imgOriginal); } cv::Mat channel_red[3]; cv::split(imgOriginal, channel_red); //seuillage sur le rouge : on garde que les pixel entre min et max cv::inRange(channel_red[2], cv::Scalar(min), cv::Scalar(max), channel_red[2]); cv::Mat kernel = cv::getStructuringElement(2, cv::Size(5,5)); cv::erode(channel_red[2], channel_red[2], kernel); cv::dilate(channel_red[2], channel_red[2], kernel); cv::Mat channel_white[3]; cv::split(imgOriginal, channel_white); imgPoints.clear(); ///////////////////////////////////////////////////////////////////////// //ajout detection des pts et traitement find_p(channel_white, channel_red, imgPoints, rayon_zone_red, seuil_nbPixel_red, val_min_red, coeff_min_white, coeff_max_white, rayon_zone_white, seuil_nbPixel_white, val_min_white); if(imgPoints.size() != 4) { std::cout << "Erreur : nombre de LED total detecté = " << imgPoints.size() << " (!=4)" << std::endl; imgPoints.clear(); imgPoints = imgPoints_old; } else { imgPoints_old.clear(); imgPoints_old = imgPoints; } cv::Mat result = cv::Mat::zeros(3, 4, CV_64FC1); solvePNP (objPoints, imgPoints, cam, distorsion, result); //std::cout << "matrice : " << std::endl << result << std::endl; //result contient la matrice resultat de la position estimee imgFinal = imgOriginal; cv::Mat channel_imgFinal[3]; cv::split(imgFinal,channel_imgFinal); if(affichage) { int rayon_cercle = 10; //points rouges for(int x=0;x<imgPoints.size()/2;x++) { cv::circle(channel_imgFinal[0], imgPoints[x],rayon_cercle, cv::Scalar(0,0,0)); cv::circle(channel_imgFinal[1], imgPoints[x],rayon_cercle, cv::Scalar(0,0,0)); cv::circle(channel_imgFinal[2], imgPoints[x],rayon_cercle, cv::Scalar(0,0,0)); } //points verts for(int x=imgPoints.size()/2;x<imgPoints.size();x++) { cv::circle(channel_imgFinal[0], imgPoints[x],rayon_cercle, cv::Scalar(0,0,0)); cv::circle(channel_imgFinal[1], imgPoints[x],rayon_cercle, cv::Scalar(0,0,0)); cv::circle(channel_imgFinal[2], imgPoints[x],rayon_cercle, cv::Scalar(0,0,0)); } cv::merge(channel_imgFinal,3,imgFinal); cv::imshow("final",imgFinal); } if (cv::waitKey(30) == 27) //wait for 'esc' key press for 30ms. If 'esc' key is pressed, break loop { std::cout << "esc key is pressed by user" << std::endl; break; } } cv::destroyAllWindows(); return 0; } <file_sep>/src/exe.cpp #include "projet.cpp" #include <iostream> #include <fstream> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/calib3d/calib3d.hpp> #include <opencv2/imgproc/imgproc.hpp> /* * * * *********************** PARTIE A MODIFIER *********************** * * * */ //lien vers les fichiers const char* calibration_path = "calibration_matrix.txt"; const char* distorsion_path = "distorsion_matrix.txt"; std::string video_path = "/home/valentin/Bureau/projet/calibration5/videotest.mp4"; //affichage bool affichage = true; //intensité des LED int min = 255; int max = 255; int val_min_red = 250; int val_min_white = 250; //taille des LED int rayon_zone_red = 45; int rayon_zone_white = 30; int seuil_nbPixel_red = 35 ; int seuil_nbPixel_white = 20 ; //géomètrie double coeff_min_white = 0.8 ; double coeff_max_white = 1.2 ; int main(int argc, char** argv ) { //paramètre du modèle double cable = 1.5; std::vector<cv::Point3f> objPoints; objPoints.push_back(cv::Point3f(-0.237193325, -0.24218675, cable)); objPoints.push_back(cv::Point3f(0.251283175, -0.23832675,cable)); objPoints.push_back(cv::Point3f(-0.242993025, 0.23693425, cable)); objPoints.push_back(cv::Point3f(0.228903175, 0.24357925, cable)); /* * * *********************** FIN DE LA PARTIE A MODIFIER *********************** * * * */ projet(cable, min, max, rayon_zone_red, seuil_nbPixel_red, val_min_red, coeff_min_white, coeff_max_white, rayon_zone_white, seuil_nbPixel_white, val_min_white, affichage , video_path, objPoints, calibration_path, distorsion_path ); } <file_sep>/src/calib.cpp //http://docs.opencv.org/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html #include <iostream> #include <fstream> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/calib3d/calib3d.hpp> #include <stdio.h> #include <stdlib.h> #include <string.h> void calibrer(cv::Mat cameraMatrix, cv::Mat distCoeffs) { bool flag = true; //while true, continue running ////////////////// Chargement des paramètres ///////////////////////////////////////////// // /!\ /!\ /!\ Attention, les images doivent être nommées sous la forme 'nom-00' avec 01,02,03... /!\ /!\ /!\ // cv::Size imageSize; std::string folder_path ; std::cout << "dossier contenant les images ? exemple : /home/valentin/Bureau/projet/calibration4/" << std::endl ; std::cin >> folder_path ; int nbImage = 6 ; std::cout << "Nombre d'images ? exemple : 6" << std::endl ; std::cin >> nbImage ; std::string image_pref = "tellus"; std::cout << "préfixe de l'image ? (nom de l'image du type prefixe-00.jpg)" << std::endl ; std::cin >> image_pref ; image_pref = image_pref + "-"; std::string image_ext; std::cout << "Extension des images ? (.jpg,.png... sans point avant)" << std::endl ; std::cin >> image_ext ; image_ext = "." + image_ext; int points_per_row; int points_per_colum; std::cout << "nombre de coins par lignes ? (uniquement les coins interieur de la mire) si mire fournie par opencv : 9" << std::endl ; std::cin >> points_per_row ; std::cout << "nombre de coins par colonne ? (uniquement les coins interieur de la mire) si mire fournie par opencv : 6" << std::endl ; std::cin >> points_per_colum ; double square_world_width = 0.029; //en metre std::cout << "taille d'un carré sur la mire imprimée ? (en metres) " << std::endl ; std::cin >> square_world_width ; std::cout << "------------------------------------------------------------------------" << std::endl; std::cout << "images de la forme : " << folder_path << image_pref << "00" << image_ext << std::endl; std::cout << "contenu : " << std::endl; std::cout << "-"<< points_per_row << " coins par lignes" << std::endl; std::cout << "-"<< points_per_colum << " coins par colonnes" << std::endl; std::cout << "taille des carrés = "<< square_world_width << "m"<< std::endl; std::cout << "------------------------------------------------------------------------" << std::endl; //Création de la liste (des noms) des images std::vector<std::string> liste_image; for(int i=0;i<nbImage;i++) { std::string image_name = image_pref; if(i<10) { char nb[1] ; sprintf(nb, "%d", 0); image_name.append(nb); } char nb[1] ; sprintf(nb, "%d", i); image_name.append(nb); image_name.append(image_ext); liste_image.push_back(image_name); } std::vector<std::vector<cv::Vec3f> > objectPoints; std::vector<std::vector<cv::Vec2f> > imagePoints; for(int image=0;image<nbImage;image++) { std::string image_name = liste_image[image]; std::string img_path = folder_path+image_name; //importer une image cv::Mat mire = cv::imread(img_path); if(mire.empty()) { std::cerr<<"Il y a un problème dans la calibration de l'image, veuillez vérifier que le dossier est situé au même endroit que le binaire\n ou que vous ne vous êtes pas trompés dans les paramètres précédents\n"; return ; } imageSize = cv::Size(mire.cols,mire.rows); //déterminer les coordonnées 3D des points (dans le repère de la mire) std::vector<cv::Point3f> v ; for(int i=1;i<points_per_colum+1;i++) { for(int j=1;j<points_per_row+1;j++) { cv::Point3f pt(i*square_world_width,j*square_world_width,0); v.push_back(pt); } } objectPoints.push_back(cv::Mat(v)); //extraire les points dans l'image std::vector<cv::Point2f> corners; cv::Size patternSize(points_per_row,points_per_colum); bool corners_found = cv::findChessboardCorners(mire, patternSize, corners); if(!corners_found) { std::cout<<"erreur lors de l'extraction des coins de l'image"<<std::endl; std::cout<<"Verifiez les paramètres (nombres de coins par image)" << std::endl; std::cout<< "Si les paramètres sont justes, au moins l'une des images n'est pas utilisable"<<std::endl; flag = false; } imagePoints.push_back(cv::Mat(corners)); if(!flag) {break;} } if(flag) { //calibrer la caméra std::vector<cv::Mat> rvecs ; std::vector<cv::Mat> tvecs ; cv::calibrateCamera(objectPoints, imagePoints, imageSize, cameraMatrix, distCoeffs,rvecs, tvecs); //std::cout << "distor " << distCoeffs << std::endl; } } void writeMatToFile(cv::Mat & m, const char* filename) { std::ofstream fout(filename); if(!fout) { std::cout<<"File Not Opened"<<std::endl; return; } for(int i=0; i<m.rows; i++) { for(int j=0; j<m.cols; j++) { fout<<m.at<double>(i,j)<<"\t"; } fout<<std::endl; } fout.close(); } void readFileToMat(cv::Mat & m, const char* filename) { std::ifstream fin(filename); if(!fin) { std::cout<<"File Not Opened"<<std::endl; return; } for(int i=0; i<m.rows; i++) { for(int j=0; j<m.cols; j++) { fin>>m.at<double>(i,j); } } fin.close(); } int main( int argc, const char* argv[] ) { cv::Mat cameraMatrix = cv::Mat::zeros(3, 3, CV_64FC1); cv::Mat distCoeffs = cv::Mat::zeros(1, 5, CV_64FC1); //Output vector of distortion coefficients (k1,k2,p1,p2[,k3[,k4,k5,k6],[s1,s2,s3,s4]]) of 4, 5, 8 or 12 elements. calibrer(cameraMatrix, distCoeffs); //Sauvegarde de la matrice const char* filename = "calibration_matrix.txt"; writeMatToFile(cameraMatrix,filename); filename = "distorsion_matrix.txt"; writeMatToFile(distCoeffs,filename); std::cout << "param " << std::endl << cameraMatrix << std::endl; std::cout << "distor " << std::endl << distCoeffs << std::endl; cv::Mat m = cv::Mat::zeros(3, 3, CV_64FC1); filename = "calibration_matrix.txt"; readFileToMat(m,filename); std::cout << "read mat(calib matrix) " << std::endl << m<< std::endl; return 0; } <file_sep>/CMakeLists.txt # Ajustez en fonction de votre version de CMake cmake_minimum_required (VERSION 2.8) # Nom du projet project (TELLUS) find_package (OpenCV REQUIRED) ADD_EXECUTABLE(exe src/exe.cpp) ADD_EXECUTABLE(calib src/calib.cpp) # link avec les bibliothèques d'OpenCV target_link_libraries(exe ${OpenCV_LIBS} ) target_link_libraries(calib ${OpenCV_LIBS} )
038069fd4f95ea9b841381b1fad767cbdd0a17a2
[ "C++", "CMake" ]
4
C++
farrelNZL/industrialProject
d48dbe086df6ffd479ae3a78583f8d7dd0e08665
c548a9f1f99968d6b7be6eaaef6b7c6e96e9308d
refs/heads/master
<repo_name>DaCardinal/Skeleton<file_sep>/src/app/components/admin/views/test/test.module.js (function(){ 'use strict'; angular.module('app.view.test', []); })(); <file_sep>/src/app/components/components.module.js (function(){ 'use strict'; angular.module('skeleton.components', ['skeleton.layouts', 'skeleton.elements']); })(); <file_sep>/src/app/components/admin/views/test/test.config.js (function(){ 'use strict'; angular.module('app.view.test').config(moduleConfig); /*@ngInject */ function moduleConfig($stateProvider){ $stateProvider .state('skeleton.admin.profile', { url: '/admin/profile', templateUrl: 'app/components/admin/views/test/test.html', controller: 'TestController', controllerAs: 'vm' }); } })(); <file_sep>/src/app/components/admin/views/home/home.controller.js (function() { 'use strict'; angular .module('skeleton') .controller('HomeController', HomeController); /** @ngInject */ function HomeController($scope, $timeout, $state, toastr) { var vm = this; vm.awesomeThings = []; vm.classAnimation = ''; vm.creationDate = 1445477261635; vm.showToastr = showToastr; vm.testClick = testClick; vm.loginClick = loginClick; activate(); function activate() { $timeout(function() { vm.classAnimation = 'rubberBand'; }, 4000); } function showToastr() { toastr.info('Fork <a href="https://github.com/Swiip/generator-gulp-angular" target="_blank"><b>generator-gulp-angular</b></a>'); vm.classAnimation = ''; } function testClick() { $state.go('skeleton.admin.profile'); } function loginClick() { $state.go('skeleton-blank.login'); } } })(); <file_sep>/src/app/components/config.route.js (function() { 'use strict'; angular .module('skeleton.components') .config(routeConfig); /* @ngInject */ function routeConfig($stateProvider) { $stateProvider .state('skeleton-blank', { abstract: true, templateUrl: 'app/components/layouts/setup/setup-blank.html' }) .state('skeleton', { abstract: true, templateUrl: 'app/components/layouts/setup/setup.html', controller: 'SetupLayoutController', controllerAs: 'layoutController' }) .state('skeleton.admin', { abstract: true, views: { navbar: { templateUrl: 'app/components/elements/navbar/navbar.html', controller: 'NavBarController', controllerAs: 'vm' }, content: { template: '<div id="admin-panel-content-view" flex ui-view></div>' }, footer: { template: '<div ui-view="footer"></div>' } } }); } })(); // sidebarLeft: { // templateUrl: 'app/triangular/components/menu/menu.tmpl.html', // controller: 'MenuController', // controllerAs: 'vm' // }, <file_sep>/src/app/components/elements/navbar/navbar.controller.js (function(){ 'use strict'; angular.module('skeleton.elements').controller('NavBarController', NavBarController); /*@ngInject */ function NavBarController($log){ var vm = this; vm.title = 'sample navbar title'; vm.drawerToggle = drawerToggle; function drawerToggle() { var drawer = document.getElementsByClassName('mdl-layout__drawer')[0]; drawer.classList.toggle("is-visible"); } } })(); <file_sep>/src/app/components/layouts/setup/setup.directive.js (function(){ 'use strict'; angular.module('skeleton.layouts').directive('skeletonDefaultContent', skeletonDefaultContent); /*@ngInject */ function skeletonDefaultContent($rootScope, $compile, $templateRequest, $timeout){ var directive = { link: link, replace: true, restrict: 'A' } return directive; function link($scope, $element){ $scope.$on('$stateChangeStart', scrollToTop); $scope.$on('$viewContentLoaded', NQContent); function scrollToTop(){ $element.scrollTop(0); } function NQContent(){ var contentView = $element.find('#admin-panel-content-view'); $templateRequest('app/components/elements/footer/footer.html') .then(function(template){ var linkFn = $compile(template); var content = linkFn($scope); contentView.append(content); }); //Re-register all components $timeout(function() { componentHandler.upgradeAllRegistered(); }); // $rootScope.$broadcast('$mdContentLoaded', $element); } } } })(); <file_sep>/src/app/components/admin/views/test/test.controller.js (function(){ 'use strict'; angular.module('app.view.test').controller('TestController', TestController); /*@ngInject */ function TestController($state){ var vm = this; vm.testTitle = "Sample Test title"; vm.loginClick = loginClick; vm.homeClick = homeClick; //////////////// function loginClick() { $state.go('skeleton-blank.login'); } function homeClick() { $state.go('home'); } } })(); <file_sep>/src/app/components/layouts/setup/layout.controller.js (function(){ 'use strict'; angular.module('skeleton.layouts').controller('SetupLayoutController', SetupLayoutController); /*@ngInject */ function SetupLayoutController() { var vm = this; vm.pageTitle = 'sample layout title'; } })(); <file_sep>/src/app/components/layouts/layouts.module.js (function(){ 'use strict'; angular.module('skeleton.layouts', []); })(); <file_sep>/src/app/components/elements/footer/footer.controller.js (function(){ 'use strict'; angular.module('skeleton.elements').controller('FooterController', FooterController); /*@ngInject */ function FooterController(){ var vm = this; vm.title = 'Sample footer title title'; vm.copyright = 'Copyright (c) 2015 <NAME> All Rights Reserved.'; } })();
71ad9851a6aea7f7bd5fae4879d9866a16974db0
[ "JavaScript" ]
11
JavaScript
DaCardinal/Skeleton
2872ca2bd659e2ed689aa7062dbc2c7d3d69254a
b0b9a8ae3561d860d239fef0fc19bb9e01068232
refs/heads/master
<file_sep>package net.tomp2p.rpc; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandler; import io.netty.util.concurrent.EventExecutorGroup; import net.tomp2p.connection.ChannelClientConfiguration; import net.tomp2p.connection.ChannelCreator; import net.tomp2p.connection.ChannelServerConficuration; import net.tomp2p.connection.PeerConnection; import net.tomp2p.connection.PipelineFilter; import net.tomp2p.futures.BaseFutureAdapter; import net.tomp2p.futures.FutureChannelCreator; import net.tomp2p.futures.FutureDirect; import net.tomp2p.futures.FuturePeerConnection; import net.tomp2p.futures.FutureResponse; import net.tomp2p.futures.ProgressListener; import net.tomp2p.message.Buffer; import net.tomp2p.message.CountConnectionOutboundHandler; import net.tomp2p.message.Message; import net.tomp2p.p2p.Peer; import net.tomp2p.p2p.PeerMaker; import net.tomp2p.p2p.builder.SendDirectBuilder; import net.tomp2p.peers.Number160; import net.tomp2p.peers.PeerAddress; import net.tomp2p.utils.Pair; import net.tomp2p.utils.Timings; import net.tomp2p.utils.Utils; import org.junit.Assert; import org.junit.Test; public class TestDirect { @Test public void testDirectMessage() throws Exception { testDirectMessage(true); testDirectMessage(false); } private void testDirectMessage(boolean wait) throws Exception { Peer sender = null; Peer recv1 = null; ChannelCreator cc = null; final AtomicInteger replyComplete = new AtomicInteger(0); final AtomicInteger replyNotComplete = new AtomicInteger(0); final AtomicInteger progressComplete = new AtomicInteger(0); final AtomicInteger progressNotComplete = new AtomicInteger(0); try { PeerMaker pm1 = new PeerMaker(new Number160("0x50")).p2pId(55).ports(2424); ChannelServerConficuration css = pm1.createDefaultChannelServerConfiguration(); css.idleTCPSeconds(Integer.MAX_VALUE); pm1.channelServerConfiguration(css); sender = pm1.makeAndListen(); PeerMaker pm2 = new PeerMaker(new Number160("0x20")).p2pId(55).ports(8088); pm2.channelServerConfiguration(css); recv1 = pm2.makeAndListen(); recv1.setRawDataReply(new RawDataReply() { @Override public Buffer reply(PeerAddress sender, Buffer requestBuffer, boolean complete) throws Exception { System.err.println("reply 2 ? " + complete); ByteBuf replyBuffer = Unpooled.buffer(50); replyBuffer.writerIndex(50); if (complete) { replyComplete.incrementAndGet(); return new Buffer(replyBuffer, 100); } else { replyNotComplete.incrementAndGet(); return new Buffer(replyBuffer, 100); } } }); FutureChannelCreator fcc = sender.getConnectionBean().reservation().create(0, 1); fcc.awaitUninterruptibly(); cc = fcc.getChannelCreator(); SendDirectBuilder sendDirectBuilder = new SendDirectBuilder(sender, (PeerAddress) null); sendDirectBuilder.setStreaming(); sendDirectBuilder.idleTCPSeconds(Integer.MAX_VALUE); byte[] me = new byte[50]; Buffer b = new Buffer(Unpooled.compositeBuffer(), 100); b.addComponent(Unpooled.wrappedBuffer(me)); if (!wait) { ByteBuf replyBuffer = Unpooled.buffer(50); replyBuffer.writerIndex(50); b.addComponent(replyBuffer); } sendDirectBuilder.setBuffer(b); sendDirectBuilder.progressListener(new ProgressListener() { @Override public void progress(final Message interMediateMessage) { if (interMediateMessage.isDone()) { progressComplete.incrementAndGet(); System.err.println("progress 1 ? done"); } else { progressNotComplete.incrementAndGet(); System.err.println("progress 1 ? not done"); } } }); FutureResponse fr = sender.getDirectDataRPC().send(recv1.getPeerAddress(), sendDirectBuilder, cc); if (wait) { Thread.sleep(500); ByteBuf replyBuffer = Unpooled.buffer(50); replyBuffer.writerIndex(50); b.addComponent(replyBuffer); } fr.progress(); System.err.println("progres"); // we are not done yet! // now we are done fr.awaitUninterruptibly(); if (wait) { Assert.assertEquals(1, progressComplete.get()); Assert.assertEquals(1, progressNotComplete.get()); Assert.assertEquals(1, replyComplete.get()); Assert.assertEquals(1, replyNotComplete.get()); } else { Assert.assertEquals(1, progressComplete.get()); Assert.assertEquals(1, progressNotComplete.get()); Assert.assertEquals(2, replyComplete.get()); Assert.assertEquals(0, replyNotComplete.get()); } Assert.assertEquals(true, fr.isSuccess()); } finally { if (cc != null) { cc.shutdown().awaitListenersUninterruptibly(); } if (sender != null) { sender.shutdown().await(); } if (recv1 != null) { recv1.shutdown().await(); } } } @Test public void testDirectMessage1() throws Exception { Peer sender = null; Peer recv1 = null; ChannelCreator cc = null; try { sender = new PeerMaker(new Number160("0x50")).p2pId(55).ports(2424).makeAndListen(); recv1 = new PeerMaker(new Number160("0x20")).p2pId(55).ports(8088).makeAndListen(); recv1.setObjectDataReply(new ObjectDataReply() { @Override public Object reply(PeerAddress sender, Object request) throws Exception { return "yes"; } }); FutureChannelCreator fcc = sender.getConnectionBean().reservation().create(0, 2); fcc.awaitUninterruptibly(); cc = fcc.getChannelCreator(); SendDirectBuilder sendDirectBuilder = new SendDirectBuilder(sender, (PeerAddress) null); sendDirectBuilder.setObject("test"); FutureResponse fd1 = sender.getDirectDataRPC() .send(recv1.getPeerAddress(), sendDirectBuilder, cc); FutureResponse fd2 = sender.getDirectDataRPC() .send(recv1.getPeerAddress(), sendDirectBuilder, cc); fd1.awaitUninterruptibly(); fd2.awaitUninterruptibly(); System.err.println(fd1.getFailedReason()); Assert.assertEquals(true, fd1.isSuccess()); Assert.assertEquals(true, fd2.isSuccess()); Object ret = fd1.getResponse().getBuffer(0).object(); Assert.assertEquals("yes", ret); } finally { if (cc != null) { cc.shutdown().awaitListenersUninterruptibly(); } if (sender != null) { sender.shutdown().await(); } if (recv1 != null) { recv1.shutdown().await(); } } } @Test public void testOrder() throws Exception { Peer sender = null; Peer recv1 = null; ChannelCreator cc = null; try { sender = new PeerMaker(new Number160("0x9876")).p2pId(55).ports(2424).makeAndListen(); recv1 = new PeerMaker(new Number160("0x1234")).p2pId(55).ports(8088).makeAndListen(); recv1.setObjectDataReply(new ObjectDataReply() { @Override public Object reply(PeerAddress sender, Object request) throws Exception { Integer i = (Integer) request; System.err.println("got " + i); return i + 1; } }); for (int i = 0; i < 500; i++) { FutureChannelCreator fcc = sender.getConnectionBean().reservation().create(0, 1); fcc.awaitUninterruptibly(); cc = fcc.getChannelCreator(); SendDirectBuilder sendDirectBuilder = new SendDirectBuilder(sender, (PeerAddress) null); sendDirectBuilder.setObject((Object) Integer.valueOf(i)); FutureResponse futureData = sender.getDirectDataRPC().send(recv1.getPeerAddress(), sendDirectBuilder, cc); Utils.addReleaseListener(cc, futureData); futureData.addListener(new BaseFutureAdapter<FutureResponse>() { @Override public void operationComplete(FutureResponse future) throws Exception { // the future object might be null if the future failed, // e.g due to shutdown System.err.println(future.getResponse().getBuffer(0).object()); } }); } System.err.println("done"); Timings.sleep(2000); } finally { if (cc != null) { cc.shutdown().awaitListenersUninterruptibly(); } if (sender != null) { sender.shutdown().await(); } if (recv1 != null) { recv1.shutdown().await(); } } } @Test public void testDirectReconnect() throws Exception { Peer sender = null; Peer recv1 = null; try { final CountConnectionOutboundHandler ccohTCP = new CountConnectionOutboundHandler(); final CountConnectionOutboundHandler ccohUDP = new CountConnectionOutboundHandler(); PipelineFilter pf = new PipelineFilter() { @Override public Map<String, Pair<EventExecutorGroup, ChannelHandler>> filter(Map<String, Pair<EventExecutorGroup, ChannelHandler>> channelHandlers, boolean tcp, boolean client) { Map<String, Pair<EventExecutorGroup, ChannelHandler>> retVal = new LinkedHashMap<String, Pair<EventExecutorGroup, ChannelHandler>>(); retVal.put("counter", new Pair<EventExecutorGroup, ChannelHandler>(null, tcp? ccohTCP:ccohUDP)); retVal.putAll(channelHandlers); return retVal; } }; ChannelServerConficuration csc = PeerMaker.createDefaultChannelServerConfiguration(); ChannelClientConfiguration ccc = PeerMaker.createDefaultChannelClientConfiguration(); csc.pipelineFilter(pf); ccc.pipelineFilter(pf); sender = new PeerMaker(new Number160("0x50")).p2pId(55).setEnableMaintenance(false).ports(2424).channelClientConfiguration(ccc).channelServerConfiguration(csc).makeAndListen(); recv1 = new PeerMaker(new Number160("0x20")).p2pId(55).setEnableMaintenance(false).ports(8088).channelClientConfiguration(ccc).channelServerConfiguration(csc).makeAndListen(); recv1.setObjectDataReply(new ObjectDataReply() { @Override public Object reply(PeerAddress sender, Object request) throws Exception { return "yes"; } }); FuturePeerConnection peerConnection = sender.createPeerConnection(recv1.getPeerAddress()); ccohTCP.reset(); ccohUDP.reset(); FutureDirect fd1 = sender.sendDirect(peerConnection).setObject("test") .connectionTimeoutTCPMillis(2000).idleTCPSeconds(10 * 1000).start(); fd1.awaitListenersUninterruptibly(); Assert.assertEquals(true, fd1.isSuccess()); Assert.assertEquals(1, ccohTCP.total()); Assert.assertEquals(0, ccohUDP.total()); Timings.sleep(2000); System.err.println("send second with the same connection"); FutureDirect fd2 = sender.sendDirect(peerConnection).setObject("test").start(); fd2.awaitUninterruptibly(); Assert.assertEquals(1, ccohTCP.total()); Assert.assertEquals(0, ccohUDP.total()); Assert.assertEquals(true, fd2.isSuccess()); peerConnection.close().await(); System.err.println("done"); } finally { if (sender != null) { sender.shutdown().await(); } if (recv1 != null) { recv1.shutdown().await(); } } } @Test public void testDirect2() throws Exception { Peer sender = null; Peer recv1 = null; try { final CountConnectionOutboundHandler ccohTCP = new CountConnectionOutboundHandler(); final CountConnectionOutboundHandler ccohUDP = new CountConnectionOutboundHandler(); PipelineFilter pf = new PipelineFilter() { @Override public Map<String, Pair<EventExecutorGroup, ChannelHandler>> filter(Map<String, Pair<EventExecutorGroup, ChannelHandler>> channelHandlers, boolean tcp, boolean client) { Map<String, Pair<EventExecutorGroup, ChannelHandler>> retVal = new LinkedHashMap<String, Pair<EventExecutorGroup, ChannelHandler>>(); retVal.put("counter", new Pair<EventExecutorGroup, ChannelHandler>(null, tcp? ccohTCP:ccohUDP)); retVal.putAll(channelHandlers); return retVal; } }; ChannelServerConficuration csc = PeerMaker.createDefaultChannelServerConfiguration(); ChannelClientConfiguration ccc = PeerMaker.createDefaultChannelClientConfiguration(); csc.pipelineFilter(pf); ccc.pipelineFilter(pf); sender = new PeerMaker(new Number160("0x50")).p2pId(55).ports(2424).setEnableMaintenance(false) .channelClientConfiguration(ccc).channelServerConfiguration(csc).makeAndListen(); recv1 = new PeerMaker(new Number160("0x20")).p2pId(55).ports(8088).setEnableMaintenance(false) .channelClientConfiguration(ccc).channelServerConfiguration(csc).makeAndListen(); recv1.setObjectDataReply(new ObjectDataReply() { @Override public Object reply(PeerAddress sender, Object request) throws Exception { return "yes"; } }); FuturePeerConnection peerConnection = sender.createPeerConnection(recv1.getPeerAddress(), 8000); ccohTCP.reset(); ccohUDP.reset(); FutureDirect fd1 = sender.sendDirect(peerConnection).setObject("test") .connectionTimeoutTCPMillis(2000).idleTCPSeconds(5).start(); fd1.awaitUninterruptibly(); Assert.assertEquals(1, ccohTCP.total()); Timings.sleep(7000); FutureDirect fd2 = sender.sendDirect(peerConnection).setObject("test").start(); fd2.awaitUninterruptibly(); peerConnection.close().await(); Assert.assertEquals(2, ccohTCP.total()); System.out.println("done"); } finally { if (sender != null) { sender.shutdown().await(); } if (recv1 != null) { recv1.shutdown().await(); } } } } <file_sep>package net.tomp2p.p2p; public interface ReplicationFactor extends PeerInit { int replicationFactor(); } <file_sep>/* * Copyright 2013 <NAME>, <NAME> * * 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 net.tomp2p.synchronization; import net.tomp2p.p2p.Peer; import net.tomp2p.peers.PeerAddress; public class PeerSync { private final SyncRPC syncRPC; private final Peer peer; private final int blockSize; /** * Create a PeerSync class and register the RPC. Be aware that if you use * {@link ReplicationSync}, than use the PeerSync that was created in that * class. * * @param peer * The peer * @param blockSize * The block size as the basis for the checksums, RSync uses a * default of 700 */ public PeerSync(Peer peer, final int blockSize) { this.peer = peer; this.syncRPC = new SyncRPC(peer.getPeerBean(), peer.getConnectionBean(), blockSize); this.blockSize = blockSize; } public Peer peer() { return peer; } public SyncRPC syncRPC() { return syncRPC; } public SyncBuilder synchronize(PeerAddress other) { return new SyncBuilder(this, other, blockSize); } } <file_sep>/* * Copyright 2009 <NAME> * * 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 net.tomp2p.connection; import java.security.KeyPair; import net.tomp2p.p2p.MaintenanceTask; import net.tomp2p.peers.PeerAddress; import net.tomp2p.peers.PeerMap; import net.tomp2p.peers.PeerStatusListener; import net.tomp2p.p2p.Replication; import net.tomp2p.p2p.ReplicationExecutor; import net.tomp2p.rpc.BloomfilterFactory; import net.tomp2p.storage.StorageLayer; import net.tomp2p.storage.TrackerStorage; /** * A bean that holds non-sharable (unique for each peer) configuration settings for the peer. The sharable * configurations are stored in {@link ConnectionBean}. * * @author <NAME> */ public class PeerBean { private KeyPair keyPair; private PeerAddress serverPeerAddress; private PeerMap peerMap; private PeerStatusListener[] peerStatusListeners; private StorageLayer storage; private TrackerStorage trackerStorage; private Replication replicationStorage; private Replication replicationTracker; private BloomfilterFactory bloomfilterFactory; private MaintenanceTask maintenanceTask; private ReplicationExecutor replicationExecutor; /* * private Statistics statistics; private Peer peer; */ /** * Creates a bean with a key pair. * * @param keyPair * The key pair that holds private public key */ public PeerBean(final KeyPair keyPair) { this.keyPair = keyPair; } /** * @return The key pair that holds private public key */ public KeyPair keyPair() { return keyPair; } /** * @return The address of this peer. This address may change. */ public PeerAddress serverPeerAddress() { return serverPeerAddress; } /** * @param serverPeerAddress * The new address of this peer. * @return This class */ public PeerBean serverPeerAddress(final PeerAddress serverPeerAddress) { this.serverPeerAddress = serverPeerAddress; return this; } /** * @return The public and private key */ public KeyPair getKeyPair() { return keyPair; } /** * @param keyPair * The public and private key * @return This class */ public PeerBean keyPair(final KeyPair keyPair) { this.keyPair = keyPair; return this; } /** * @return The peermap that stores neighbors */ public PeerMap peerMap() { return peerMap; } /** * @param peerMap * The peermap that stores neighbors * @return This class */ public PeerBean peerMap(final PeerMap peerMap) { this.peerMap = peerMap; return this; } /** * @return The listeners that are interested in the peer status, e.g., peer is found to be online, or a peer is * offline or failed to respond in time. */ public PeerStatusListener[] peerStatusListeners() { return peerStatusListeners; } /** * @param peerStatusListeners * The listeners that are interested in the peer status, e.g., peer is found to be online, or a peer is * offline or failed to respond in time * @return This class */ public PeerBean peerStatusListeners(final PeerStatusListener[] peerStatusListeners) { this.peerStatusListeners = peerStatusListeners; return this; } /** * @param storage * The storage where the key value pairs are stored * @return This class */ public PeerBean storage(final StorageLayer storage) { this.storage = storage; return this; } /** * @return The storage where the key value pairs are stored */ public StorageLayer storage() { return storage; } /** * Set the replication class that stores who is responsible for what. The backend is typically implemented together * with the storage. * * @param replicationStorage * The replication used for storage * @return This class */ public PeerBean replicationStorage(final Replication replicationStorage) { this.replicationStorage = replicationStorage; return this; } /** * @return The replication class that stores who is responsible for what. The backend is typically implemented * together with the storage. */ public Replication replicationStorage() { return replicationStorage; } public PeerBean replicationTracker(final Replication replicationTracker) { this.replicationTracker = replicationTracker; return this; } public Replication getReplicationTracker() { return replicationTracker; } public PeerBean trackerStorage(TrackerStorage trackerStorage) { this.trackerStorage = trackerStorage; return this; } public TrackerStorage trackerStorage() { return trackerStorage; } public PeerBean bloomfilterFactory(final BloomfilterFactory bloomfilterFactory) { this.bloomfilterFactory = bloomfilterFactory; return this; } public BloomfilterFactory bloomfilterFactory() { return bloomfilterFactory; } public PeerBean maintenanceTask(MaintenanceTask maintenanceTask) { this.maintenanceTask = maintenanceTask; return this; } public MaintenanceTask maintenanceTask() { return maintenanceTask; } public ReplicationExecutor replicationExecutor() { return replicationExecutor; } public PeerBean replicationExecutor(ReplicationExecutor replicationExecutor) { this.replicationExecutor = replicationExecutor; return this; } } <file_sep>/* * Copyright 2013 <NAME> * * 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 net.tomp2p.p2p; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Random; import java.util.TreeSet; import net.tomp2p.Utils2; import net.tomp2p.futures.BaseFuture; import net.tomp2p.futures.FutureBootstrap; import net.tomp2p.futures.FuturePut; import net.tomp2p.peers.Number160; import net.tomp2p.peers.Number640; import net.tomp2p.peers.PeerAddress; import net.tomp2p.peers.PeerMap; import net.tomp2p.storage.Data; import net.tomp2p.utils.Timings; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author <NAME> * */ public class TestReplication { private static final Random RND = new Random(42L); private static final Random RND2 = new Random(42L); private static final int PORT = 4001; private static final int SECOND = 1000; private static final Logger LOG = LoggerFactory.getLogger(TestReplication.class); private static final int NR_PEERS = 100; private static final int NINE_SECONDS = 9000; /** * Test the direct replication, where the initiator is also the responsible peer. * * @throws Exception . */ /*@Test public void testDirectReplication() throws Exception { Peer master = null; try { // setup Peer[] peers = Utils2.createNodes(NR_PEERS, RND, PORT); master = peers[0]; List<FutureBootstrap> tmp = new ArrayList<FutureBootstrap>(); for (int i = 0; i < peers.length; i++) { if (peers[i] != master) { FutureBootstrap res = peers[i].bootstrap().setPeerAddress(master.getPeerAddress()).start(); tmp.add(res); } } int i = 0; for (FutureBootstrap fm : tmp) { fm.awaitUninterruptibly(); if (fm.isFailed()) { System.err.println(fm.getFailedReason()); } Assert.assertEquals(true, fm.isSuccess()); System.err.println("i:" + (++i)); } final AtomicInteger counter = new AtomicInteger(0); // New storage class to count the puts. final class MyStorageMemory extends StorageMemory { @Override public PutStatus put(final Number160 locationKey, final Number160 domainKey, final Number160 contentKey, final Data newData, final PublicKey publicKey, final boolean putIfAbsent, final boolean domainProtection) { System.err.println("here"); counter.incrementAndGet(); return super.put(locationKey, domainKey, contentKey, newData, publicKey, putIfAbsent, domainProtection); } } final int peerNr = 50; final int repetitions = 5; peers[peerNr].getPeerBean().setStorage(new MyStorageMemory()); FutureCreate<FutureDHT> futureCreate = new FutureCreate<FutureDHT>() { @Override public void repeated(final FutureDHT future) { System.err.println("chain1..."); } }; FutureDHT fdht = peers[1].put(peers[peerNr].getPeerID()).setData(new Data("test")).setRefreshSeconds(2) .setDirectReplication().setFutureCreate(futureCreate).start(); Timings.sleep(NINE_SECONDS); Assert.assertEquals(repetitions, counter.get()); fdht.shutdown(); System.err.println("stop chain1"); final AtomicInteger counter2 = new AtomicInteger(0); futureCreate = new FutureCreate<FutureDHT>() { @Override public void repeated(final FutureDHT future) { System.err.println("chain2..."); counter2.incrementAndGet(); } }; FutureDHT fdht2 = peers[2].remove(peers[peerNr].getPeerID()).setRefreshSeconds(1) .setRepetitions(repetitions).setFutureCreate(futureCreate).setDirectReplication().start(); Timings.sleep(NINE_SECONDS); Assert.assertEquals(repetitions, counter.get()); Assert.assertEquals(true, fdht2.isSuccess()); Assert.assertEquals(repetitions, counter2.get()); } finally { if (master != null) { master.halt(); } } }*/ /*@Test public void testActiveReplicationRefresh() throws Exception { Peer master = null; try { // setup Peer[] peers = Utils2.createNodes(100, rnd, 4001, 5 * 1000, true); master = peers[0]; Number160 locationKey = master.getPeerID().xor(new Number160(77)); // store Data data = new Data("Test"); FutureDHT futureDHT = master.put(locationKey).setData(data).start(); futureDHT.awaitUninterruptibly(); futureDHT.getFutureRequests().awaitUninterruptibly(); Assert.assertEquals(true, futureDHT.isSuccess()); // bootstrap List<FutureBootstrap> tmp2 = new ArrayList<FutureBootstrap>(); for (int i = 0; i < peers.length; i++) { if (peers[i] != master) { tmp2.add(peers[i].bootstrap().setPeerAddress(master.getPeerAddress()).start()); } } for (FutureBootstrap fm : tmp2) { fm.awaitUninterruptibly(); Assert.assertEquals(true, fm.isSuccess()); } for (int i = 0; i < peers.length; i++) { for (BaseFuture baseFuture : peers[i].getPendingFutures().keySet()) baseFuture.awaitUninterruptibly(); } // wait for refresh Thread.sleep(6000); // TreeSet<PeerAddress> tmp = new TreeSet<PeerAddress>(master.getPeerBean().getPeerMap() .createPeerComparator(locationKey)); tmp.add(master.getPeerAddress()); for (int i = 0; i < peers.length; i++) tmp.add(peers[i].getPeerAddress()); int i = 0; for (PeerAddress closest : tmp) { final FutureChannelCreator fcc = master.getConnectionBean().getConnectionReservation() .reserve(1); fcc.awaitUninterruptibly(); ChannelCreator cc = fcc.getChannelCreator(); FutureResponse futureResponse = master.getStoreRPC().get(closest, locationKey, DHTBuilder.DEFAULT_DOMAIN, null, null, null, false, false, false, false, cc, false); futureResponse.awaitUninterruptibly(); master.getConnectionBean().getConnectionReservation().release(cc); Assert.assertEquals(true, futureResponse.isSuccess()); Assert.assertEquals(1, futureResponse.getResponse().getDataMap().size()); i++; if (i >= 5) break; } } finally { if (master != null) { master.shutdown().await(); } } }*/ @Test public void testDataloss() throws IOException, InterruptedException { Peer p1 = null; Peer p2 = null; Peer p3 = null; try { p1 = new PeerMaker(Number160.createHash("111")).setEnableIndirectReplication(true).ports(PORT) .makeAndListen(); p2 = new PeerMaker(Number160.createHash("22")).setEnableIndirectReplication(true).ports(PORT+1) .makeAndListen(); p3 = new PeerMaker(Number160.createHash("33")).setEnableIndirectReplication(true).ports(PORT+2) .makeAndListen(); Utils2.perfectRouting(p1, p2, p3); Number160 locationKey = Number160.createHash("test1"); FuturePut fp = p2.put(locationKey).setData(new Data("hallo")).setRequestP2PConfiguration(new RequestP2PConfiguration(2, 10, 0)).start(); fp.awaitUninterruptibly(); getReplicasCount(locationKey, p1, p2, p3); // p3.announceShutdown().start().awaitUninterruptibly(); p3.shutdown().awaitUninterruptibly(); Thread.sleep(500); p3 = new PeerMaker(locationKey).setEnableIndirectReplication(true).ports(PORT+3).makeAndListen(); System.out.println("now we add a peer that matches perfectly the key " + locationKey+ ". This will now become the responsible peer"); p3.bootstrap().setPeerAddress(p1.getPeerAddress()).start().awaitUninterruptibly(); getReplicasCount(locationKey, p1, p2, p3); Thread.sleep(500); p1.announceShutdown().start().awaitUninterruptibly(); p1.shutdown().awaitUninterruptibly(); p2.announceShutdown().start().awaitUninterruptibly(); p2.shutdown().awaitUninterruptibly(); Thread.sleep(500); int count = getReplicasCount(locationKey, p1, p2, p3); Assert.assertEquals(1, count); } finally { if (p1 != null && !p1.isShutdown()) { p1.shutdown().awaitUninterruptibly(); } if (p2 != null && !p2.isShutdown()) { p2.shutdown().awaitUninterruptibly(); } if (p3 != null && !p3.isShutdown()) { p3.shutdown().awaitUninterruptibly(); } } } @Test public void testDataloss2() throws IOException, InterruptedException { Peer p1 = null; Peer p2 = null; Peer p3 = null; try { p1 = new PeerMaker(Number160.createHash("111")).setEnableIndirectReplication(true).ports(PORT) .makeAndListen(); p2 = new PeerMaker(Number160.createHash("22")).setEnableIndirectReplication(true).ports(PORT+1) .makeAndListen(); p3 = new PeerMaker(Number160.createHash("33")).setEnableIndirectReplication(true).ports(PORT+2) .makeAndListen(); Utils2.perfectRouting(p1, p2, p3); Number160 locationKey = Number160.createHash("test1"); FuturePut fp = p2.put(locationKey).setData(new Data("hallo")).setRequestP2PConfiguration(new RequestP2PConfiguration(2, 10, 0)).start(); fp.awaitUninterruptibly(); getReplicasCount(locationKey, p1, p2, p3); p3.announceShutdown().start().awaitUninterruptibly(); p3.shutdown().awaitUninterruptibly(); p1.announceShutdown().start().awaitUninterruptibly(); p1.shutdown().awaitUninterruptibly(); Thread.sleep(500); getReplicasCount(locationKey, p1, p2, p3); // p3 = new PeerMaker(locationKey).setEnableIndirectReplication(true).ports(PORT+3).makeAndListen(); System.out.println("now we add a peer that matches perfectly the key " + locationKey+ ". This will now become the responsible peer"); p3.bootstrap().setPeerAddress(p2.getPeerAddress()).start().awaitUninterruptibly(); p1 = new PeerMaker(Number160.createHash("1111")).setEnableIndirectReplication(true).ports(PORT+4) .makeAndListen(); p1.bootstrap().setPeerAddress(p2.getPeerAddress()).start().awaitUninterruptibly(); getReplicasCount(locationKey, p1, p2, p3); Thread.sleep(500); int count = getReplicasCount(locationKey, p1, p2, p3); Assert.assertEquals(2, count); } finally { if (p1 != null && !p1.isShutdown()) { p1.shutdown().awaitUninterruptibly(); } if (p2 != null && !p2.isShutdown()) { p2.shutdown().awaitUninterruptibly(); } if (p3 != null && !p3.isShutdown()) { p3.shutdown().awaitUninterruptibly(); } } } private static int getReplicasCount(Number160 key, Peer... peers) { int count = 0; Number160 locationKey = null; ArrayList<Number160> peerIds = new ArrayList<Number160>(); for(int i=0; i<peers.length; i++) if(!peers[i].isShutdown()) for(Map.Entry<Number640, Data> entry: peers[i].getPeerBean().storage().get().entrySet()){ locationKey = entry.getKey().getLocationKey(); if(locationKey.equals(key)){ count++; peerIds.add(peers[i].getPeerID()); System.out.println("key " + key + " FoundOn peers["+i+"]=" + peers[i].getPeerID()); //break; } } System.out.println("key " + key + " FoundOn "+count+" peers"); return count; } @Test public void testSimpleIndirectReplicationForward() throws Exception { final Random rnd = new Random(42L); Peer master = null; try { // setup Peer[] peers = Utils2.createNodes(2, rnd, PORT, new AutomaticFuture() { @Override public void futureCreated(BaseFuture future) { System.err.println("future created "+ future); } }, true); master = peers[0]; //print out info System.err.println("looking for "+searchPeer(Number160.createHash("2"), peers).getPeerAddress()+" in "); for(Peer peer:peers) { System.err.println(peer.getPeerAddress()); } //store data, the two peers do not know each other Data data = new Data("Test"); FuturePut futureDHT = master.put(Number160.createHash("2")).setData(data).start(); futureDHT.awaitUninterruptibly(); futureDHT.getFutureRequests().awaitUninterruptibly(); //now, do the routing, so that each peers know each other. The content should be moved Assert.assertEquals(false, peers[1].getPeerBean().storage().contains(new Number640(Number160.createHash("2"), Number160.ZERO, Number160.ZERO, Number160.ZERO))); Utils2.perfectRouting(peers); //we should see now the forward replication Thread.sleep(1000); //test it Assert.assertEquals(true, peers[1].getPeerBean().storage().contains(new Number640(Number160.createHash("2"), Number160.ZERO, Number160.ZERO, Number160.ZERO))); } finally { if (master != null) { master.shutdown().awaitUninterruptibly(); } } } /** * Test the indirect replication where the closest peer is responsible for a location key. * * @throws Exception . */ @Test public void testIndirectReplicationForward() throws Exception { Peer master = null; try { // setup Peer[] peers = Utils2.createNodes(NR_PEERS, RND2, PORT, new AutomaticFuture() { @Override public void futureCreated(BaseFuture future) { System.err.println("future created "+ future); } }, true); master = peers[0]; Number160 locationKey = new Number160(RND2); master.getPeerBean().peerMap(); // closest TreeSet<PeerAddress> tmp = new TreeSet<PeerAddress>(PeerMap.createComparator(locationKey)); tmp.add(master.getPeerAddress()); for (int i = 0; i < peers.length; i++) { tmp.add(peers[i].getPeerAddress()); } PeerAddress closest = tmp.iterator().next(); System.err.println("closest to " + locationKey + " is " + closest); // store Data data = new Data("Test"); FuturePut futureDHT = master.put(locationKey).setData(data).start(); futureDHT.awaitUninterruptibly(); futureDHT.getFutureRequests().awaitUninterruptibly(); Assert.assertEquals(true, futureDHT.isSuccess()); List<FutureBootstrap> tmp2 = new ArrayList<FutureBootstrap>(); Utils2.perfectRouting(peers); //for (int i = 0; i < peers.length; i++) { // if (peers[i] != master) { // tmp2.add(peers[i].bootstrap().setPeerAddress(master.getPeerAddress()).start()); // } //} for (FutureBootstrap fm : tmp2) { fm.awaitUninterruptibly(); Assert.assertEquals(true, fm.isSuccess()); } // wait for the replication Peer peerClose = searchPeer(closest, peers); int i = 0; // wait for 2.5 sec final int tests = 10; final int wait = 2500; while (!peerClose.getPeerBean().storage() .contains(new Number640(locationKey, Number160.ZERO, Number160.ZERO, Number160.ZERO))) { Timings.sleep(wait / tests); i++; if (i > tests) { break; } } Assert.assertEquals(true, peerClose.getPeerBean().storage() .contains(new Number640(locationKey, Number160.ZERO, Number160.ZERO, Number160.ZERO))); } finally { if (master != null) { master.shutdown().awaitUninterruptibly(); } } } /** * Test the replication with the following scenario: 2 peers online that store data, third peer joins. This means * for indirect replication, that the content need to be stored on peer 3 as well. * * @throws IOException . * @throws InterruptedException . */ /*@Test public void testReplication() throws IOException, InterruptedException { Peer p1 = null; try { p1 = new PeerMaker(Number160.createHash("1")).setEnableIndirectReplication(true).setPorts(PORT) .makeAndListen(); Peer p2 = new PeerMaker(Number160.createHash("2")).setEnableIndirectReplication(true).setMasterPeer(p1) .makeAndListen(); Peer p3 = new PeerMaker(Number160.createHash("3")).setEnableIndirectReplication(true).setMasterPeer(p1) .makeAndListen(); LOG.info("p1 = " + p1.getPeerAddress()); LOG.info("p2 = " + p2.getPeerAddress()); LOG.info("p3 = " + p3.getPeerAddress()); p2.bootstrap().setPeerAddress(p1.getPeerAddress()).start().awaitUninterruptibly(); p2.put(Number160.createHash("key")).setData(new Data("test")).start().awaitUninterruptibly(); LOG.info("storage done"); Thread.sleep(SECOND); LOG.info("new peer joins"); p3.bootstrap().setPeerAddress(p1.getPeerAddress()).start().awaitUninterruptibly(); Thread.sleep(SECOND); Data test = p3.getPeerBean().getStorage() .get(Number160.createHash("key"), DHTBuilder.DEFAULT_DOMAIN, Number160.ZERO); Assert.assertNotNull(test); } finally { if (p1 != null) { p1.halt(); } } }*/ /** * Search a Peer in a list. * * @param peerAddress * The peer to search for * @param peers * The list of peers * @return The found peer or null if not found */ private static Peer searchPeer(final PeerAddress peerAddress, final Peer[] peers) { for (Peer peer : peers) { if (peer.getPeerAddress().equals(peerAddress)) { return peer; } } return null; } private static Peer searchPeer(final Number160 locationKey, final Peer[] peers) { TreeSet<PeerAddress> tmp = new TreeSet<PeerAddress>(PeerMap.createComparator(locationKey)); for (int i = 0; i < peers.length; i++) { tmp.add(peers[i].getPeerAddress()); } PeerAddress peerAddress = tmp.iterator().next(); return searchPeer(peerAddress, peers); } } <file_sep>/* * Copyright 2009 <NAME> * * 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 net.tomp2p.p2p; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import net.tomp2p.connection.ChannelCreator; import net.tomp2p.connection.ConnectionBean; import net.tomp2p.connection.PeerBean; import net.tomp2p.connection.PeerConnection; import net.tomp2p.connection.PeerCreator; import net.tomp2p.futures.BaseFuture; import net.tomp2p.futures.BaseFutureAdapter; import net.tomp2p.futures.FutureChannelCreator; import net.tomp2p.futures.FutureDone; import net.tomp2p.futures.FutureLateJoin; import net.tomp2p.futures.FuturePeerConnection; import net.tomp2p.p2p.builder.AddBuilder; import net.tomp2p.p2p.builder.AddTrackerBuilder; import net.tomp2p.p2p.builder.BootstrapBuilder; import net.tomp2p.p2p.builder.BroadcastBuilder; import net.tomp2p.p2p.builder.DigestBuilder; import net.tomp2p.p2p.builder.DiscoverBuilder; import net.tomp2p.p2p.builder.GetBuilder; import net.tomp2p.p2p.builder.GetTrackerBuilder; import net.tomp2p.p2p.builder.ParallelRequestBuilder; import net.tomp2p.p2p.builder.PingBuilder; import net.tomp2p.p2p.builder.PutBuilder; import net.tomp2p.p2p.builder.RemoveBuilder; import net.tomp2p.p2p.builder.SendBuilder; import net.tomp2p.p2p.builder.SendDirectBuilder; import net.tomp2p.p2p.builder.ShutdownBuilder; import net.tomp2p.peers.Number160; import net.tomp2p.peers.PeerAddress; import net.tomp2p.rpc.BroadcastRPC; import net.tomp2p.rpc.DirectDataRPC; import net.tomp2p.rpc.NeighborRPC; import net.tomp2p.rpc.ObjectDataReply; import net.tomp2p.rpc.PeerExchangeRPC; import net.tomp2p.rpc.PingRPC; import net.tomp2p.rpc.QuitRPC; import net.tomp2p.rpc.RawDataReply; import net.tomp2p.rpc.StorageRPC; //import net.tomp2p.rpc.TaskRPC; import net.tomp2p.rpc.TrackerRPC; //import net.tomp2p.task.AsyncTask; //import net.tomp2p.task.Worker; /** * This is the main class to start DHT operations. This class makes use of the build pattern and for each DHT operation, * a builder class is returned. The main operations can be initiated with {@link #put(Number160)}, * {@link #get(Number160)}, {@link #add(Number160)}, {@link #addTracker(Number160)}, {@link #getTracker(Number160)}, * {@link #remove(Number160)}, {@link #submit(Number160, Worker)}, {@link #send(Number160)}, {@link #sendDirect()}, * {@link #broadcast(Number160)}. Each of those operations return a builder that offers more options. One of the main * difference to a "regular" DHT is that TomP2P can store a map (key-values) instead of just values. To distinguish * those, the keys are termed location key (for finding the right peer in the network), and content key (to store more * than one value on a peer). For the put builder e.g. the following options can be set: * * <ul> * <li>{@link PutBuilder#setData(Number160, net.tomp2p.storage.Data)} - puts a content key with a value</li> * <li>{@link PutBuilder#setDataMap(Map) - puts multiple content key / values at once</li> * <li>{@link PutBuilder#setPutIfAbsent() - only puts data if its not already on the peers</li> * <li>...</li> * </ul> * * Furthermore, TomP2P also provides to store keys in different domains to avoid key collisions * ({@link PutBuilder#setDomainKey(Number160)). * * @author <NAME> */ public class Peer { // As soon as the user calls listen, this connection handler is set private final PeerCreator peerCreator; // the id of this node private final Number160 peerId; // the p2p network identifier, two different networks can have the same // ports private final int p2pID; // Distributed private DistributedHashTable distributedHashMap; private DistributedTracker distributedTracker; private DistributedRouting distributedRouting; //private DistributedTask distributedTask; // private AsyncTask asyncTask; // RPC private PingRPC pingRCP; private StorageRPC storageRPC; private NeighborRPC neighborRPC; private QuitRPC quitRCP; private PeerExchangeRPC peerExchangeRPC; private DirectDataRPC directDataRPC; private TrackerRPC trackerRPC; // private TaskRPC taskRPC; private BroadcastRPC broadcastRPC; private volatile boolean shutdown = false; private List<AutomaticFuture> automaticFutures = null; private List<Shutdown> shutdownListeners = Collections.synchronizedList(new ArrayList<Shutdown>()); // // final private ConnectionConfiguration configuration; // final private Map<BaseFuture, Long> pendingFutures = Collections.synchronizedMap(new CacheMap<BaseFuture, Long>( // 1000, true)); // private boolean masterFlag = true; // private List<ScheduledFuture<?>> scheduledFutures = Collections // .synchronizedList(new ArrayList<ScheduledFuture<?>>()); // final private List<PeerListener> listeners = new ArrayList<PeerListener>(); // private Timer timer; // final public static int BLOOMFILTER_SIZE = 1024; // // final private int maintenanceThreads; // final private int replicationThreads; // final private int replicationRefreshMillis; // final private PeerMap peerMap; // final private int maxMessageSize; // private volatile boolean shutdown = false; /** * Create a peer. Please use {@link PeerMaker} to create a class * * @param p2pID * The P2P ID * @param peerId * The Id of the peer * @param peerCreator * The peer creator that holds the peer bean and connection bean */ Peer(final int p2pID, final Number160 peerId, final PeerCreator peerCreator) { this.p2pID = p2pID; this.peerId = peerId; this.peerCreator = peerCreator; } PeerCreator peerCreator() { return peerCreator; } public PingRPC pingRPC() { if (pingRCP == null) { throw new RuntimeException("Not enabled, please enable this RPC in PeerMaker"); } return pingRCP; } public Peer pingRPC(PingRPC handshakeRPC) { this.pingRCP = handshakeRPC; return this; } public StorageRPC getStoreRPC() { if (storageRPC == null) { throw new RuntimeException("Not enabled, please enable this RPC in PeerMaker"); } return storageRPC; } public void setStorageRPC(StorageRPC storageRPC) { this.storageRPC = storageRPC; } public NeighborRPC getNeighborRPC() { if (neighborRPC == null) { throw new RuntimeException("Not enabled, please enable this RPC in PeerMaker"); } return neighborRPC; } public void setNeighborRPC(NeighborRPC neighborRPC) { this.neighborRPC = neighborRPC; } public QuitRPC getQuitRPC() { if (quitRCP == null) { throw new RuntimeException("Not enabled, please enable this RPC in PeerMaker"); } return quitRCP; } public void setQuitRPC(QuitRPC quitRCP) { this.quitRCP = quitRCP; } public PeerExchangeRPC getPeerExchangeRPC() { if (peerExchangeRPC == null) { throw new RuntimeException("Not enabled, please enable this RPC in PeerMaker"); } return peerExchangeRPC; } public void setPeerExchangeRPC(PeerExchangeRPC peerExchangeRPC) { this.peerExchangeRPC = peerExchangeRPC; } public DirectDataRPC getDirectDataRPC() { if (directDataRPC == null) { throw new RuntimeException("Not enabled, please enable this RPC in PeerMaker"); } return directDataRPC; } public void setDirectDataRPC(DirectDataRPC directDataRPC) { this.directDataRPC = directDataRPC; } public TrackerRPC getTrackerRPC() { if (trackerRPC == null) { throw new RuntimeException("Not enabled, please enable this RPC in PeerMaker"); } return trackerRPC; } public void setTrackerRPC(TrackerRPC trackerRPC) { this.trackerRPC = trackerRPC; } /* * public TaskRPC getTaskRPC() { if (taskRPC == null) { throw new * RuntimeException("Not enabled, please enable this RPC in PeerMaker"); } return taskRPC; } * * public void setTaskRPC(TaskRPC taskRPC) { this.taskRPC = taskRPC; } */ public void setBroadcastRPC(BroadcastRPC broadcastRPC) { this.broadcastRPC = broadcastRPC; } public BroadcastRPC getBroadcastRPC() { if (broadcastRPC == null) { throw new RuntimeException("Not enabled, please enable this RPC in PeerMaker"); } return broadcastRPC; } public DistributedRouting getDistributedRouting() { if (distributedRouting == null) { throw new RuntimeException("Not enabled, please enable this P2P function in PeerMaker"); } return distributedRouting; } public void setDistributedRouting(DistributedRouting distributedRouting) { this.distributedRouting = distributedRouting; } public DistributedHashTable getDistributedHashMap() { if (distributedHashMap == null) { throw new RuntimeException("Not enabled, please enable this P2P function in PeerMaker"); } return distributedHashMap; } public void setDistributedHashMap(DistributedHashTable distributedHashMap) { this.distributedHashMap = distributedHashMap; } public DistributedTracker getDistributedTracker() { if (distributedTracker == null) { throw new RuntimeException("Not enabled, please enable this P2P function in PeerMaker"); } return distributedTracker; } public void setDistributedTracker(DistributedTracker distributedTracker) { this.distributedTracker = distributedTracker; } /* * public AsyncTask getAsyncTask() { if (asyncTask == null) { throw new * RuntimeException("Not enabled, please enable this RPC in PeerMaker"); } return asyncTask; } * * public void setAsyncTask(AsyncTask asyncTask) { this.asyncTask = asyncTask; } */ /*public DistributedTask getDistributedTask() { if (distributedTask == null) { throw new RuntimeException("Not enabled, please enable this P2P function in PeerMaker"); } return distributedTask; } public void setDistributedTask(DistributedTask task) { this.distributedTask = task; }*/ public PeerBean getPeerBean() { return peerCreator.peerBean(); } public ConnectionBean getConnectionBean() { return peerCreator.connectionBean(); } public Number160 getPeerID() { return peerId; } public int getP2PID() { return p2pID; } public PeerAddress getPeerAddress() { return getPeerBean().serverPeerAddress(); } Peer setAutomaticFutures(List<AutomaticFuture> automaticFutures) { this.automaticFutures = Collections.unmodifiableList(automaticFutures); return this; } //TODO: expose this public Peer notifyAutomaticFutures(BaseFuture future) { if(automaticFutures!=null) { for(AutomaticFuture automaticFuture:automaticFutures) { automaticFuture.futureCreated(future); } } return this; } // *********************************** DHT / Tracker operations start here public void setRawDataReply(final RawDataReply rawDataReply) { getDirectDataRPC().setReply(rawDataReply); } public void setObjectDataReply(final ObjectDataReply objectDataReply) { getDirectDataRPC().setReply(objectDataReply); } public FuturePeerConnection createPeerConnection(final PeerAddress destination) { return createPeerConnection(destination, PeerConnection.HEART_BEAT_MILLIS); } /** * Opens a TCP connection and keeps it open. The user can provide the idle timeout, which means that the connection * gets closed after that time of inactivity. If the other peer goes offline or closes the connection (due to * inactivity), further requests with this connections reopens the connection. This methods blocks until a * connection can be reserver. * * @param destination * The end-point to connect to * @param idleTCPMillis * time in milliseconds after a connection gets closed if idle, -1 if it should remain always open until * the user closes the connection manually. * @return A class that needs to be passed to those methods that should use the already open connection. If the * connection could not be reserved, maybe due to a shutdown, null is returned. */ public FuturePeerConnection createPeerConnection(final PeerAddress destination, final int heartBeatMillis) { final FuturePeerConnection futureDone = new FuturePeerConnection(destination); final FutureChannelCreator fcc = getConnectionBean().reservation().createPermanent(1); fcc.addListener(new BaseFutureAdapter<FutureChannelCreator>() { @Override public void operationComplete(final FutureChannelCreator future) throws Exception { if (future.isSuccess()) { final ChannelCreator cc = fcc.getChannelCreator(); final PeerConnection peerConnection = new PeerConnection(destination, cc, heartBeatMillis); futureDone.setDone(peerConnection); } else { futureDone.setFailed(future); } } }); return futureDone; } // New API - builder pattern // -------------------------------------------------- /* * public SubmitBuilder submit(Number160 locationKey, Worker worker) { return new SubmitBuilder(this, locationKey, * worker); } */ public AddBuilder add(Number160 locationKey) { return new AddBuilder(this, locationKey); } public PutBuilder put(Number160 locationKey) { return new PutBuilder(this, locationKey); } public GetBuilder get(Number160 locationKey) { return new GetBuilder(this, locationKey); } public DigestBuilder digest(Number160 locationKey) { return new DigestBuilder(this, locationKey); } public RemoveBuilder remove(Number160 locationKey) { return new RemoveBuilder(this, locationKey); } /** * The send method works as follows: * * <pre> * 1. routing: find close peers to the content hash. * You can control the routing behavior with * setRoutingConfiguration() * 2. sending: send the data to the n closest peers. * N is set via setRequestP2PConfiguration(). * If you want to send it to the closest one, use * setRequestP2PConfiguration(1, 5, 0) * </pre> * * @param locationKey * The target hash to search for during the routing process * @return The send builder that allows to set options */ public SendBuilder send(Number160 locationKey) { return new SendBuilder(this, locationKey); } public SendDirectBuilder sendDirect(PeerAddress recipientAddress) { return new SendDirectBuilder(this, recipientAddress); } public SendDirectBuilder sendDirect(FuturePeerConnection recipientConnection) { return new SendDirectBuilder(this, recipientConnection); } public SendDirectBuilder sendDirect(PeerConnection peerConnection) { return new SendDirectBuilder(this, peerConnection); } public BootstrapBuilder bootstrap() { return new BootstrapBuilder(this); } public PingBuilder ping() { return new PingBuilder(this); } public DiscoverBuilder discover() { return new DiscoverBuilder(this); } public AddTrackerBuilder addTracker(Number160 locationKey) { return new AddTrackerBuilder(this, locationKey); } public GetTrackerBuilder getTracker(Number160 locationKey) { return new GetTrackerBuilder(this, locationKey); } public ParallelRequestBuilder<?> parallelRequest(Number160 locationKey) { return new ParallelRequestBuilder<>(this, locationKey); } public BroadcastBuilder broadcast(Number160 messageKey) { return new BroadcastBuilder(this, messageKey); } /** * Sends a friendly shutdown message to my close neighbors in the DHT. * * @return A builder for shutdown that runs asynchronous. */ public ShutdownBuilder announceShutdown() { return new ShutdownBuilder(this); } /** * Shuts down everything. TODO: test in ExampleDirectReplication, when the direct replication was not yet shut down. * * @return The future, when shutdown is completed */ public BaseFuture shutdown() { //prevent the shutdown from being called twice if (!shutdown) { shutdown = true; final List<Shutdown> copy; synchronized (shutdownListeners) { copy = new ArrayList<Shutdown>(shutdownListeners); } final FutureLateJoin<BaseFuture> futureLateJoin = new FutureLateJoin<BaseFuture>(shutdownListeners.size() + 1); for(Shutdown shutdown:copy) { futureLateJoin.add(shutdown.shutdown()); removeShutdownListener(shutdown); } futureLateJoin.add(peerCreator.shutdown()); return futureLateJoin; } else { return new FutureDone<Void>().setFailed("already shutting / shut down"); } } /** * @return True if the peer is about or already has shutdown */ public boolean isShutdown() { return shutdown; } public void addShutdownListener(Shutdown shutdown) { shutdownListeners.add(shutdown); } public void removeShutdownListener(Shutdown shutdown) { shutdownListeners.remove(shutdown); } } <file_sep>/* * Copyright 2013 <NAME> * * 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 net.tomp2p.p2p.builder; import java.util.NavigableSet; import net.tomp2p.futures.FutureShutdown; import net.tomp2p.p2p.Peer; import net.tomp2p.p2p.RequestP2PConfiguration; import net.tomp2p.p2p.RoutingConfiguration; import net.tomp2p.peers.Number160; import net.tomp2p.peers.PeerAddress; /** * Set the configuration options for the shutdown command. The shutdown does first a rounting, searches for its close * peers and then send a quit message so that the other peers knows that this peer is offline. * * @author <NAME> * */ public class ShutdownBuilder extends DHTBuilder<ShutdownBuilder> { private static final FutureShutdown FUTURE_SHUTDOWN = new FutureShutdown(null) .setFailed("shutdown builder - peer is shutting down"); private Filter filter; /** * Constructor. * * @param peer * The peer that runs the routing and quit messages */ public ShutdownBuilder(final Peer peer) { super(peer, peer.getPeerID()); self(this); } public ShutdownBuilder filter(final Filter filter) { this.filter = filter; return this; } public Filter filter() { return filter; } /** * Start the shutdown. This method returns immediately with a future object. The future object can be used to block * or add a listener. * * @return The future object */ public FutureShutdown start() { if (peer.isShutdown()) { return FUTURE_SHUTDOWN; } setForceUDP(); if (routingConfiguration == null) { routingConfiguration = new RoutingConfiguration(0, 0, 0); } if (requestP2PConfiguration == null) { requestP2PConfiguration = new RequestP2PConfiguration(10, 0, 10); } preBuild("shutdown-builder"); if (filter == null) { filter = new Filter() { @Override public NavigableSet<PeerAddress> filter(NavigableSet<PeerAddress> closePeers) { return closePeers; } }; } return peer.getDistributedHashMap().quit(this); } @Override public ShutdownBuilder setDomainKey(final Number160 domainKey) { throw new IllegalArgumentException("Cannot be set here"); } /** * Adds the possibility to filter the peers, to add more or remove peers for the shutdown process. * * @param closePeers * The close peers that were found in the peer map. * @return The set modified by the user, may be the same set or a new one */ public NavigableSet<PeerAddress> filter(NavigableSet<PeerAddress> closePeers) { return filter.filter(closePeers); } /** * The filter can be used to add or remove peers to notify for a shutdown. * * @author <NAME> * */ public static interface Filter { /** * Adds the possibility to filter the peers, to add more or remove peers for the shutdown process * * @param closePeers * The close peers that were found in the peer map. * @return The set modified by the user, may be the same set or a new one */ public NavigableSet<PeerAddress> filter(NavigableSet<PeerAddress> closePeers); } } <file_sep>/* * Copyright 2012 <NAME> * * 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 net.tomp2p.p2p.builder; import java.security.KeyPair; import java.util.ArrayList; import java.util.Collection; import net.tomp2p.connection.ConnectionConfiguration; import net.tomp2p.connection.DefaultConnectionConfiguration; import net.tomp2p.futures.FutureChannelCreator; import net.tomp2p.p2p.Peer; import net.tomp2p.p2p.RequestP2PConfiguration; import net.tomp2p.p2p.RoutingConfiguration; import net.tomp2p.peers.Number160; import net.tomp2p.peers.PeerFilter; /** * Every DHT builder has those methods in common. * * @author <NAME> * * @param <K> */ public abstract class DHTBuilder<K extends DHTBuilder<K>> extends DefaultConnectionConfiguration implements BasicBuilder<K>, ConnectionConfiguration, SignatureBuilder<K> { // changed this to zero as for the content key its also zero protected final Peer peer; protected final Number160 locationKey; protected Number160 domainKey; protected Number160 versionKey; protected RoutingConfiguration routingConfiguration; protected RequestP2PConfiguration requestP2PConfiguration; protected FutureChannelCreator futureChannelCreator; // private int idleTCPSeconds = ConnectionBean.DEFAULT_TCP_IDLE_SECONDS; // private int idleUDPSeconds = ConnectionBean.DEFAULT_UDP_IDLE_SECONDS; // private int connectionTimeoutTCPMillis = ConnectionBean.DEFAULT_CONNECTION_TIMEOUT_TCP; private boolean protectDomain = false; // private boolean signMessage = false; private KeyPair keyPair = null; private boolean streaming = false; // private boolean forceUDP = false; // private boolean forceTCP = false; private Collection<PeerFilter> peerFilters; private K self; public DHTBuilder(Peer peer, Number160 locationKey) { this.peer = peer; this.locationKey = locationKey; } public void self(K self) { this.self = self; } /** * @return The location key */ public Number160 getLocationKey() { return locationKey; } public Number160 getDomainKey() { return domainKey; } public K setDomainKey(Number160 domainKey) { this.domainKey = domainKey; return self; } public Number160 getVersionKey() { return versionKey; } public K setVersionKey(Number160 versionKey) { this.versionKey = versionKey; return self; } /** * @return The configuration for the routing options */ public RoutingConfiguration getRoutingConfiguration() { return routingConfiguration; } /** * @param routingConfiguration * The configuration for the routing options * @return This object */ public K setRoutingConfiguration(final RoutingConfiguration routingConfiguration) { this.routingConfiguration = routingConfiguration; return self; } /** * @return The P2P request configuration options */ public RequestP2PConfiguration getRequestP2PConfiguration() { return requestP2PConfiguration; } /** * @param requestP2PConfiguration * The P2P request configuration options * @return This object */ public K setRequestP2PConfiguration(final RequestP2PConfiguration requestP2PConfiguration) { this.requestP2PConfiguration = requestP2PConfiguration; return self; } /** * @return The future of the created channel */ public FutureChannelCreator getFutureChannelCreator() { return futureChannelCreator; } /** * @param futureChannelCreator * The future of the created channel * @return This object */ public K setFutureChannelCreator(FutureChannelCreator futureChannelCreator) { this.futureChannelCreator = futureChannelCreator; return self; } /** * @return Set to true if the domain should be set to protected. This means that this domain is flagged an a public * key is stored for this entry. An update or removal can only be made with the matching private key. */ public boolean isProtectDomain() { return protectDomain; } /** * @param protectDomain * Set to true if the domain should be set to protected. This means that this domain is flagged an a * public key is stored for this entry. An update or removal can only be made with the matching private * key. * @return This class */ public K setProtectDomain(final boolean protectDomain) { this.protectDomain = protectDomain; return self; } /** * @return Set to true if the domain should be set to protected. This means that this domain is flagged an a public * key is stored for this entry. An update or removal can only be made with the matching private key. */ public K setProtectDomain() { this.protectDomain = true; if(this.keyPair == null) { setSign(); } return self; } /* (non-Javadoc) * @see net.tomp2p.p2p.builder.SignatureBuilder#isSignMessage() */ @Override public boolean isSign() { return keyPair != null; } /* (non-Javadoc) * @see net.tomp2p.p2p.builder.SignatureBuilder#setSignMessage(boolean) */ @Override public K sign(final boolean signMessage) { if (signMessage) { setSign(); } else { this.keyPair = null; } return self; } /* (non-Javadoc) * @see net.tomp2p.p2p.builder.SignatureBuilder#setSignMessage() */ @Override public K setSign() { this.keyPair = peer.getPeerBean().keyPair(); return self; } /* (non-Javadoc) * @see net.tomp2p.p2p.builder.SignatureBuilder#keyPair(java.security.KeyPair) */ @Override public K keyPair(KeyPair keyPair) { this.keyPair = keyPair; return self; } /* (non-Javadoc) * @see net.tomp2p.p2p.builder.SignatureBuilder#keyPair() */ @Override public KeyPair keyPair() { return keyPair; } /** * @return True if streaming should be used */ public boolean isStreaming() { return streaming; } /** * Set streaming. If streaming is set to true, than the data can be added after {@link #start()} has been called. * * @param streaming * True if streaming should be used * @return This class */ public K setStreaming(final boolean streaming) { this.streaming = streaming; return self; } /** * Set streaming to true. See {@link #setStreaming(boolean)} * * @return This class */ public K setStreaming() { this.streaming = true; return self; } public K addPeerFilter(PeerFilter peerFilter) { if(peerFilters == null) { //most likely we have 1-2 filters peerFilters = new ArrayList<PeerFilter>(2); } peerFilters.add(peerFilter); return self; } public Collection<PeerFilter> peerFilters() { return peerFilters; } protected void preBuild(String name) { if (domainKey == null) { domainKey = Number160.ZERO; } if (versionKey == null) { versionKey = Number160.ZERO; } if (routingConfiguration == null) { routingConfiguration = new RoutingConfiguration(5, 10, 2); } if (requestP2PConfiguration == null) { requestP2PConfiguration = new RequestP2PConfiguration(3, 5, 3); } int size = peer.getPeerBean().peerMap().size() + 1; requestP2PConfiguration = requestP2PConfiguration.adjustMinimumResult(size); if (futureChannelCreator == null || (futureChannelCreator.getChannelCreator()!=null && futureChannelCreator.getChannelCreator().isShutdown())) { futureChannelCreator = peer.getConnectionBean().reservation() .create(routingConfiguration, requestP2PConfiguration, this); } } public RoutingBuilder createBuilder(RequestP2PConfiguration requestP2PConfiguration, RoutingConfiguration routingConfiguration) { RoutingBuilder routingBuilder = new RoutingBuilder(); routingBuilder.setParallel(routingConfiguration.getParallel()); routingBuilder.setMaxNoNewInfo(routingConfiguration.getMaxNoNewInfo(requestP2PConfiguration .getMinimumResults())); routingBuilder.setMaxDirectHits(routingConfiguration.getMaxDirectHits()); routingBuilder.setMaxFailures(routingConfiguration.getMaxFailures()); routingBuilder.setMaxSuccess(routingConfiguration.getMaxSuccess()); return routingBuilder; } // public abstract FutureDHT start(); } <file_sep>package net.tomp2p.rpc; public class RPC { //Max. 255 Commands public enum Commands{ PING(0), PUT(1), GET(2), ADD(3), REMOVE(4), NEIGHBOR(5), QUIT(6), DIRECT_DATA(7), TRACKER_ADD(8), TRACKER_GET(9), PEX(10), DIGEST(11), BROADCAST(12), PUT_META(13), DIGEST_BLOOMFILTER(14), RELAY(15), DIGEST_META_VALUES(16), SYNC(17), SYNC_INFO(18); private final byte nr; Commands(int nr) { this.nr = (byte)nr; } public byte getNr() { return nr; } } } <file_sep>/* * Copyright 2011 <NAME> * * 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 net.tomp2p.p2p; import io.netty.buffer.ByteBuf; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.NavigableMap; import java.util.NavigableSet; import java.util.SortedMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReferenceArray; import net.tomp2p.connection.ChannelCreator; import net.tomp2p.futures.BaseFuture; import net.tomp2p.futures.BaseFutureAdapter; import net.tomp2p.futures.FutureChannelCreator; import net.tomp2p.futures.FutureDHT; import net.tomp2p.futures.FutureDigest; import net.tomp2p.futures.FutureForkJoin; import net.tomp2p.futures.FutureGet; import net.tomp2p.futures.FuturePut; import net.tomp2p.futures.FutureRemove; import net.tomp2p.futures.FutureResponse; import net.tomp2p.futures.FutureRouting; import net.tomp2p.futures.FutureSend; import net.tomp2p.futures.FutureShutdown; import net.tomp2p.message.Message.Type; import net.tomp2p.p2p.builder.AddBuilder; import net.tomp2p.p2p.builder.BasicBuilder; import net.tomp2p.p2p.builder.DigestBuilder; import net.tomp2p.p2p.builder.GetBuilder; import net.tomp2p.p2p.builder.PutBuilder; import net.tomp2p.p2p.builder.RemoveBuilder; import net.tomp2p.p2p.builder.RoutingBuilder; import net.tomp2p.p2p.builder.SearchableBuilder; import net.tomp2p.p2p.builder.SendBuilder; import net.tomp2p.p2p.builder.ShutdownBuilder; import net.tomp2p.peers.Number160; import net.tomp2p.peers.Number640; import net.tomp2p.peers.PeerAddress; import net.tomp2p.rpc.DefaultBloomfilterFactory; import net.tomp2p.rpc.DigestInfo; import net.tomp2p.rpc.DigestResult; import net.tomp2p.rpc.DirectDataRPC; import net.tomp2p.rpc.QuitRPC; import net.tomp2p.rpc.SimpleBloomFilter; import net.tomp2p.rpc.StorageRPC; import net.tomp2p.storage.Data; import net.tomp2p.utils.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DistributedHashTable { private static final Logger logger = LoggerFactory.getLogger(DistributedHashTable.class); private final DistributedRouting routing; private final StorageRPC storeRCP; private final DirectDataRPC directDataRPC; private final QuitRPC quitRPC; public DistributedHashTable(DistributedRouting routing, StorageRPC storeRCP, DirectDataRPC directDataRPC, QuitRPC quitRPC) { this.routing = routing; this.storeRCP = storeRCP; this.directDataRPC = directDataRPC; this.quitRPC = quitRPC; } public FuturePut add(final AddBuilder builder) { final FuturePut futureDHT = new FuturePut(builder, builder.getRequestP2PConfiguration() .getMinimumResults(), builder.getDataSet().size()); builder.getFutureChannelCreator().addListener(new BaseFutureAdapter<FutureChannelCreator>() { @Override public void operationComplete(final FutureChannelCreator future) throws Exception { if (future.isSuccess()) { final RoutingBuilder routingBuilder = createBuilder(builder); final FutureRouting futureRouting = routing.route(routingBuilder, Type.REQUEST_1, future.getChannelCreator()); futureDHT.setFutureRouting(futureRouting); futureRouting.addListener(new BaseFutureAdapter<FutureRouting>() { @Override public void operationComplete(final FutureRouting futureRouting) throws Exception { if (futureRouting.isSuccess()) { logger.debug("adding lkey={} on {}", builder.getLocationKey(), futureRouting.getPotentialHits()); parallelRequests(builder.getRequestP2PConfiguration(), futureRouting.getPotentialHits(), futureDHT, false, future.getChannelCreator(), new OperationMapper<FuturePut>() { Map<PeerAddress, Map<Number640, Byte>> rawData = new HashMap<PeerAddress, Map<Number640, Byte>>(); @Override public FutureResponse create(ChannelCreator channelCreator, PeerAddress address) { return storeRCP.add(address, builder, channelCreator); } @Override public void response(FuturePut futureDHT) { futureDHT.setStoredKeys(rawData); } @Override public void interMediateResponse(FutureResponse future) { // the future tells us that the communication was successful, but we // need to check the result if we could store it. if (future.isSuccess() && future.getResponse().isOk()) { rawData.put(future.getRequest().getRecipient(), future .getResponse().getKeyMapByte(0).keysMap()); } } }); } else { futureDHT.setFailed("routing failed"); } } }); futureDHT.addFutureDHTReleaseListener(future.getChannelCreator()); } else { futureDHT.setFailed(future); } } }); return futureDHT; } /* * public FutureDHT direct(final Number160 locationKey, final ByteBuf buffer, final boolean raw, final * RoutingConfiguration routingConfiguration, final RequestP2PConfiguration p2pConfiguration, final * FutureCreate<FutureDHT> futureCreate, final boolean cancelOnFinish, final boolean manualCleanup, final * FutureChannelCreator futureChannelCreator, final ConnectionReservation connectionReservation) { */ public FutureSend direct(final SendBuilder builder) { final FutureSend futureDHT = new FutureSend(builder, builder.getRequestP2PConfiguration() .getMinimumResults(), new VotingSchemeDHT()); builder.getFutureChannelCreator().addListener(new BaseFutureAdapter<FutureChannelCreator>() { @Override public void operationComplete(final FutureChannelCreator future) throws Exception { if (future.isSuccess()) { final RoutingBuilder routingBuilder = createBuilder(builder); final FutureRouting futureRouting = routing.route(routingBuilder, Type.REQUEST_1, future.getChannelCreator()); futureDHT.setFutureRouting(futureRouting); futureRouting.addListener(new BaseFutureAdapter<FutureRouting>() { @Override public void operationComplete(FutureRouting futureRouting) throws Exception { if (futureRouting.isSuccess()) { logger.debug("storing lkey={} on {}", builder.getLocationKey(), futureRouting.getPotentialHits()); parallelRequests(builder.getRequestP2PConfiguration(), futureRouting.getPotentialHits(), futureDHT, builder.isCancelOnFinish(), future.getChannelCreator(), new OperationMapper<FutureSend>() { Map<PeerAddress, ByteBuf> rawChannels = new HashMap<PeerAddress, ByteBuf>(); Map<PeerAddress, Object> rawObjects = new HashMap<PeerAddress, Object>(); @Override public FutureResponse create(ChannelCreator channelCreator, PeerAddress address) { return directDataRPC.send(address, builder, channelCreator); } @Override public void response(FutureSend futureDHT) { if (builder.isRaw()) futureDHT.setDirectData1(rawChannels); else futureDHT.setDirectData2(rawObjects); } @Override public void interMediateResponse(FutureResponse future) { // the future tells us that the communication was successful, but we // need to check the result if we could store it. if (future.isSuccess() && future.getResponse().isOk()) { if (builder.isRaw()) { rawChannels.put(future.getRequest().getRecipient(), future.getResponse().getBuffer(0).buffer()); } else { try { rawObjects.put( future.getRequest().getRecipient(), future.getResponse().getBuffer(0) .object()); } catch (ClassNotFoundException e) { rawObjects.put( future.getRequest().getRecipient(), e); } catch (IOException e) { rawObjects.put( future.getRequest().getRecipient(), e); } } } } }); } else { futureDHT.setFailed("routing failed"); } } }); futureDHT.addFutureDHTReleaseListener(future.getChannelCreator()); } else { futureDHT.setFailed(future); } } }); return futureDHT; } public FuturePut put(final PutBuilder putBuilder) { final int dataSize = Utils.dataSize(putBuilder); final FuturePut futureDHT = new FuturePut(putBuilder, putBuilder.getRequestP2PConfiguration() .getMinimumResults(), dataSize); putBuilder.getFutureChannelCreator().addListener(new BaseFutureAdapter<FutureChannelCreator>() { @Override public void operationComplete(final FutureChannelCreator future) throws Exception { if (future.isSuccess()) { final RoutingBuilder routingBuilder = createBuilder(putBuilder); final FutureRouting futureRouting = routing.route(routingBuilder, Type.REQUEST_1, future.getChannelCreator()); futureDHT.setFutureRouting(futureRouting); futureRouting.addListener(new BaseFutureAdapter<FutureRouting>() { @Override public void operationComplete(final FutureRouting futureRouting) throws Exception { if (futureRouting.isSuccess()) { logger.debug("storing lkey={} on {}", putBuilder.getLocationKey(), futureRouting.getPotentialHits()); parallelRequests(putBuilder.getRequestP2PConfiguration(), futureRouting.getPotentialHits(), futureDHT, false, future.getChannelCreator(), new OperationMapper<FuturePut>() { Map<PeerAddress, Map<Number640, Byte>> rawData = new HashMap<PeerAddress, Map<Number640, Byte>>(); @Override public FutureResponse create(final ChannelCreator channelCreator, final PeerAddress address) { if (putBuilder.isPutIfAbsent()) { return storeRCP.putIfAbsent(address, putBuilder, channelCreator); } else if (putBuilder.isPutMeta()) { return storeRCP.putMeta(address, putBuilder, channelCreator); } else { return storeRCP.put(address, putBuilder, channelCreator); } } @Override public void response(final FuturePut futureDHT) { futureDHT.setStoredKeys(rawData); } @Override public void interMediateResponse(final FutureResponse future) { // the future tells us that the communication was successful, to check // the result if we could store it. if (future.isSuccess() && future.getResponse().isOk()) { rawData.put(future.getRequest().getRecipient(), future .getResponse().getKeyMapByte(0).keysMap()); } else { rawData.put(future.getRequest().getRecipient(), null); } } }); } else { futureDHT.setFailed("routing failed"); } } }); futureDHT.addFutureDHTReleaseListener(future.getChannelCreator()); } else { futureDHT.setFailed(future); } } }); return futureDHT; } public FutureGet get(final GetBuilder builder) { final FutureGet futureDHT = new FutureGet(builder, builder.getRequestP2PConfiguration() .getMinimumResults(), new VotingSchemeDHT()); builder.getFutureChannelCreator().addListener(new BaseFutureAdapter<FutureChannelCreator>() { @Override public void operationComplete(final FutureChannelCreator future) throws Exception { if (future.isSuccess()) { final RoutingBuilder routingBuilder = createBuilder(builder); fillRoutingBuilder(builder, routingBuilder); final FutureRouting futureRouting = routing.route(routingBuilder, Type.REQUEST_2, future.getChannelCreator()); futureDHT.setFutureRouting(futureRouting); futureRouting.addListener(new BaseFutureAdapter<FutureRouting>() { @Override public void operationComplete(FutureRouting futureRouting) throws Exception { if (futureRouting.isSuccess()) { logger.debug("found direct hits for get: {}", futureRouting.getDirectHits()); // this adjust is based on results from the routing process, if we find the same data on // 2 // peers, we want to get it from one only. Unless its digest, then we want to know // exactly what is going on RequestP2PConfiguration p2pConfiguration2 = builder.isRange() ? builder .getRequestP2PConfiguration() : adjustConfiguration( builder.getRequestP2PConfiguration(), futureRouting.getDirectHitsDigest()); // store in direct hits parallelRequests( p2pConfiguration2, builder.isRange() ? futureRouting.getPotentialHits() : futureRouting .getDirectHits(), futureDHT, true, future.getChannelCreator(), new OperationMapper<FutureGet>() { Map<PeerAddress, Map<Number640, Data>> rawData = new HashMap<PeerAddress, Map<Number640, Data>>(); @Override public FutureResponse create(ChannelCreator channelCreator, PeerAddress address) { return storeRCP.get(address, builder, channelCreator); } @Override public void response(FutureGet futureDHT) { futureDHT.setReceivedData(rawData); } @Override public void interMediateResponse(FutureResponse future) { // the future tells us that the communication was successful, which is // ok for digest if (future.isSuccess()) { rawData.put(future.getRequest().getRecipient(), future .getResponse().getDataMap(0).dataMap()); logger.debug("set data from {}", future.getRequest() .getRecipient()); } } }); } else { futureDHT.setFailed("routing failed"); } } }); futureDHT.addFutureDHTReleaseListener(future.getChannelCreator()); } else { futureDHT.setFailed(future); } } }); return futureDHT; } public FutureDigest digest(final DigestBuilder builder) { final FutureDigest futureDHT = new FutureDigest(builder, builder.getRequestP2PConfiguration() .getMinimumResults(), new VotingSchemeDHT()); builder.getFutureChannelCreator().addListener(new BaseFutureAdapter<FutureChannelCreator>() { @Override public void operationComplete(final FutureChannelCreator future) throws Exception { if (future.isSuccess()) { final RoutingBuilder routingBuilder = createBuilder(builder); fillRoutingBuilder(builder, routingBuilder); final FutureRouting futureRouting = routing.route(routingBuilder, Type.REQUEST_2, future.getChannelCreator()); futureDHT.setFutureRouting(futureRouting); futureRouting.addListener(new BaseFutureAdapter<FutureRouting>() { @Override public void operationComplete(FutureRouting futureRouting) throws Exception { if (futureRouting.isSuccess()) { logger.debug("found direct hits for digest: {}", futureRouting.getDirectHits()); // store in direct hits parallelRequests( builder.getRequestP2PConfiguration(), builder.isRange() ? futureRouting.getPotentialHits() : futureRouting .getDirectHits(), futureDHT, true, future.getChannelCreator(), new OperationMapper<FutureDigest>() { Map<PeerAddress, DigestResult> rawDigest = new HashMap<PeerAddress, DigestResult>(); @Override public FutureResponse create(ChannelCreator channelCreator, PeerAddress address) { return storeRCP.digest(address, builder, channelCreator); } @Override public void response(FutureDigest futureDHT) { futureDHT.setReceivedDigest(rawDigest); } @Override public void interMediateResponse(FutureResponse future) { // the future tells us that the communication was successful, which is // ok for digest if (future.isSuccess()) { final DigestResult digest; if (builder.isReturnMetaValues()) { Map<Number640, Data> dataMap = future.getResponse() .getDataMap(0).dataMap(); digest = new DigestResult(dataMap); } else if (builder.isReturnBloomFilter()) { SimpleBloomFilter<Number160> sbf1 = future.getResponse() .getBloomFilter(0); SimpleBloomFilter<Number160> sbf2 = future.getResponse() .getBloomFilter(1); digest = new DigestResult(sbf1, sbf2); } else { NavigableMap<Number640, Number160> keyDigest = future .getResponse().getKeyMap640(0).keysMap(); digest = new DigestResult(keyDigest); } rawDigest.put(future.getRequest().getRecipient(), digest); logger.debug("set data from {}", future.getRequest().getRecipient()); } } }); } else { futureDHT.setFailed("routing failed"); } } }); futureDHT.addFutureDHTReleaseListener(future.getChannelCreator()); } else { futureDHT.setFailed(future); } } }); return futureDHT; } /* * public FutureDHT remove(final Number160 locationKey, final Number160 domainKey, final Collection<Number160> * contentKeys, final RoutingConfiguration routingConfiguration, final RequestP2PConfiguration p2pConfiguration, * final boolean returnResults, final boolean signMessage, final boolean isManualCleanup, FutureCreate<FutureDHT> * futureCreate, final FutureChannelCreator futureChannelCreator, final ConnectionReservation connectionReservation) * { */ public FutureRemove remove(final RemoveBuilder builder) { final int dataSize = Utils.dataSize(builder); final FutureRemove futureDHT = new FutureRemove(builder, builder.getRequestP2PConfiguration() .getMinimumResults(), new VotingSchemeDHT(), dataSize); builder.getFutureChannelCreator().addListener(new BaseFutureAdapter<FutureChannelCreator>() { @Override public void operationComplete(final FutureChannelCreator future) throws Exception { if (future.isSuccess()) { final RoutingBuilder routingBuilder = createBuilder(builder); fillRoutingBuilder(builder, routingBuilder); final FutureRouting futureRouting = routing.route(routingBuilder, Type.REQUEST_2, future.getChannelCreator()); futureDHT.setFutureRouting(futureRouting); futureRouting.addListener(new BaseFutureAdapter<FutureRouting>() { @Override public void operationComplete(FutureRouting futureRouting) throws Exception { if (futureRouting.isSuccess()) { logger.debug("found direct hits for remove: {}", futureRouting.getDirectHits()); RequestP2PConfiguration p2pConfiguration2 = adjustConfiguration( builder.getRequestP2PConfiguration(), futureRouting.getDirectHitsDigest()); parallelRequests(p2pConfiguration2, futureRouting.getDirectHits(), futureDHT, false, future.getChannelCreator(), new OperationMapper<FutureRemove>() { Map<PeerAddress, Map<Number640, Data>> rawDataResult = new HashMap<PeerAddress, Map<Number640, Data>>(); Map<PeerAddress, Map<Number640, Byte>> rawDataNoResult = new HashMap<PeerAddress, Map<Number640, Byte>>(); @Override public FutureResponse create(ChannelCreator channelCreator, PeerAddress address) { return storeRCP.remove(address, builder, channelCreator); } @Override public void response(FutureRemove futureDHT) { if (builder.isReturnResults()) { futureDHT.setReceivedData(rawDataResult); } else { futureDHT.setStoredKeys(rawDataNoResult); } } @Override public void interMediateResponse(FutureResponse future) { // the future tells us that the communication was successful, but we // need to check the result if we could store it. if (future.isSuccess() && future.getResponse().isOk()) { if (builder.isReturnResults()) { rawDataResult.put(future.getRequest().getRecipient(), future.getResponse().getDataMap(0).dataMap()); } else { rawDataNoResult.put(future.getRequest() .getRecipient(), future.getResponse() .getKeyMapByte(0).keysMap()); } } } }); } else futureDHT.setFailed("routing failed"); } }); futureDHT.addFutureDHTReleaseListener(future.getChannelCreator()); } else { futureDHT.setFailed(future); } } }); return futureDHT; } /** * Send a friendly shutdown message to your close neighbors. * * @param connectionReservation * The connection reservation The routing configuration * @param builder * All other options * @return future shutdown */ public FutureShutdown quit(final ShutdownBuilder builder) { final FutureShutdown futureShutdown = new FutureShutdown(builder); builder.getFutureChannelCreator().addListener(new BaseFutureAdapter<FutureChannelCreator>() { @Override public void operationComplete(final FutureChannelCreator future) throws Exception { if (future.isSuccess()) { // content key and domain key are not important when sending a friendly shutdown // no need for routing, we can take the close peers from our map, in addition offer a way to add // peers to notify by the end user. NavigableSet<PeerAddress> closePeers = routing.peerMap().closePeers(20); closePeers = builder.filter(closePeers); parallelRequests(builder.getRequestP2PConfiguration(), closePeers, futureShutdown, false, future.getChannelCreator(), new OperationMapper<FutureShutdown>() { @Override public FutureResponse create(final ChannelCreator channelCreator, final PeerAddress address) { return quitRPC.quit(address, builder, channelCreator); } @Override public void response(final FutureShutdown future) { future.setDone(); } // its fire and forget, so don't bother checking the future success @Override public void interMediateResponse(final FutureResponse future) { // contactedPeers can be accessed by several threads futureShutdown.report(future.getRequest().getRecipient(), future.isSuccess()); } }); futureShutdown.addFutureDHTReleaseListener(future.getChannelCreator()); } else { futureShutdown.setFailed(future); } } }); return futureShutdown; } /** * Creates RPCs and executes them parallel. * * @param p2pConfiguration * The configuration that specifies e.g. how many parallel requests there are. * @param queue * The sorted set that will be queries. The first RPC takes the first in the queue. * @param futureDHT * The future object that tracks the progress * @param cancleOnFinish * Set to true if the operation should be canceled (e.g. file transfer) if the future has finished. * @param operation * The operation that creates the request */ public static <K extends FutureDHT<?>> K parallelRequests(final RequestP2PConfiguration p2pConfiguration, final NavigableSet<PeerAddress> queue, final boolean cancleOnFinish, final FutureChannelCreator futureChannelCreator, final OperationMapper<K> operation, final K futureDHT) { futureChannelCreator.addListener(new BaseFutureAdapter<FutureChannelCreator>() { @Override public void operationComplete(final FutureChannelCreator future) throws Exception { if (future.isSuccess()) { parallelRequests(p2pConfiguration, queue, futureDHT, cancleOnFinish, future.getChannelCreator(), operation); Utils.addReleaseListener(future.getChannelCreator(), futureDHT); } else { futureDHT.setFailed(future); } } }); return futureDHT; } private static <K extends FutureDHT<?>> void parallelRequests(RequestP2PConfiguration p2pConfiguration, NavigableSet<PeerAddress> queue, K future, boolean cancleOnFinish, ChannelCreator channelCreator, OperationMapper<K> operation) { if (p2pConfiguration.getMinimumResults() == 0) { operation.response(future); return; } FutureResponse[] futures = new FutureResponse[p2pConfiguration.getParallel()]; // here we split min and pardiff, par=min+pardiff loopRec(queue, p2pConfiguration.getMinimumResults(), new AtomicInteger(0), p2pConfiguration.getMaxFailure(), p2pConfiguration.getParallelDiff(), new AtomicReferenceArray<FutureResponse>(futures), future, cancleOnFinish, channelCreator, operation); } private static <K extends FutureDHT<?>> void loopRec(final NavigableSet<PeerAddress> queue, final int min, final AtomicInteger nrFailure, final int maxFailure, final int parallelDiff, final AtomicReferenceArray<FutureResponse> futures, final K futureDHT, final boolean cancelOnFinish, final ChannelCreator channelCreator, final OperationMapper<K> operation) { // final int parallel=min+parallelDiff; int active = 0; for (int i = 0; i < min + parallelDiff; i++) { if (futures.get(i) == null) { PeerAddress next = queue.pollFirst(); if (next != null) { active++; FutureResponse futureResponse = operation.create(channelCreator, next); futures.set(i, futureResponse); futureDHT.addRequests(futureResponse); } } else { active++; } } if (active == 0) { operation.response(futureDHT); if (cancelOnFinish) { cancel(futures); } return; } if (logger.isDebugEnabled()) { logger.debug("fork/join status: " + min + "/" + active + " (" + parallelDiff + ")"); } FutureForkJoin<FutureResponse> fp = new FutureForkJoin<FutureResponse>(Math.min(min, active), false, futures); fp.addListener(new BaseFutureAdapter<FutureForkJoin<FutureResponse>>() { @Override public void operationComplete(final FutureForkJoin<FutureResponse> future) throws Exception { for (FutureResponse futureResponse : future.getCompleted()) { operation.interMediateResponse(futureResponse); } // we are finished if forkjoin says so or we got too many // failures if (future.isSuccess() || nrFailure.incrementAndGet() > maxFailure) { if (cancelOnFinish) { cancel(futures); } operation.response(futureDHT); } else { loopRec(queue, min - future.getSuccessCounter(), nrFailure, maxFailure, parallelDiff, futures, futureDHT, cancelOnFinish, channelCreator, operation); } } }); } private static RoutingBuilder createBuilder(BasicBuilder<?> builder) { RoutingBuilder routingBuilder = builder.createBuilder(builder.getRequestP2PConfiguration(), builder.getRoutingConfiguration()); routingBuilder.setLocationKey(builder.getLocationKey()); routingBuilder.setDomainKey(builder.getDomainKey()); routingBuilder.peerFilters(builder.peerFilters()); return routingBuilder; } private static void fillRoutingBuilder(final SearchableBuilder builder, final RoutingBuilder routingBuilder) { if (builder.from()!=null && builder.to() !=null) { routingBuilder.setRange(builder.from(), builder.to()); } else if (builder.contentKeys() != null && builder.contentKeys().size() == 1) { //builder.contentKeys() can be null if we search for all routingBuilder.setContentKey(builder.contentKeys().iterator().next()); } else if(builder.contentKeys() != null && builder.contentKeys().size() > 1) { //builder.contentKeys() can be null if we search for all DefaultBloomfilterFactory factory = new DefaultBloomfilterFactory(); SimpleBloomFilter<Number160> bf = factory.createContentKeyBloomFilter(); for (Number160 contentKey : builder.contentKeys()) { bf.add(contentKey); } routingBuilder.setKeyBloomFilter(bf); } } /** * Cancel the future that causes the underlying futures to cancel as well. */ private static void cancel(final AtomicReferenceArray<FutureResponse> futures) { int len = futures.length(); for (int i = 0; i < len; i++) { BaseFuture baseFuture = futures.get(i); if (baseFuture != null) { baseFuture.cancel(); } } } /** * Adjusts the number of minimum requests in the P2P configuration. When we query x peers for the get() operation * and they have y different data stored (y <= x), then set the minimum to y or to the value the user set if its * smaller. If no data is found, then return 0, so we don't start P2P RPCs. * * @param p2pConfiguration * The old P2P configuration with the user specified minimum result * @param directHitsDigest * The digest information from the routing process * @return The new RequestP2PConfiguration with the new minimum result */ public static RequestP2PConfiguration adjustConfiguration(final RequestP2PConfiguration p2pConfiguration, final SortedMap<PeerAddress, DigestInfo> directHitsDigest) { int size = directHitsDigest.size(); int requested = p2pConfiguration.getMinimumResults(); if (size >= requested) { return p2pConfiguration; } else { return new RequestP2PConfiguration(size, p2pConfiguration.getMaxFailure(), p2pConfiguration.getParallelDiff()); } } } <file_sep>/* * Copyright 2012 <NAME> * * 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 net.tomp2p.p2p; import net.tomp2p.connection.DefaultConnectionConfiguration; import net.tomp2p.futures.BaseFutureAdapter; import net.tomp2p.futures.FutureChannelCreator; import net.tomp2p.futures.FutureResponse; import net.tomp2p.peers.Number160; import net.tomp2p.peers.PeerAddress; import net.tomp2p.rpc.PeerExchangeRPC; import net.tomp2p.storage.TrackerStorage; import net.tomp2p.utils.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The class that will handle the synchronization of the tracker data. * * @author <NAME> * */ public class TrackerStorageReplication implements ResponsibilityListener { private static final Logger LOG = LoggerFactory.getLogger(TrackerStorageReplication.class); private final PeerExchangeRPC peerExchangeRPC; private final TrackerStorage trackerStorage; private final Peer peer; /** * @param peer * This peer * @param peerExchangeRPC * The RPC to send informaiotn * @param trackerStorage * The memory based tracker storage */ public TrackerStorageReplication(final Peer peer, final PeerExchangeRPC peerExchangeRPC, final TrackerStorage trackerStorage) { this.peer = peer; this.peerExchangeRPC = peerExchangeRPC; this.trackerStorage = trackerStorage; } @Override public void meResponsible(final Number160 locationKey) { // the other has to send us the data, so do nothing } @Override public void otherResponsible(final Number160 locationKey, final PeerAddress other, final boolean delayed) { // do pex here, but with mesh peers! LOG.debug("other peer became responsibel and we thought we were responsible, so move the data to this peer"); peerExchange(locationKey, other); } @Override public void meResponsible(final Number160 locationKey, final PeerAddress newPeer) { LOG.debug("I'm responsible and a new peer joined"); peerExchange(locationKey, newPeer); } private void peerExchange(final Number160 locationKey, final PeerAddress newPeer) { for (final Number160 domainKey : trackerStorage.responsibleDomains(locationKey)) { FutureChannelCreator futureChannelCreator = peer.getConnectionBean().reservation().create(1, 0); futureChannelCreator.addListener(new BaseFutureAdapter<FutureChannelCreator>() { @Override public void operationComplete(final FutureChannelCreator future) throws Exception { if (future.isSuccess()) { FutureResponse futureResponse = peerExchangeRPC.peerExchange(newPeer, locationKey, domainKey, true, future.getChannelCreator(), new DefaultConnectionConfiguration()); Utils.addReleaseListener(future.getChannelCreator(), futureResponse); peer.notifyAutomaticFutures(futureResponse); } else { LOG.error("otherResponsible failed {}", future.getFailedReason()); } } }); } } } <file_sep>package net.tomp2p.message; import java.io.IOException; import java.security.InvalidKeyException; import java.security.PublicKey; import java.security.SignatureException; import java.util.List; import java.util.Map; import java.util.Map.Entry; import net.tomp2p.connection.SignatureFactory; import net.tomp2p.peers.Number160; import net.tomp2p.peers.Number640; import net.tomp2p.peers.PeerAddress; import net.tomp2p.peers.PeerSocketAddress; import net.tomp2p.rpc.SimpleBloomFilter; import net.tomp2p.storage.AlternativeCompositeByteBuf; import net.tomp2p.storage.Data; import net.tomp2p.utils.Timings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Encoder { private static final Logger LOG = LoggerFactory.getLogger(Encoder.class); private boolean header = false; private boolean resume = false; private Message message; private SignatureFactory signatureFactory; public Encoder(SignatureFactory signatureFactory) { this.signatureFactory = signatureFactory; } public boolean write(final AlternativeCompositeByteBuf buf, final Message message) throws InvalidKeyException, SignatureException, IOException { this.message = message; LOG.debug("message for outbound {}", message); if (!header) { MessageHeaderCodec.encodeHeader(buf, message); header = true; } else { LOG.debug("send a follow up message {}", message); resume = true; } LOG.debug("entering loop"); boolean done = loop(buf); LOG.debug("exiting loop"); // write out what we have if (buf.isReadable() && done) { // check if we need to sign the message if (message.isSign()) { SignatureCodec decodedSignature = signatureFactory.sign(message.getPrivateKey(), buf); decodedSignature.write(buf); } } return done; } private boolean loop(AlternativeCompositeByteBuf buf) throws InvalidKeyException, SignatureException, IOException { NumberType next; while ((next = message.contentRefencencs().peek()) != null) { switch (next.content()) { case KEY: buf.writeBytes(message.getKey(next.number()).toByteArray()); message.contentRefencencs().poll(); break; case INTEGER: buf.writeInt(message.getInteger(next.number())); message.contentRefencencs().poll(); break; case LONG: buf.writeLong(message.getLong(next.number())); message.contentRefencencs().poll(); break; case SET_NEIGHBORS: NeighborSet neighborSet = message.getNeighborsSet(next.number()); // length buf.writeByte(neighborSet.size()); for (PeerAddress neighbor : neighborSet.neighbors()) { buf.writeBytes(neighbor.toByteArray()); } message.contentRefencencs().poll(); break; case SET_PEER_SOCKET: List<PeerSocketAddress> list = message.getPeerSocketAddresses(); // length buf.writeByte(list.size()); for (PeerSocketAddress addr : list) { buf.writeByte(addr.isIPv4() ? 0:1); buf.writeBytes(addr.toByteArray()); } message.contentRefencencs().poll(); break; case BLOOM_FILTER: SimpleBloomFilter<Number160> simpleBloomFilter = message.getBloomFilter(next.number()); simpleBloomFilter.toByteBuf(buf); message.contentRefencencs().poll(); break; case SET_KEY640: // length KeyCollection keys = message.getKeyCollection(next.number()); buf.writeInt(keys.size()); if (keys.isConvert()) { for (Number160 key : keys.keysConvert()) { buf.writeBytes(keys.locationKey().toByteArray()); buf.writeBytes(keys.domainKey().toByteArray()); buf.writeBytes(key.toByteArray()); buf.writeBytes(keys.versionKey().toByteArray()); } } else { for (Number640 key : keys.keys()) { buf.writeBytes(key.getLocationKey().toByteArray()); buf.writeBytes(key.getDomainKey().toByteArray()); buf.writeBytes(key.getContentKey().toByteArray()); buf.writeBytes(key.getVersionKey().toByteArray()); } } message.contentRefencencs().poll(); break; case MAP_KEY640_DATA: DataMap dataMap = message.getDataMap(next.number()); buf.writeInt(dataMap.size()); if (dataMap.isConvert()) { for (Entry<Number160, Data> entry : dataMap.dataMapConvert().entrySet()) { buf.writeBytes(dataMap.locationKey().toByteArray()); buf.writeBytes(dataMap.domainKey().toByteArray()); buf.writeBytes(entry.getKey().toByteArray()); buf.writeBytes(dataMap.versionKey().toByteArray()); encodeData(buf, entry.getValue(), dataMap.isConvertMeta(), !message.isRequest()); } } else { for (Entry<Number640, Data> entry : dataMap.dataMap().entrySet()) { buf.writeBytes(entry.getKey().getLocationKey().toByteArray()); buf.writeBytes(entry.getKey().getDomainKey().toByteArray()); buf.writeBytes(entry.getKey().getContentKey().toByteArray()); buf.writeBytes(entry.getKey().getVersionKey().toByteArray()); encodeData(buf, entry.getValue(), dataMap.isConvertMeta(), !message.isRequest()); } } message.contentRefencencs().poll(); break; case MAP_KEY640_KEY: KeyMap640 keyMap640 = message.getKeyMap640(next.number()); buf.writeInt(keyMap640.size()); for (Entry<Number640, Number160> entry : keyMap640.keysMap().entrySet()) { buf.writeBytes(entry.getKey().getLocationKey().toByteArray()); buf.writeBytes(entry.getKey().getDomainKey().toByteArray()); buf.writeBytes(entry.getKey().getContentKey().toByteArray()); buf.writeBytes(entry.getKey().getVersionKey().toByteArray()); buf.writeBytes(entry.getValue().toByteArray()); } message.contentRefencencs().poll(); break; case MAP_KEY640_BYTE: KeyMapByte keysMap = message.getKeyMapByte(next.number()); buf.writeInt(keysMap.size()); for (Entry<Number640, Byte> entry : keysMap.keysMap().entrySet()) { buf.writeBytes(entry.getKey().getLocationKey().toByteArray()); buf.writeBytes(entry.getKey().getDomainKey().toByteArray()); buf.writeBytes(entry.getKey().getContentKey().toByteArray()); buf.writeBytes(entry.getKey().getVersionKey().toByteArray()); buf.writeByte(entry.getValue()); } message.contentRefencencs().poll(); break; case BYTE_BUFFER: Buffer buffer = message.getBuffer(next.number()); if (!resume) { buf.writeInt(buffer.length()); } int readable = buffer.readable(); buf.writeBytes(buffer.buffer(), readable); if (buffer.incRead(readable) == buffer.length()) { message.contentRefencencs().poll(); } else if (message.isStreaming()) { LOG.debug("we sent a partial message of length {}", readable); return false; } else { LOG.debug("Announced a larger buffer, but not in streaming mode. This is wrong."); throw new RuntimeException( "Announced a larger buffer, but not in streaming mode. This is wrong."); } break; case SET_TRACKER_DATA: TrackerData trackerData = message.getTrackerData(next.number()); buf.writeByte(trackerData.getPeerAddresses().size()); // 1 bytes - length, max. 255 for (Map.Entry<PeerAddress, Data> entry : trackerData.getPeerAddresses().entrySet()) { buf.writeBytes(entry.getKey().toByteArray()); Data data = entry.getValue().duplicate(); encodeData(buf, data, false, !message.isRequest()); } message.contentRefencencs().poll(); break; case PUBLIC_KEY_SIGNATURE: // flag to encode public key message.setHintSign(); // then do the regular public key stuff case PUBLIC_KEY: PublicKey publicKey = message.getPublicKey(next.number()); signatureFactory.encodePublicKey(publicKey, buf); message.contentRefencencs().poll(); break; default: case USER1: throw new RuntimeException("Unknown type: " + next.content()); } } return true; } private void encodeData(AlternativeCompositeByteBuf buf, Data data, boolean isConvertMeta, boolean isReply) throws InvalidKeyException, SignatureException, IOException { if(isConvertMeta) { data = data.duplicateMeta(); } else { data = data.duplicate(); } if(isReply) { int ttl = (int) ((data.expirationMillis() - Timings.currentTimeMillis()) / 1000); data.ttlSeconds(ttl < 0 ? 0:ttl); } data.encodeHeader(buf, signatureFactory); data.encodeDone(buf, signatureFactory); } public Message message() { return message; } public void reset() { header = false; resume = false; } } <file_sep>/* * Copyright 2012 <NAME> * * 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 net.tomp2p.p2p; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Random; import java.util.SortedSet; import java.util.TimerTask; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import net.tomp2p.futures.BaseFutureAdapter; import net.tomp2p.futures.FutureChannelCreator; import net.tomp2p.futures.FutureResponse; import net.tomp2p.p2p.builder.PutBuilder; import net.tomp2p.peers.Number160; import net.tomp2p.peers.Number640; import net.tomp2p.peers.PeerAddress; import net.tomp2p.rpc.StorageRPC; import net.tomp2p.storage.Data; import net.tomp2p.storage.StorageLayer; import net.tomp2p.utils.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This implements the default indirect replication. * * @author <NAME> * @author <NAME> * */ public class ReplicationExecutor implements ResponsibilityListener, Runnable { private static final Logger LOG = LoggerFactory.getLogger(ReplicationExecutor.class); private final StorageLayer storage; private final StorageRPC storageRPC; private final Peer peer; private final Replication replicationStorage; // default replication for put and add is 6 private static final int REPLICATION = 6; private final ScheduledExecutorService timer; private final Random random; private final int delayMillis; // private final ReplicationFactor replicationFactor; private final ReplicationSender replicationSender; private final boolean allPeersReplicate; private ScheduledFuture<?> scheduledFuture; /** * Constructor for the default indirect replication. * * @param peer * The peer */ public ReplicationExecutor(final Peer peer, final ReplicationFactor replicationFactor, ReplicationSender replicationSender, final Random random, final ScheduledExecutorService timer, final int delayMillis, final boolean allPeersReplicate) { this.peer = peer; this.storage = peer.getPeerBean().storage(); this.storageRPC = peer.getStoreRPC(); this.replicationStorage = peer.getPeerBean().replicationStorage(); replicationStorage.addResponsibilityListener(this); replicationStorage.setReplicationFactor(REPLICATION); this.random = random; this.timer = timer; this.delayMillis = delayMillis; this.replicationFactor = replicationFactor; this.replicationSender = replicationSender; this.allPeersReplicate = allPeersReplicate; } public void init(int intervalMillis) { scheduledFuture = timer.scheduleAtFixedRate(this, intervalMillis, intervalMillis, TimeUnit.MILLISECONDS); } @Override public void otherResponsible(final Number160 locationKey, final PeerAddress other, final boolean delayed) { if(!allPeersReplicate) { return; } LOG.debug("Other peer {} is responsible for {}. I'm {}", other, locationKey, storageRPC.peerBean() .serverPeerAddress()); if (!delayed) { Number640 min = new Number640(locationKey, Number160.ZERO, Number160.ZERO, Number160.ZERO); Number640 max = new Number640(locationKey, Number160.MAX_VALUE, Number160.MAX_VALUE, Number160.MAX_VALUE); final Map<Number640, Data> dataMap = storage.get(min, max, -1, true); replicationSender.sendDirect(other, locationKey, dataMap); LOG.debug("transfer from {} to {} for key {}", storageRPC.peerBean().serverPeerAddress(), other, locationKey); } else { timer.schedule(new TimerTask() { @Override public void run() { otherResponsible(locationKey, other, false); } }, random.nextInt(delayMillis), TimeUnit.MILLISECONDS); } } @Override public void meResponsible(final Number160 locationKey) { LOG.debug("I ({}) now responsible for {}", storageRPC.peerBean().serverPeerAddress(), locationKey); synchronizeData(locationKey); } @Override public void meResponsible(final Number160 locationKey, PeerAddress newPeer) { LOG.debug("I ({}) sync {} to {}", storageRPC.peerBean().serverPeerAddress(), locationKey, newPeer); Number640 min = new Number640(locationKey, Number160.ZERO, Number160.ZERO, Number160.ZERO); Number640 max = new Number640(locationKey, Number160.MAX_VALUE, Number160.MAX_VALUE, Number160.MAX_VALUE); final Map<Number640, Data> dataMap = storage.get(min, max, -1, true); replicationSender.sendDirect(newPeer, locationKey, dataMap); } @Override public void run() { // we get called every x seconds for content we are responsible for. So // we need to make sure that there are enough copies. The easy way is to // publish it again... The good way is to do a diff Collection<Number160> locationKeys = storage.findContentForResponsiblePeerID(peer.getPeerID()); for (Number160 locationKey : locationKeys) { synchronizeData(locationKey); } // recalculate replication factor int replicationFactor = ReplicationExecutor.this.replicationFactor.replicationFactor(); peer.getPeerBean().replicationStorage().setReplicationFactor(replicationFactor); } /** * Get the data that I'm responsible for and make sure that there are enough replicas. * * @param locationKey * The location key. */ private void synchronizeData(final Number160 locationKey) { Number640 min = new Number640(locationKey, Number160.ZERO, Number160.ZERO, Number160.ZERO); Number640 max = new Number640(locationKey, Number160.MAX_VALUE, Number160.MAX_VALUE, Number160.MAX_VALUE); final Map<Number640, Data> dataMap = storage.get(min, max, -1, true); List<PeerAddress> closePeers = send(locationKey, dataMap); LOG.debug("[storage refresh] I ({}) restore {} to {}", storageRPC.peerBean().serverPeerAddress(), locationKey, closePeers); } /** * If my peer is responsible, I'll issue a put if absent to make sure all replicas are stored. * * @param locationKey * The location key * @param domainKey * The domain key * @param dataMapConverted * The data to store * @return The future of the put */ protected List<PeerAddress> send(final Number160 locationKey, final Map<Number640, Data> dataMapConverted) { int replicationFactor = replicationStorage.getReplicationFactor() - 1; List<PeerAddress> closePeers = new ArrayList<PeerAddress>(); SortedSet<PeerAddress> sortedSet = peer.getPeerBean().peerMap() .closePeers(locationKey, replicationFactor); int count = 0; for (PeerAddress peerAddress : sortedSet) { count++; closePeers.add(peerAddress); replicationSender.sendDirect(peerAddress, locationKey, dataMapConverted); if (count == replicationFactor) { break; } } return closePeers; } public static class DefaultReplicationSender implements ReplicationSender { private StorageRPC storageRPC; private Peer peer; @Override public void init(Peer peer) { this.peer = peer; this.storageRPC = peer.getStoreRPC(); } /** * If an other peer is responsible, we send this peer our data, so that the other peer can take care of this. * * @param other * The other peer * @param locationKey * The location key * @param domainKey * The domain key * @param dataMapConvert * The data to store */ public void sendDirect(final PeerAddress other, final Number160 locationKey, final Map<Number640, Data> dataMap) { FutureChannelCreator futureChannelCreator = peer.getConnectionBean().reservation().create(0, 1); futureChannelCreator.addListener(new BaseFutureAdapter<FutureChannelCreator>() { @Override public void operationComplete(final FutureChannelCreator future) throws Exception { if (future.isSuccess()) { PutBuilder putBuilder = new PutBuilder(peer, locationKey); putBuilder.setDataMap(dataMap); FutureResponse futureResponse = storageRPC.put(other, putBuilder, future.getChannelCreator()); Utils.addReleaseListener(future.getChannelCreator(), futureResponse); peer.notifyAutomaticFutures(futureResponse); } else { if (LOG.isErrorEnabled()) { LOG.error("otherResponsible failed " + future.getFailedReason()); } } } }); } } public void shutdown() { if(scheduledFuture!=null) { scheduledFuture.cancel(false); } } } <file_sep>/* * Copyright 2012 <NAME> * * 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 net.tomp2p.p2p; import io.netty.channel.ChannelHandler; import io.netty.util.concurrent.EventExecutorGroup; import java.io.IOException; import java.security.KeyPair; import java.security.PublicKey; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Random; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import net.tomp2p.connection.Bindings; import net.tomp2p.connection.ChannelClientConfiguration; import net.tomp2p.connection.ChannelServerConficuration; import net.tomp2p.connection.ConnectionBean; import net.tomp2p.connection.DSASignatureFactory; import net.tomp2p.connection.PeerBean; import net.tomp2p.connection.PeerCreator; import net.tomp2p.connection.PipelineFilter; import net.tomp2p.connection.Ports; import net.tomp2p.peers.Number160; import net.tomp2p.peers.PeerMap; import net.tomp2p.peers.PeerMapConfiguration; import net.tomp2p.peers.PeerStatusListener; import net.tomp2p.rpc.BloomfilterFactory; import net.tomp2p.rpc.BroadcastRPC; import net.tomp2p.rpc.DefaultBloomfilterFactory; import net.tomp2p.rpc.DirectDataRPC; import net.tomp2p.rpc.NeighborRPC; import net.tomp2p.rpc.PeerExchangeRPC; import net.tomp2p.rpc.PingRPC; import net.tomp2p.rpc.QuitRPC; import net.tomp2p.rpc.StorageRPC; //import net.tomp2p.rpc.TaskRPC; import net.tomp2p.rpc.TrackerRPC; import net.tomp2p.storage.IdentityManagement; import net.tomp2p.storage.Storage; import net.tomp2p.storage.StorageLayer; import net.tomp2p.storage.StorageMemory; import net.tomp2p.storage.TrackerStorage; import net.tomp2p.utils.Pair; import net.tomp2p.utils.Utils; /** * The maker / builder of a {@link Peer} class. * * @author <NAME> * */ public class PeerMaker { public static final PublicKey EMPTY_PUBLICKEY = new PublicKey() { private static final long serialVersionUID = 4041565007522454573L; @Override public String getFormat() { return null; } @Override public byte[] getEncoded() { return null; } @Override public String getAlgorithm() { return null; } }; private static final KeyPair EMPTY_KEYPAIR = new KeyPair(EMPTY_PUBLICKEY, null); // if the permits are chosen too high, then we might run into timeouts as we // cant handle that many connections // withing the time limit private static final int MAX_PERMITS_PERMANENT_TCP = 250; private static final int MAX_PERMITS_UDP = 250; private static final int MAX_PERMITS_TCP = 250; // required private final Number160 peerId; // optional with reasonable defaults private KeyPair keyPair = null; private int p2pID = -1; private int tcpPort = -1; private int udpPort = -1; private Bindings interfaceBindings = null; private Bindings externalBindings = null; private PeerMap peerMap = null; private Peer masterPeer = null; private ChannelServerConficuration channelServerConfiguration = null; private ChannelClientConfiguration channelClientConfiguration = null; private PeerStatusListener[] peerStatusListeners = null; private Storage storage = null; private TrackerStorage trackerStorage = null; private Boolean behindFirewall = null; // private int workerThreads = Runtime.getRuntime().availableProcessors() + // 1; // private File fileMessageLogger = null; // private ConnectionConfiguration configuration = null; // private StorageGeneric storage; private BroadcastHandler broadcastHandler; private BloomfilterFactory bloomfilterFactory; private ScheduledExecutorService scheduledExecutorService = null; private MaintenanceTask maintenanceTask = null; private ReplicationExecutor replicationExecutor = null; private List<AutomaticFuture> automaticFutures = null; private Random random = null; private int delayMillis = -1; private boolean allPeersReplicate = false; private int intervalMillis = -1; private int storageIntervalMillis = -1; private ReplicationFactor replicationFactor = null; private ReplicationSender replicationSender = null; private List<PeerInit> toInitialize = new ArrayList<PeerInit>(1); // private ReplicationExecutor replicationExecutor; // max, message size to transmit // private int maxMessageSize = 2 * 1024 * 1024; // PeerMap // private int bagSize = 2; // private int cacheTimeoutMillis = 60 * 1000; // private int maxNrBeforeExclude = 2; // private int[] waitingTimeBetweenNodeMaintenenceSeconds = { 5, 10, 20, 40, // 80, 160 }; // private int cacheSize = 100; // enable / disable private boolean enableHandShakeRPC = true; private boolean enableStorageRPC = true; private boolean enableNeighborRPC = true; private boolean enableQuitRPC = true; private boolean enablePeerExchangeRPC = true; private boolean enableDirectDataRPC = true; private boolean enableTrackerRPC = true; private boolean enableTaskRPC = true; private boolean enableSynchronizationRPC = true; // P2P private boolean enableRouting = true; private boolean enableDHT = true; private boolean enableTracker = true; private boolean enableTask = true; private boolean enableMaintenance = true; private boolean enableIndirectReplication = false; private boolean enableBroadcast = true; // private Random rnd; /** * Creates a peermaker with the peer ID and an empty key pair. * * @param peerId * The peer Id */ public PeerMaker(final Number160 peerId) { this.peerId = peerId; } /** * Creates a peermaker with the key pair and generates out of this key pair * the peer ID. * * @param keyPair * The public private key */ public PeerMaker(final KeyPair keyPair) { this.peerId = Utils.makeSHAHash(keyPair.getPublic().getEncoded()); this.keyPair = keyPair; } /** * Create a peer and start to listen for incoming connections. * * @return The peer that can operate in the P2P network. * @throws IOException . */ public Peer makeAndListen() throws IOException { if (behindFirewall == null) { behindFirewall = false; } if (channelServerConfiguration == null) { channelServerConfiguration = createDefaultChannelServerConfiguration(); } if (channelClientConfiguration == null) { channelClientConfiguration = createDefaultChannelClientConfiguration(); } if (keyPair == null) { keyPair = EMPTY_KEYPAIR; } if (p2pID == -1) { p2pID = 1; } if (tcpPort == -1) { tcpPort = Ports.DEFAULT_PORT; } if (udpPort == -1) { udpPort = Ports.DEFAULT_PORT; } channelServerConfiguration.ports(new Ports(tcpPort, udpPort)); if (interfaceBindings == null) { interfaceBindings = new Bindings(); } channelServerConfiguration.interfaceBindings(interfaceBindings); if (externalBindings == null) { externalBindings = new Bindings(); } channelClientConfiguration.externalBindings(externalBindings); if (peerMap == null) { peerMap = new PeerMap(new PeerMapConfiguration(peerId)); } if (storage == null) { storage = new StorageMemory(); } if (storageIntervalMillis == -1) { storageIntervalMillis = 60 * 1000; } if (peerStatusListeners == null) { peerStatusListeners = new PeerStatusListener[] { peerMap }; } if (masterPeer == null && scheduledExecutorService == null) { scheduledExecutorService = Executors.newScheduledThreadPool(1); } final PeerCreator peerCreator; if (masterPeer != null) { peerCreator = new PeerCreator(masterPeer.peerCreator(), peerId, keyPair); } else { peerCreator = new PeerCreator(p2pID, peerId, keyPair, channelServerConfiguration, channelClientConfiguration, peerStatusListeners, scheduledExecutorService); } final Peer peer = new Peer(p2pID, peerId, peerCreator); PeerBean peerBean = peerCreator.peerBean(); ConnectionBean connectionBean = peerCreator.connectionBean(); peerBean.peerMap(peerMap); peerBean.keyPair(keyPair); StorageLayer sl = new StorageLayer(storage); peerBean.storage(sl); sl.init(connectionBean.timer(), storageIntervalMillis); if (trackerStorage == null) { trackerStorage = new TrackerStorage(new IdentityManagement(peerBean.serverPeerAddress()), 300, peerBean.getReplicationTracker(), new Maintenance()); } peerBean.trackerStorage(trackerStorage); if (bloomfilterFactory == null) { peerBean.bloomfilterFactory(new DefaultBloomfilterFactory()); } if (broadcastHandler == null) { broadcastHandler = new DefaultBroadcastHandler(peer, new Random()); } // peerBean.setStorage(getStorage()); Replication replicationStorage = new Replication(storage, peerBean.serverPeerAddress(), peerMap, 5); peerBean.replicationStorage(replicationStorage); // TrackerStorage storageTracker = new // TrackerStorage(identityManagement, // configuration.getTrackerTimoutSeconds(), peerBean, maintenance); // peerBean.setTrackerStorage(storageTracker); // Replication replicationTracker = new Replication(storageTracker, // selfAddress, peerMap, 5); // peerBean.setReplicationTracker(replicationTracker); // peerMap.addPeerOfflineListener(storageTracker); // TaskManager taskManager = new TaskManager(connectionBean, // workerThreads); // peerBean.setTaskManager(taskManager); // IdentityManagement identityManagement = new // IdentityManagement(selfAddress); // Maintenance maintenance = new Maintenance(); initRPC(peer, connectionBean, peerBean); initP2P(peer, connectionBean, peerBean); if (maintenanceTask == null && isEnableMaintenance()) { maintenanceTask = new MaintenanceTask(); } if (maintenanceTask != null) { maintenanceTask.init(peer, connectionBean.timer()); maintenanceTask.addMaintainable(peerMap); } peerBean.maintenanceTask(maintenanceTask); if (random == null) { random = new Random(); } if (intervalMillis == -1) { intervalMillis = 60 * 1000; } if (delayMillis == -1) { delayMillis = 30 * 1000; } if (replicationFactor == null) { replicationFactor = new ReplicationFactor() { @Override public int replicationFactor() { // Default is 6 as in the builders return 6; } @Override public void init(Peer peer) { } }; } //here we need the peermap to be ready replicationFactor.init(peer); if (replicationSender == null) { replicationSender = new ReplicationExecutor.DefaultReplicationSender(); } replicationSender.init(peer); // indirect replication if (replicationExecutor == null && isEnableIndirectReplication() && isEnableStorageRPC()) { replicationExecutor = new ReplicationExecutor(peer, replicationFactor, replicationSender, random, connectionBean.timer(), delayMillis, allPeersReplicate); } if (replicationExecutor != null) { replicationExecutor.init(intervalMillis); } peerBean.replicationExecutor(replicationExecutor); if (automaticFutures != null) { peer.setAutomaticFutures(automaticFutures); } // set the ping builder for the heart beat connectionBean.sender().pingBuilder(peer.ping()); for (PeerInit peerInit : toInitialize) { peerInit.init(peer); } return peer; } public static ChannelServerConficuration createDefaultChannelServerConfiguration() { ChannelServerConficuration channelServerConfiguration = new ChannelServerConficuration(); channelServerConfiguration.interfaceBindings(new Bindings()); channelServerConfiguration.ports(new Ports(Ports.DEFAULT_PORT, Ports.DEFAULT_PORT)); channelServerConfiguration.setBehindFirewall(false); channelServerConfiguration.pipelineFilter(new DefaultPipelineFilter()); channelServerConfiguration.signatureFactory(new DSASignatureFactory()); return channelServerConfiguration; } public static ChannelClientConfiguration createDefaultChannelClientConfiguration() { ChannelClientConfiguration channelClientConfiguration = new ChannelClientConfiguration(); channelClientConfiguration.externalBindings(new Bindings()); channelClientConfiguration.maxPermitsPermanentTCP(MAX_PERMITS_PERMANENT_TCP); channelClientConfiguration.maxPermitsTCP(MAX_PERMITS_TCP); channelClientConfiguration.maxPermitsUDP(MAX_PERMITS_UDP); channelClientConfiguration.pipelineFilter(new DefaultPipelineFilter()); channelClientConfiguration.signatureFactory(new DSASignatureFactory()); return channelClientConfiguration; } /** * Initialize the RPC communications. * * @param peer * The peer where the RPC reference is stored * @param connectionBean * The connection bean * @param peerBean * The peer bean */ private void initRPC(final Peer peer, final ConnectionBean connectionBean, final PeerBean peerBean) { // RPC communication if (isEnableHandShakeRPC()) { PingRPC handshakeRCP = new PingRPC(peerBean, connectionBean); peer.pingRPC(handshakeRCP); } if (isEnableStorageRPC()) { StorageRPC storageRPC = new StorageRPC(peerBean, connectionBean); peer.setStorageRPC(storageRPC); } if (isEnableNeighborRPC()) { NeighborRPC neighborRPC = new NeighborRPC(peerBean, connectionBean); peer.setNeighborRPC(neighborRPC); } if (isEnableDirectDataRPC()) { DirectDataRPC directDataRPC = new DirectDataRPC(peerBean, connectionBean); peer.setDirectDataRPC(directDataRPC); } if (isEnableQuitRPC()) { QuitRPC quitRCP = new QuitRPC(peerBean, connectionBean); quitRCP.addPeerStatusListener(peerMap); peer.setQuitRPC(quitRCP); } if (isEnablePeerExchangeRPC()) { PeerExchangeRPC peerExchangeRPC = new PeerExchangeRPC(peerBean, connectionBean); peer.setPeerExchangeRPC(peerExchangeRPC); } if (isEnableTrackerRPC()) { TrackerRPC trackerRPC = new TrackerRPC(peerBean, connectionBean); peer.setTrackerRPC(trackerRPC); } if (isEnableBroadcast()) { BroadcastRPC broadcastRPC = new BroadcastRPC(peerBean, connectionBean, broadcastHandler); peer.setBroadcastRPC(broadcastRPC); } } private void initP2P(final Peer peer, final ConnectionBean connectionBean, final PeerBean peerBean) { // distributed communication if (isEnableRouting() && isEnableNeighborRPC()) { DistributedRouting routing = new DistributedRouting(peerBean, peer.getNeighborRPC()); peer.setDistributedRouting(routing); } if (isEnableRouting() && isEnableStorageRPC() && isEnableDirectDataRPC()) { DistributedHashTable dht = new DistributedHashTable(peer.getDistributedRouting(), peer.getStoreRPC(), peer.getDirectDataRPC(), peer.getQuitRPC()); peer.setDistributedHashMap(dht); } if (isEnableRouting() && isEnableTrackerRPC() && isEnablePeerExchangeRPC()) { DistributedTracker tracker = new DistributedTracker(peerBean, peer.getDistributedRouting(), peer.getTrackerRPC(), peer.getPeerExchangeRPC()); peer.setDistributedTracker(tracker); } /*if (isEnableTaskRPC() && * isEnableTask() && isEnableRouting()) { // the task manager needs to * use the rpc to send the result back. //TODO: enable again * //peerBean.getTaskManager().init(peer.getTaskRPC()); //AsyncTask * asyncTask = new AsyncTask(peer.getTaskRPC(), * connectionBean.getScheduler(), peerBean); * //peer.setAsyncTask(asyncTask); * //peerBean.getTaskManager().addListener(asyncTask); * //connectionBean.getScheduler().startTracking(peer.getTaskRPC(), // * connectionBean.getConnectionReservation()); //DistributedTask * distributedTask = new DistributedTask(peer.getDistributedRouting(), * peer.getAsyncTask()); //peer.setDistributedTask(distributedTask); } * // maintenance if (isEnableMaintenance()) { //TODO: enable again * //connectionHandler // .getConnectionBean() // .getScheduler() // * .startMaintainance(peerBean.getPeerMap(), peer.getHandshakeRPC(), // * connectionBean.getConnectionReservation(), 5); } */ } public Number160 peerId() { return peerId; } public KeyPair keyPair() { return keyPair; } public PeerMaker keyPair(KeyPair keyPair) { this.keyPair = keyPair; return this; } public int p2pId() { return p2pID; } public PeerMaker p2pId(int p2pID) { this.p2pID = p2pID; return this; } public int tcpPort() { return tcpPort; } public PeerMaker tcpPort(int tcpPort) { this.tcpPort = tcpPort; return this; } public int udpPort() { return udpPort; } public PeerMaker udpPort(int udpPort) { this.udpPort = udpPort; return this; } public PeerMaker ports(int port) { this.udpPort = port; this.tcpPort = port; return this; } public PeerMaker bindings(Bindings bindings) { this.interfaceBindings = bindings; this.externalBindings = bindings; return this; } public Bindings interfaceBindings() { return interfaceBindings; } public PeerMaker interfaceBindings(Bindings interfaceBindings) { this.interfaceBindings = interfaceBindings; return this; } public Bindings externalBindings() { return externalBindings; } public PeerMaker externalBindings(Bindings externalBindings) { this.externalBindings = externalBindings; return this; } public PeerMap peerMap() { return peerMap; } public PeerMaker peerMap(PeerMap peerMap) { this.peerMap = peerMap; return this; } public Storage storage() { return storage; } public PeerMaker storage(Storage storage) { this.storage = storage; return this; } public Peer masterPeer() { return masterPeer; } public PeerMaker masterPeer(Peer masterPeer) { this.masterPeer = masterPeer; return this; } public ChannelServerConficuration channelServerConfiguration() { return channelServerConfiguration; } public PeerMaker channelServerConfiguration(ChannelServerConficuration channelServerConfiguration) { this.channelServerConfiguration = channelServerConfiguration; return this; } public ChannelClientConfiguration channelClientConfiguration() { return channelClientConfiguration; } public PeerMaker channelClientConfiguration(ChannelClientConfiguration channelClientConfiguration) { this.channelClientConfiguration = channelClientConfiguration; return this; } public PeerStatusListener[] peerStatusListeners() { return peerStatusListeners; } public PeerMaker peerStatusListeners(PeerStatusListener[] peerStatusListeners) { this.peerStatusListeners = peerStatusListeners; return this; } public BroadcastHandler broadcastHandler() { return broadcastHandler; } public PeerMaker broadcastHandler(BroadcastHandler broadcastHandler) { this.broadcastHandler = broadcastHandler; return this; } public BloomfilterFactory bloomfilterFactory() { return bloomfilterFactory; } public PeerMaker bloomfilterFactory(BloomfilterFactory bloomfilterFactory) { this.bloomfilterFactory = bloomfilterFactory; return this; } public MaintenanceTask maintenanceTask() { return maintenanceTask; } public PeerMaker maintenanceTask(MaintenanceTask maintenanceTask) { this.maintenanceTask = maintenanceTask; return this; } public ReplicationExecutor replicationExecutor() { return replicationExecutor; } public PeerMaker replicationExecutor(ReplicationExecutor replicationExecutor) { this.replicationExecutor = replicationExecutor; return this; } public Random random() { return random; } public PeerMaker random(Random random) { this.random = random; return this; } public int delayMillis() { return delayMillis; } public PeerMaker delayMillis(int delayMillis) { this.delayMillis = delayMillis; return this; } public boolean isAllPeersReplicate() { return allPeersReplicate; } public PeerMaker allPeersReplicate() { this.allPeersReplicate = true; return this; } public PeerMaker allPeersReplicate(boolean allPeersReplicate) { this.allPeersReplicate = allPeersReplicate; return this; } public int intervalMillis() { return intervalMillis; } public PeerMaker intervalMillis(int intervalMillis) { this.intervalMillis = intervalMillis; return this; } public int storageIntervalMillis() { return storageIntervalMillis; } public PeerMaker storageIntervalMillis(int storageIntervalMillis) { this.storageIntervalMillis = storageIntervalMillis; return this; } public ReplicationFactor replicationFactor() { return replicationFactor; } public PeerMaker replicationFactor(ReplicationFactor replicationFactor) { this.replicationFactor = replicationFactor; return this; } public ReplicationSender replicationSender() { return replicationSender; } public PeerMaker replicationSender(ReplicationSender replicationSender) { this.replicationSender = replicationSender; return this; } public PeerMaker init(PeerInit init) { toInitialize.add(init); return this; } public PeerMaker init(PeerInit... inits) { for (PeerInit init : inits) { toInitialize.add(init); } return this; } public ScheduledExecutorService timer() { return scheduledExecutorService; } public PeerMaker timer(ScheduledExecutorService scheduledExecutorService) { this.scheduledExecutorService = scheduledExecutorService; return this; } // isEnabled methods public boolean isEnableHandShakeRPC() { return enableHandShakeRPC; } public PeerMaker setEnableHandShakeRPC(boolean enableHandShakeRPC) { this.enableHandShakeRPC = enableHandShakeRPC; return this; } public boolean isEnableStorageRPC() { return enableStorageRPC; } public PeerMaker setEnableStorageRPC(boolean enableStorageRPC) { this.enableStorageRPC = enableStorageRPC; return this; } public boolean isEnableNeighborRPC() { return enableNeighborRPC; } public PeerMaker setEnableNeighborRPC(boolean enableNeighborRPC) { this.enableNeighborRPC = enableNeighborRPC; return this; } public boolean isEnableQuitRPC() { return enableQuitRPC; } public PeerMaker setEnableQuitRPC(boolean enableQuitRPC) { this.enableQuitRPC = enableQuitRPC; return this; } public boolean isEnablePeerExchangeRPC() { return enablePeerExchangeRPC; } public PeerMaker setEnablePeerExchangeRPC(boolean enablePeerExchangeRPC) { this.enablePeerExchangeRPC = enablePeerExchangeRPC; return this; } public boolean isEnableDirectDataRPC() { return enableDirectDataRPC; } public PeerMaker setEnableDirectDataRPC(boolean enableDirectDataRPC) { this.enableDirectDataRPC = enableDirectDataRPC; return this; } public boolean isEnableTrackerRPC() { return enableTrackerRPC; } public PeerMaker setEnableTrackerRPC(boolean enableTrackerRPC) { this.enableTrackerRPC = enableTrackerRPC; return this; } public boolean isEnableTaskRPC() { return enableTaskRPC; } public PeerMaker setEnableTaskRPC(boolean enableTaskRPC) { this.enableTaskRPC = enableTaskRPC; return this; } public boolean isEnableSynchronizationRPC() { return enableSynchronizationRPC; } public PeerMaker setEnableSynchronizationRPC(boolean enableQuitRPC) { this.enableQuitRPC = enableQuitRPC; return this; } public boolean isEnableRouting() { return enableRouting; } public PeerMaker setEnableRouting(boolean enableRouting) { this.enableRouting = enableRouting; return this; } public boolean isEnableDHT() { return enableDHT; } public PeerMaker setEnableDHT(boolean enableDHT) { this.enableDHT = enableDHT; return this; } public boolean isEnableTracker() { return enableTracker; } public PeerMaker setEnableTracker(boolean enableTracker) { this.enableTracker = enableTracker; return this; } public boolean isEnableTask() { return enableTask; } public PeerMaker setEnableTask(boolean enableTask) { this.enableTask = enableTask; return this; } public boolean isEnableMaintenance() { return enableMaintenance; } public PeerMaker setEnableMaintenance(boolean enableMaintenance) { this.enableMaintenance = enableMaintenance; return this; } public boolean isEnableIndirectReplication() { return enableIndirectReplication; } public PeerMaker setEnableIndirectReplication(boolean enableIndirectReplication) { this.enableIndirectReplication = enableIndirectReplication; return this; } public boolean isEnableBroadcast() { return enableBroadcast; } public PeerMaker setEnableBroadcast(boolean enableBroadcast) { this.enableBroadcast = enableBroadcast; return this; } /** * @return True if this peer is behind a firewall and cannot be accessed * directly */ public boolean isBehindFirewall() { return behindFirewall == null ? false : behindFirewall; } /** * @param behindFirewall * Set to true if this peer is behind a firewall and cannot be * accessed directly * @return This class */ public PeerMaker setBehindFirewall(final boolean behindFirewall) { this.behindFirewall = behindFirewall; return this; } /** * Set peer to be behind a firewall and cannot be accessed directly. * * @return This class */ public PeerMaker setBehindFirewall() { this.behindFirewall = true; return this; } public PeerMaker addAutomaticFuture(AutomaticFuture automaticFuture) { if (automaticFutures == null) { automaticFutures = new ArrayList<>(1); } automaticFutures.add(automaticFuture); return this; } /** * The default filter is no filter, just return the same array. * * @author <NAME> * */ public static class DefaultPipelineFilter implements PipelineFilter { @Override public Map<String,Pair<EventExecutorGroup,ChannelHandler>> filter(final Map<String, Pair<EventExecutorGroup, ChannelHandler>> channelHandlers, boolean tcp, boolean client) { return channelHandlers; } } /** * A pipeline filter that executes handlers in a thread. If you plan to * block within listeners, then use this pipeline. * * @author <NAME> * */ public static class EventExecutorGroupFilter implements PipelineFilter { private final EventExecutorGroup eventExecutorGroup; public EventExecutorGroupFilter(EventExecutorGroup eventExecutorGroup) { this.eventExecutorGroup = eventExecutorGroup; } @Override public Map<String,Pair<EventExecutorGroup,ChannelHandler>> filter(final Map<String, Pair<EventExecutorGroup, ChannelHandler>> channelHandlers, boolean tcp, boolean client) { setExecutor("handler", channelHandlers); setExecutor("dispatcher", channelHandlers); return channelHandlers; } private void setExecutor(String handlerName, final Map<String, Pair<EventExecutorGroup, ChannelHandler>> channelHandlers) { Pair<EventExecutorGroup, ChannelHandler> pair = channelHandlers.get(handlerName); if (pair != null) { channelHandlers.put(handlerName, pair.element0(eventExecutorGroup)); } } } } <file_sep>/* * Copyright 2009 <NAME> * * 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 net.tomp2p.peers; import java.io.Serializable; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import net.tomp2p.utils.Timings; /** * Keeps track of the statistics of a given peer. * * @author <NAME> * */ public class PeerStatatistic implements Serializable { private static final long serialVersionUID = -6225586345726672194L; private final AtomicLong lastSeenOnline = new AtomicLong(0); private final long created = Timings.currentTimeMillis(); private final AtomicInteger successfullyChecked = new AtomicInteger(0); private final AtomicInteger failed = new AtomicInteger(0); private PeerAddress peerAddress; /** * Constructor. Sets the peer address * * @param peerAddress * The peer address that belongs to this statistics */ public PeerStatatistic(final PeerAddress peerAddress) { if (peerAddress == null) { throw new IllegalArgumentException("PeerAddress cannot be null"); } this.peerAddress = peerAddress; } /** * Sets the time when last seen online to now. * * @return The number of successful checks */ public int successfullyChecked() { lastSeenOnline.set(Timings.currentTimeMillis()); failed.set(0); return successfullyChecked.incrementAndGet(); } /** * @return The time last seen online */ public long getLastSeenOnline() { return lastSeenOnline.get(); } /** * @return The number of times the peer has been successfully checked */ public int getSuccessfullyChecked() { return successfullyChecked.get(); } /** * Increases the failed counter. * * @return The number of failed checks. */ public int failed() { return failed.incrementAndGet(); } /** * @return The time of creating this peer (statistic) */ public long getCreated() { return created; } /** * @return The time that this peer is online */ public int onlineTime() { return (int) (lastSeenOnline.get() - created); } /** * @return the peer address associated with this peer address */ public PeerAddress getPeerAddress() { return peerAddress; } /** * Set the peer address only if the previous peer address that had the same peer ID. * * @param peerAddress * The updated peer ID * @return The old peer address */ public PeerAddress setPeerAddress(final PeerAddress peerAddress) { if (!this.peerAddress.getPeerId().equals(peerAddress.getPeerId())) { throw new IllegalArgumentException("can only update the same peer address"); } PeerAddress previousPeerAddress = this.peerAddress; this.peerAddress = peerAddress; return previousPeerAddress; } } <file_sep>package net.tomp2p.peers; import net.tomp2p.storage.StorageMemoryReplication; import org.junit.Assert; import org.junit.Test; public class TestStorageMemoryReplication { @Test public void testStorageMemoryReplication1() { StorageMemoryReplication storageMemoryReplication = new StorageMemoryReplication(); Number160 testLoc = Number160.createHash("test1"); Number160 testPer = Number160.createHash("test2"); storageMemoryReplication.updateResponsibilities(testLoc, testPer); Assert.assertEquals(testPer, storageMemoryReplication.findPeerIDForResponsibleContent(testLoc)); } @Test public void testStorageMemoryReplication2() { StorageMemoryReplication storageMemoryReplication = new StorageMemoryReplication(); Number160 testLoc = Number160.createHash("test1"); Number160 testPer = Number160.createHash("test2"); storageMemoryReplication.updateResponsibilities(testLoc, testPer); Assert.assertEquals(testLoc, storageMemoryReplication.findContentForResponsiblePeerID(testPer).iterator() .next()); } @Test public void testStorageMemoryReplication3() { StorageMemoryReplication storageMemoryReplication = new StorageMemoryReplication(); Number160 testLoc = Number160.createHash("test1"); Number160 testPer = Number160.createHash("test2"); storageMemoryReplication.updateResponsibilities(testLoc, testPer); storageMemoryReplication.updateResponsibilities(testLoc, testPer); Assert.assertEquals(testPer, storageMemoryReplication.findPeerIDForResponsibleContent(testLoc)); Assert.assertEquals(testLoc, storageMemoryReplication.findContentForResponsiblePeerID(testPer).iterator() .next()); } @Test public void testStorageMemoryReplication4() { StorageMemoryReplication storageMemoryReplication = new StorageMemoryReplication(); Number160 testLoc = Number160.createHash("test1"); Number160 testPer = Number160.createHash("test2"); storageMemoryReplication.updateResponsibilities(testLoc, testPer); storageMemoryReplication.updateResponsibilities(testLoc, testPer); storageMemoryReplication.removeResponsibility(testLoc); Assert.assertEquals(null, storageMemoryReplication.findPeerIDForResponsibleContent(testLoc)); Assert.assertEquals(0, storageMemoryReplication.findContentForResponsiblePeerID(testPer).size()); } } <file_sep>package net.tomp2p.relay; import java.util.Collection; import java.util.Map; import java.util.Random; import net.tomp2p.Utils2; import net.tomp2p.connection.PeerConnection; import net.tomp2p.futures.BaseFuture; import net.tomp2p.futures.FutureBootstrap; import net.tomp2p.futures.FutureChannelCreator; import net.tomp2p.futures.FutureDirect; import net.tomp2p.futures.FutureDone; import net.tomp2p.futures.FuturePeerConnection; import net.tomp2p.futures.FuturePut; import net.tomp2p.nat.FutureRelayNAT; import net.tomp2p.nat.PeerNAT; import net.tomp2p.p2p.Peer; import net.tomp2p.p2p.PeerMaker; import net.tomp2p.p2p.Shutdown; import net.tomp2p.peers.Number160; import net.tomp2p.peers.Number640; import net.tomp2p.peers.PeerAddress; import net.tomp2p.peers.PeerMap; import net.tomp2p.peers.PeerMapConfiguration; import net.tomp2p.rpc.DispatchHandler; import net.tomp2p.rpc.ObjectDataReply; import net.tomp2p.storage.Data; import org.junit.Assert; import org.junit.Test; public class TestRelay { @Test public void testSetupRelayPeers() throws Exception { final Random rnd = new Random(42); final int nrOfNodes = 200; Peer master = null; Peer unreachablePeer = null; try { // setup test peers Peer[] peers = Utils2.createNodes(nrOfNodes, rnd, 4001); master = peers[0]; Utils2.perfectRouting(peers); for (Peer peer : peers) { new PeerNAT(peer); } // Test setting up relay peers unreachablePeer = new PeerMaker(Number160.createHash(rnd.nextInt())).ports(5000).makeAndListen(); PeerAddress pa = unreachablePeer.getPeerBean().serverPeerAddress(); pa = pa.changeFirewalledTCP(true).changeFirewalledUDP(true); unreachablePeer.getPeerBean().serverPeerAddress(pa); // find neighbors FutureBootstrap futureBootstrap = unreachablePeer.bootstrap().setPeerAddress(peers[0].getPeerAddress()).start(); futureBootstrap.awaitUninterruptibly(); Assert.assertTrue(futureBootstrap.isSuccess()); //setup relay PeerNAT uNat = new PeerNAT(unreachablePeer); FutureRelay fr = uNat.startSetupRelay(); fr.awaitUninterruptibly(); Assert.assertTrue(fr.isSuccess()); Assert.assertEquals(2, fr.relays().size()); // Check if flags are set correctly Assert.assertTrue(unreachablePeer.getPeerAddress().isRelayed()); Assert.assertFalse(unreachablePeer.getPeerAddress().isFirewalledTCP()); Assert.assertFalse(unreachablePeer.getPeerAddress().isFirewalledUDP()); } finally { if (master != null) { unreachablePeer.shutdown().await(); master.shutdown().await(); } } } @Test public void testBoostrap() throws Exception { final Random rnd = new Random(42); final int nrOfNodes = 10; Peer master = null; Peer unreachablePeer = null; try { // setup test peers Peer[] peers = Utils2.createNodes(nrOfNodes, rnd, 4001); master = peers[0]; Utils2.perfectRouting(peers); for(Peer peer:peers) { new PeerNAT(peer); } // Test setting up relay peers unreachablePeer = new PeerMaker(Number160.createHash(rnd.nextInt())).ports(5000).makeAndListen(); PeerAddress upa = unreachablePeer.getPeerBean().serverPeerAddress(); upa = upa.changeFirewalledTCP(true).changeFirewalledUDP(true); unreachablePeer.getPeerBean().serverPeerAddress(upa); // find neighbors FutureBootstrap futureBootstrap = unreachablePeer.bootstrap().setPeerAddress(peers[0].getPeerAddress()).start(); futureBootstrap.awaitUninterruptibly(); Assert.assertTrue(futureBootstrap.isSuccess()); //setup relay PeerNAT uNat = new PeerNAT(unreachablePeer); FutureRelay fr = uNat.startSetupRelay(); fr.awaitUninterruptibly(); // find neighbors again futureBootstrap = unreachablePeer.bootstrap().setPeerAddress(peers[0].getPeerAddress()).start(); futureBootstrap.awaitUninterruptibly(); Assert.assertTrue(futureBootstrap.isSuccess()); boolean otherPeersHaveRelay = false; for(Peer peer:peers) { if(peer.getPeerBean().peerMap().getAllOverflow().contains(unreachablePeer.getPeerAddress())) { for(PeerAddress pa: peer.getPeerBean().peerMap().getAllOverflow()) { if(pa.getPeerId().equals(unreachablePeer.getPeerID())) { if(pa.getPeerSocketAddresses().size() > 0) { otherPeersHaveRelay = true; } System.err.println("-->"+pa.getPeerSocketAddresses()); System.err.println("relay="+pa.isRelayed()); } } System.err.println("check 1! "+peer.getPeerAddress()); } } Assert.assertTrue(otherPeersHaveRelay); //wait for maintenance Thread.sleep(3000); boolean otherPeersMe = false; for(Peer peer:peers) { if(peer.getPeerBean().peerMap().getAll().contains(unreachablePeer.getPeerAddress())) { System.err.println("check 2! "+peer.getPeerAddress()); otherPeersMe = true; } } Assert.assertTrue(otherPeersMe); } finally { if (master != null) { unreachablePeer.shutdown().await(); master.shutdown().await(); } } } @Test public void testRelaySendDirect() throws Exception { final Random rnd = new Random(42); final int nrOfNodes = 100; Peer master = null; Peer unreachablePeer = null; try { // setup test peers Peer[] peers = Utils2.createNodes(nrOfNodes, rnd, 4001); master = peers[0]; Utils2.perfectRouting(peers); for(Peer peer:peers) { new PeerNAT(peer); } // Test setting up relay peers unreachablePeer = new PeerMaker(Number160.createHash(rnd.nextInt())).ports(13337).makeAndListen(); PeerAddress upa = unreachablePeer.getPeerBean().serverPeerAddress(); upa = upa.changeFirewalledTCP(true).changeFirewalledUDP(true); unreachablePeer.getPeerBean().serverPeerAddress(upa); // find neighbors FutureBootstrap futureBootstrap = unreachablePeer.bootstrap().setPeerAddress(peers[0].getPeerAddress()).start(); futureBootstrap.awaitUninterruptibly(); Assert.assertTrue(futureBootstrap.isSuccess()); //setup relay PeerNAT uNat = new PeerNAT(unreachablePeer); FutureRelay fr = uNat.startSetupRelay(); fr.awaitUninterruptibly(); // find neighbors again futureBootstrap = unreachablePeer.bootstrap().setPeerAddress(peers[0].getPeerAddress()).start(); futureBootstrap.awaitUninterruptibly(); Assert.assertTrue(futureBootstrap.isSuccess()); System.out.print("Send direct message to unreachable peer"); final String request = "Hello "; final String response = "World!"; unreachablePeer.setObjectDataReply(new ObjectDataReply() { public Object reply(PeerAddress sender, Object request) throws Exception { Assert.assertEquals(request.toString(), request); return response; } }); FutureDirect fd = peers[42].sendDirect(unreachablePeer.getPeerAddress()).setObject(request).start().awaitUninterruptibly(); Assert.assertEquals(response, fd.object()); //make sure we did not receive it from the unreachable peer with port 13337 Assert.assertEquals(fd.wrappedFuture().getResponse().getSender().tcpPort(), 4001); } finally { if (unreachablePeer != null) { unreachablePeer.shutdown().await(); } if (master != null) { master.shutdown().await(); } } } @Test public void testRelaySendDirect2() throws Exception { final Random rnd = new Random(42); final int nrOfNodes = 100; Peer master = null; Peer unreachablePeer = null; try { // setup test peers Peer[] peers = Utils2.createNodes(nrOfNodes, rnd, 4001); master = peers[0]; Utils2.perfectRouting(peers); for(Peer peer:peers) { new PeerNAT(peer); } // Test setting up relay peers unreachablePeer = new PeerMaker(Number160.createHash(rnd.nextInt())).ports(13337).makeAndListen(); PeerNAT uNat = new PeerNAT(unreachablePeer); uNat.bootstrapBuilder(unreachablePeer.bootstrap().setPeerAddress(master.getPeerAddress())); FutureRelayNAT fbn = uNat.startRelay(); fbn.awaitUninterruptibly(); Assert.assertTrue(fbn.isSuccess()); System.out.print("Send direct message to unreachable peer"); final String request = "Hello "; final String response = "World!"; unreachablePeer.setObjectDataReply(new ObjectDataReply() { public Object reply(PeerAddress sender, Object request) throws Exception { Assert.assertEquals(request.toString(), request); return response; } }); FutureDirect fd = peers[42].sendDirect(unreachablePeer.getPeerAddress()).setObject(request).start().awaitUninterruptibly(); //fd.awaitUninterruptibly(); Assert.assertEquals(response, fd.object()); //make sure we did not receive it from the unreachable peer with port 13337 //System.err.println(fd.getWrappedFuture()); Assert.assertEquals(fd.wrappedFuture().getResponse().getSender().tcpPort(), 4001); } finally { if (unreachablePeer != null) { unreachablePeer.shutdown().await(); } if (master != null) { master.shutdown().await(); } } } @Test public void testRelayRouting() throws Exception { final Random rnd = new Random(42); final int nrOfNodes = 8; //test only works if total nr of nodes is < 8 Peer master = null; Peer unreachablePeer = null; try { // setup test peers Peer[] peers = Utils2.createNodes(nrOfNodes, rnd, 4001); master = peers[0]; Utils2.perfectRouting(peers); for(Peer peer:peers) { new PeerNAT(peer); } // Test setting up relay peers unreachablePeer = new PeerMaker(Number160.createHash(rnd.nextInt())).ports(13337).makeAndListen(); PeerAddress upa = unreachablePeer.getPeerBean().serverPeerAddress(); upa = upa.changeFirewalledTCP(true).changeFirewalledUDP(true); unreachablePeer.getPeerBean().serverPeerAddress(upa); // find neighbors FutureBootstrap futureBootstrap = unreachablePeer.bootstrap().setPeerAddress(peers[0].getPeerAddress()).start(); futureBootstrap.awaitUninterruptibly(); Assert.assertTrue(futureBootstrap.isSuccess()); //setup relay PeerNAT uNat = new PeerNAT(unreachablePeer); FutureRelay fr = uNat.startSetupRelay(); fr.awaitUninterruptibly(); // find neighbors again futureBootstrap = unreachablePeer.bootstrap().setPeerAddress(peers[0].getPeerAddress()).start(); futureBootstrap.awaitUninterruptibly(); Assert.assertTrue(futureBootstrap.isSuccess()); // uNat.bootstrapBuilder(unreachablePeer.bootstrap().setPeerAddress(peers[0].getPeerAddress())); Shutdown shutdown = uNat.startRelayMaintenance(fr); PeerAddress relayPeer = fr.distributedRelay().relayAddresses().iterator().next().remotePeer(); Peer found = null; for(Peer p:peers) { if(p.getPeerAddress().equals(relayPeer)) { found = p; break; } } Thread.sleep(3000); int nrOfNeighbors = getNeighbors(found).size(); //we have in total 9 peers, we should find 8 as neighbors Assert.assertEquals(8, nrOfNeighbors); System.err.println("neighbors: "+nrOfNeighbors); for(PeerConnection pc:fr.distributedRelay().relayAddresses()) { System.err.println("pc:"+pc.remotePeer()); } Assert.assertEquals(5, fr.distributedRelay().relayAddresses().size()); //Shut down a peer Thread.sleep(3000); peers[nrOfNodes - 1].shutdown().await(); peers[nrOfNodes - 2].shutdown().await(); peers[nrOfNodes - 3].shutdown().await(); /* * needed because failure of a node is detected with periodic * heartbeat and the routing table of the relay peers are also * updated periodically */ Thread.sleep(15000); Assert.assertEquals(nrOfNeighbors - 3, getNeighbors(found).size()); Assert.assertEquals(5, fr.distributedRelay().relayAddresses().size()); shutdown.shutdown(); } finally { if (unreachablePeer != null) { unreachablePeer.shutdown().await(); } if (master != null) { master.shutdown().await(); } } } @Test public void testRelayRPC() throws Exception { Peer master = null; Peer slave = null; try { final Random rnd = new Random(42); Peer[] peers = Utils2.createNodes(2, rnd, 4000); master = peers[0]; // the relay peer new PeerNAT(master); // register relayRPC ioHandler slave = peers[1]; // create channel creator FutureChannelCreator fcc = slave.getConnectionBean().reservation().create(1, PeerAddress.MAX_RELAYS); fcc.awaitUninterruptibly(); final FuturePeerConnection fpc = slave.createPeerConnection(master.getPeerAddress()); FutureDone<PeerConnection> rcf = new PeerNAT(slave).relayRPC().setupRelay(fcc.getChannelCreator(), fpc); rcf.awaitUninterruptibly(); //Check if permanent peer connection was created Assert.assertTrue(rcf.isSuccess()); Assert.assertEquals(master.getPeerAddress(), fpc.getObject().remotePeer()); Assert.assertTrue(fpc.getObject().channelFuture().channel().isActive()); Assert.assertTrue(fpc.getObject().channelFuture().channel().isOpen()); } finally { master.shutdown().await(); slave.shutdown().await(); } } public BaseFuture publishNeighbors() { return null; } @Test public void testNoRelayDHT() throws Exception { final Random rnd = new Random(42); Peer master = null; Peer slave = null; try { Peer[] peers = Utils2.createNodes(10, rnd, 4000); master = peers[0]; // the relay peer Utils2.perfectRouting(peers); for(Peer peer:peers) { new PeerNAT(peer); } PeerMapConfiguration pmc = new PeerMapConfiguration(Number160.createHash(rnd.nextInt())); slave = new PeerMaker(Number160.ONE).peerMap(new PeerMap(pmc)).ports(13337).makeAndListen(); printMapStatus(slave, peers); FuturePut futurePut = peers[8].put(slave.getPeerID()).setData(new Data("hello")).start().awaitUninterruptibly(); futurePut.getFutureRequests().awaitUninterruptibly(); Assert.assertTrue(futurePut.isSuccess()); Assert.assertFalse(slave.getPeerBean().storage().contains( new Number640(slave.getPeerID(), Number160.ZERO, Number160.ZERO, Number160.ZERO))); System.err.println("DONE!"); } finally { master.shutdown().await(); slave.shutdown().await(); } } private void printMapStatus(Peer slave, Peer[] peers) { for(Peer peer:peers) { if(peer.getPeerBean().peerMap().getAllOverflow().contains(slave.getPeerAddress())) { System.err.println("found relayed peer in overflow bag " + peer.getPeerAddress()); } } for(Peer peer:peers) { if(peer.getPeerBean().peerMap().getAll().contains(slave.getPeerAddress())) { System.err.println("found relayed peer in regular bag" + peer.getPeerAddress()); } } } @Test public void testRelayDHT() throws Exception { final Random rnd = new Random(42); Peer master = null; Peer unreachablePeer = null; try { Peer[] peers = Utils2.createNodes(10, rnd, 4000); master = peers[0]; // the relay peer Utils2.perfectRouting(peers); for(Peer peer:peers) { new PeerNAT(peer); } // Test setting up relay peers unreachablePeer = new PeerMaker(Number160.createHash(rnd.nextInt())).ports(13337).makeAndListen(); PeerNAT uNat = new PeerNAT(unreachablePeer); uNat.bootstrapBuilder(unreachablePeer.bootstrap().setPeerAddress(master.getPeerAddress())); FutureRelayNAT fbn = uNat.startRelay(); fbn.awaitUninterruptibly(); Assert.assertTrue(fbn.isSuccess()); // PeerMapConfiguration pmc = new PeerMapConfiguration(Number160.createHash(rnd.nextInt())); // slave = new PeerMaker(Number160.ONE).peerMap(new PeerMap(pmc)).ports(13337).makeAndListen(); // FutureRelay rf = new RelayConf(slave).bootstrapAddress(master.getPeerAddress()).start().awaitUninterruptibly(); // Assert.assertTrue(rf.isSuccess()); // RelayManager manager = rf.relayManager(); // System.err.println("relays: "+manager.getRelayAddresses()); // System.err.println("psa: "+ slave.getPeerAddress().getPeerSocketAddresses()); //wait for maintenance to kick in Thread.sleep(4000); printMapStatus(unreachablePeer, peers); FuturePut futurePut = peers[8].put(unreachablePeer.getPeerID()).setData(new Data("hello")).start().awaitUninterruptibly(); //the relayed one is the slowest, so we need to wait for it! futurePut.getFutureRequests().awaitUninterruptibly(); Assert.assertTrue(futurePut.isSuccess()); //we cannot see the peer in futurePut.rawResult, as the relayed is the slowest and we finish earlier than that. Assert.assertTrue(unreachablePeer.getPeerBean().storage().contains(new Number640(unreachablePeer.getPeerID(), Number160.ZERO, Number160.ZERO, Number160.ZERO))); System.err.println("DONE!"); } finally { master.shutdown().await(); unreachablePeer.shutdown().await(); } } @Test public void testVeryFewPeers() throws Exception { final Random rnd = new Random(42); Peer master = null; Peer unreachablePeer = null; try { Peer[] peers = Utils2.createNodes(3, rnd, 4000); master = peers[0]; // the relay peer Utils2.perfectRouting(peers); for (Peer peer : peers) { new PeerNAT(peer); } // Test setting up relay peers unreachablePeer = new PeerMaker(Number160.createHash(rnd.nextInt())).ports(13337).makeAndListen(); PeerNAT uNat = new PeerNAT(unreachablePeer); uNat.bootstrapBuilder(unreachablePeer.bootstrap().setPeerAddress(master.getPeerAddress())); FutureRelayNAT fbn = uNat.startRelay(); fbn.awaitUninterruptibly(); Assert.assertTrue(fbn.isSuccess()); } finally { master.shutdown().await(); unreachablePeer.shutdown().await(); } } private Collection<PeerAddress> getNeighbors(Peer peer) { Map<Number160, DispatchHandler> handlers = peer.getConnectionBean().dispatcher().searchHandler(5); for(Map.Entry<Number160, DispatchHandler> entry:handlers.entrySet()) { if(entry.getValue() instanceof RelayForwarderRPC) { return ((RelayForwarderRPC)entry.getValue()).getAll(); } } return null; } } <file_sep>/* * Copyright 2013 <NAME>, <NAME> * * 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 net.tomp2p.synchronization; import java.util.Map; import net.tomp2p.futures.FutureDone; import net.tomp2p.message.DataMap; import net.tomp2p.p2p.Peer; import net.tomp2p.p2p.PeerInit; import net.tomp2p.p2p.ReplicationSender; import net.tomp2p.peers.Number160; import net.tomp2p.peers.Number640; import net.tomp2p.peers.PeerAddress; import net.tomp2p.storage.Data; public class ReplicationSync implements ReplicationSender, PeerInit { private final int blockSize; private PeerSync peerSync; private Peer peer; public ReplicationSync() { this.blockSize = SyncBuilder.DEFAULT_BLOCK_SIZE; } public ReplicationSync(final int blockSize) { this.blockSize = blockSize; } @Override public void init(Peer peer) { this.peerSync = new PeerSync(peer, blockSize); this.peer = peer; } @Override public void sendDirect(PeerAddress other, Number160 locationKey, Map<Number640, Data> dataMap) { FutureDone<SyncStat> future = peerSync.synchronize(other) .dataMap(new DataMap(dataMap)).start(); peer.notifyAutomaticFutures(future); } public PeerSync peerSync() { return peerSync; } } <file_sep>/* * Copyright 2009 <NAME> * * 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 net.tomp2p.message; import java.util.Iterator; import java.util.Map; import net.tomp2p.peers.Number160; import net.tomp2p.peers.PeerAddress; import net.tomp2p.storage.Data; public class TrackerData { public final static Data EMTPY_DATA = new Data(0, 0); private final Map<PeerAddress, Data> peerAddresses; final private PeerAddress referrer; final private boolean couldProvideMoreData; public TrackerData(Map<PeerAddress, Data> peerAddresses, PeerAddress referrer) { this(peerAddresses, referrer, false); } public TrackerData(Map<PeerAddress, Data> peerAddresses, PeerAddress referrer, boolean couldProvideMoreData) { this.peerAddresses = peerAddresses; this.referrer = referrer; this.couldProvideMoreData = couldProvideMoreData; } public Map<PeerAddress, Data> getPeerAddresses() { return peerAddresses; } public PeerAddress getReferrer() { return referrer; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("p:").append(peerAddresses).append(",l:"); return sb.toString(); } public boolean couldProvideMoreData() { return couldProvideMoreData; } public int size() { return peerAddresses.size(); } public Map<PeerAddress, Data> map() { return peerAddresses; } public void put(PeerAddress remotePeer, Data attachement) { peerAddresses.put(remotePeer, attachement == null ? EMTPY_DATA : attachement); } public Map.Entry<PeerAddress, Data> remove(Number160 remotePeerId) { for (Iterator<Map.Entry<PeerAddress, Data>> iterator = peerAddresses.entrySet().iterator(); iterator .hasNext();) { Map.Entry<PeerAddress, Data> entry = iterator.next(); if (entry.getKey().getPeerId().equals(remotePeerId)) { iterator.remove(); return entry; } } return null; } public boolean containsKey(Number160 tmpKey) { for (Iterator<Map.Entry<PeerAddress, Data>> iterator = peerAddresses.entrySet().iterator(); iterator .hasNext();) { Map.Entry<PeerAddress, Data> entry = iterator.next(); if (entry.getKey().getPeerId().equals(tmpKey)) { return true; } } return false; } } <file_sep>/* * Copyright 2009 <NAME> * * 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 net.tomp2p.rpc; import io.netty.channel.ChannelHandlerContext; import java.io.IOException; import java.security.PublicKey; import java.util.HashMap; import java.util.Map; import net.tomp2p.connection.ChannelCreator; import net.tomp2p.connection.ConnectionBean; import net.tomp2p.connection.ConnectionConfiguration; import net.tomp2p.connection.PeerBean; import net.tomp2p.connection.PeerConnection; import net.tomp2p.connection.RequestHandler; import net.tomp2p.connection.Responder; import net.tomp2p.futures.FutureResponse; import net.tomp2p.message.Message; import net.tomp2p.message.Message.Type; import net.tomp2p.message.TrackerData; import net.tomp2p.p2p.builder.AddTrackerBuilder; import net.tomp2p.p2p.builder.GetTrackerBuilder; import net.tomp2p.peers.Number160; import net.tomp2p.peers.PeerAddress; import net.tomp2p.storage.Data; import net.tomp2p.storage.TrackerStorage; import net.tomp2p.storage.TrackerStorage.ReferrerType; import net.tomp2p.utils.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TrackerRPC extends DispatchHandler { private static final Logger LOG = LoggerFactory.getLogger(TrackerRPC.class); public static final int MAX_MSG_SIZE_UDP = 35; // final private ConnectionConfiguration p2pConfiguration; /** * @param peerBean * @param connectionBean */ public TrackerRPC(final PeerBean peerBean, final ConnectionBean connectionBean) { super(peerBean, connectionBean); register(RPC.Commands.TRACKER_ADD.getNr(), RPC.Commands.TRACKER_GET.getNr()); } public static boolean isPrimary(FutureResponse response) { return response.getRequest().getType() == Type.REQUEST_3; } public static boolean isSecondary(FutureResponse response) { return response.getRequest().getType() == Type.REQUEST_1; } public FutureResponse addToTracker(final PeerAddress remotePeer, AddTrackerBuilder builder, ChannelCreator channelCreator) { Utils.nullCheck(remotePeer, builder.getLocationKey(), builder.getDomainKey()); final Message message = createMessage(remotePeer, RPC.Commands.TRACKER_ADD.getNr(), builder.isPrimary() ? Type.REQUEST_3 : Type.REQUEST_1); if (builder.isSign()) { message.setPublicKeyAndSign(builder.keyPair()); } message.setKey(builder.getLocationKey()); message.setKey(builder.getDomainKey()); if (builder.getBloomFilter() != null) { message.setBloomFilter(builder.getBloomFilter()); } final FutureResponse futureResponse = new FutureResponse(message); final TrackerRequest<FutureResponse> requestHandler = new TrackerRequest<FutureResponse>( futureResponse, peerBean(), connectionBean(), message, builder.getLocationKey(), builder.getDomainKey(), builder); TrackerData trackerData = new TrackerData(new HashMap<PeerAddress, Data>(), null); PeerAddress peerAddressToAnnounce = builder.peerAddressToAnnounce(); if(peerAddressToAnnounce == null) { peerAddressToAnnounce = peerBean().serverPeerAddress(); } trackerData.put(peerAddressToAnnounce, builder.getAttachement()); message.setTrackerData(trackerData); if (builder.isForceTCP()) { return requestHandler.sendTCP(channelCreator); } else { return requestHandler.sendUDP(channelCreator); } } public FutureResponse getFromTracker(final PeerAddress remotePeer, GetTrackerBuilder builder, ChannelCreator channelCreator) { //final Number160 locationKey, //final Number160 domainKey, boolean expectAttachement, boolean signMessage, //Set<Number160> knownPeers, Utils.nullCheck(remotePeer, builder.getLocationKey(), builder.getDomainKey()); final Message message = createMessage(remotePeer, RPC.Commands.TRACKER_GET.getNr(), Type.REQUEST_1); if (builder.isSign()) { message.setPublicKeyAndSign(builder.keyPair()); } message.setKey(builder.getLocationKey()); message.setKey(builder.getDomainKey()); //TODO: make this always a bloom filter if (builder.getKnownPeers() != null && (builder.getKnownPeers() instanceof SimpleBloomFilter)) { message.setBloomFilter((SimpleBloomFilter<Number160>) builder.getKnownPeers()); } FutureResponse futureResponse = new FutureResponse(message); final TrackerRequest<FutureResponse> requestHandler = new TrackerRequest<FutureResponse>( futureResponse, peerBean(), connectionBean(), message, builder.getLocationKey(), builder.getDomainKey(), builder); if ((builder.isExpectAttachement() || builder.isForceTCP())) { return requestHandler.sendTCP(channelCreator); } else { return requestHandler.sendUDP(channelCreator); } } @Override public void handleResponse(Message message, PeerConnection peerConnection, boolean sign, Responder responder) throws Exception { if (!((message.getType() == Type.REQUEST_1 || message.getType() == Type.REQUEST_3) && message.getKey(0) != null && message.getKey(1) != null)) { throw new IllegalArgumentException("Message content is wrong"); } final Message responseMessage = createResponseMessage(message, Type.OK); // get data Number160 locationKey = message.getKey(0); Number160 domainKey = message.getKey(1); SimpleBloomFilter<Number160> knownPeers = message.getBloomFilter(0); PublicKey publicKey = message.getPublicKey(0); // final TrackerStorage trackerStorage = peerBean().trackerStorage(); TrackerData meshPeers = trackerStorage.meshPeers(locationKey, domainKey); boolean couldProvideMoreData = false; if (meshPeers != null) { if (knownPeers != null) { meshPeers = Utils.disjunction(meshPeers, knownPeers); } int size = meshPeers.size(); meshPeers = Utils.limit(meshPeers, TrackerRPC.MAX_MSG_SIZE_UDP); couldProvideMoreData = size > meshPeers.size(); responseMessage.setTrackerData(meshPeers); } if (couldProvideMoreData) { responseMessage.setType(Message.Type.PARTIALLY_OK); } if (message.getCommand() == RPC.Commands.TRACKER_ADD.getNr()) { TrackerData trackerData = message.getTrackerData(0); if (trackerData.size() != 1) { responseMessage.setType(Message.Type.EXCEPTION); } else { Map.Entry<PeerAddress, Data> entry = trackerData.getPeerAddresses().entrySet().iterator() .next(); if (!trackerStorage.put(locationKey, domainKey, entry.getKey(), publicKey, entry.getValue())) { responseMessage.setType(Message.Type.DENIED); LOG.debug("tracker NOT put on({}) locationKey:{}, domainKey:{}, address:{}", peerBean() .serverPeerAddress(), locationKey, domainKey, entry.getKey()); } else { LOG.debug("tracker put on({}) locationKey:{}, domainKey:{}, address: {} sizeP: {}", peerBean().serverPeerAddress(), locationKey, domainKey, entry.getKey(), trackerStorage.sizePrimary(locationKey, domainKey)); } } } else { LOG.debug("tracker get on({}) locationKey:{}, domainKey:{}, address:{}, returning: {}", peerBean().serverPeerAddress(), locationKey, domainKey, message.getSender(), (meshPeers == null ? "0" : meshPeers.size())); } if (sign) { responseMessage.setPublicKeyAndSign(peerBean().getKeyPair()); } responder.response(responseMessage); } private class TrackerRequest<K> extends RequestHandler<FutureResponse> { private final Message message; private final Number160 locationKey; private final Number160 domainKey; public TrackerRequest(FutureResponse futureResponse, PeerBean peerBean, ConnectionBean connectionBean, Message message, Number160 locationKey, Number160 domainKey, ConnectionConfiguration configuration) { super(futureResponse, peerBean, connectionBean, configuration); this.message = message; this.locationKey = locationKey; this.domainKey = domainKey; } protected void channelRead0(final ChannelHandlerContext ctx, final Message responseMessage) throws Exception { preHandleMessage(responseMessage, peerBean().trackerStorage(), this.message.getRecipient(), locationKey, domainKey); super.channelRead0(ctx, responseMessage); } } private void preHandleMessage(Message message, TrackerStorage trackerStorage, PeerAddress referrer, Number160 locationKey, Number160 domainKey) throws IOException, ClassNotFoundException { // Since I might become a tracker as well, we keep this information // about those trackers. TrackerData tmp = message.getTrackerData(0); // no data found if (tmp == null || tmp.size() == 0) { return; } for (Map.Entry<PeerAddress, Data> trackerData : tmp.getPeerAddresses().entrySet()) { // we don't know the public key, since this is not first hand // information. // TTL will be set in tracker storage, so don't worry about it here. trackerStorage.putReferred(locationKey, domainKey, trackerData.getKey(), referrer, trackerData.getValue(), ReferrerType.MESH); } } } <file_sep>package net.tomp2p.rpc; import net.tomp2p.connection.ChannelCreator; import net.tomp2p.connection.DefaultConnectionConfiguration; import net.tomp2p.futures.FutureChannelCreator; import net.tomp2p.futures.FutureResponse; import net.tomp2p.p2p.Peer; import net.tomp2p.p2p.PeerMaker; import net.tomp2p.peers.Number160; import org.junit.Assert; import org.junit.Test; public class TestReservation { /* * @Test public void testReservationTCPL() throws Exception { for(int i=0;i<100;i++) testReservationTCP(); } */ @Test public void testReservationTCP() throws Exception { Peer sender = null; Peer recv1 = null; ChannelCreator cc = null; try { sender = new PeerMaker(new Number160("0x9876")).p2pId(55).ports(2424).makeAndListen(); recv1 = new PeerMaker(new Number160("0x1234")).p2pId(55).ports(8088).makeAndListen(); FutureChannelCreator fcc = recv1.getConnectionBean().reservation().create(0, 3); fcc.awaitUninterruptibly(); cc = fcc.getChannelCreator(); for (int i = 0; i < 1000; i++) { FutureResponse fr1 = sender.pingRPC().pingTCP(recv1.getPeerAddress(), cc, new DefaultConnectionConfiguration()); FutureResponse fr2 = sender.pingRPC().pingTCP(recv1.getPeerAddress(), cc, new DefaultConnectionConfiguration()); FutureResponse fr3 = sender.pingRPC().pingTCP(recv1.getPeerAddress(), cc, new DefaultConnectionConfiguration()); fr1.awaitUninterruptibly(); fr2.awaitUninterruptibly(); fr3.awaitUninterruptibly(); System.err.println(fr1.getFailedReason() + " / " + fr2.getFailedReason() + " / " + fr3.getFailedReason()); Assert.assertEquals(true, fr1.isSuccess()); Assert.assertEquals(true, fr2.isSuccess()); Assert.assertEquals(true, fr3.isSuccess()); } } catch (Throwable t) { t.printStackTrace(); } finally { if (cc != null) { cc.shutdown().await(); } if (sender != null) { sender.shutdown().await(); } if (recv1 != null) { recv1.shutdown().await(); } } } /* * @Test public void testReservationUDPL() throws Exception { for(int i=0;i<100;i++) testReservationUDP(); } */ @Test public void testReservationUDP() throws Exception { Peer sender = null; Peer recv1 = null; ChannelCreator cc = null; try { sender = new PeerMaker(new Number160("0x9876")).p2pId(55).ports(2424).makeAndListen(); recv1 = new PeerMaker(new Number160("0x1234")).p2pId(55).ports(8088).makeAndListen(); FutureChannelCreator fcc = recv1.getConnectionBean().reservation().create(3, 0); fcc.awaitUninterruptibly(); cc = fcc.getChannelCreator(); for (int i = 0; i < 1000; i++) { FutureResponse fr1 = sender.pingRPC().pingUDP(recv1.getPeerAddress(), cc, new DefaultConnectionConfiguration()); FutureResponse fr2 = sender.pingRPC().pingUDP(recv1.getPeerAddress(), cc, new DefaultConnectionConfiguration()); FutureResponse fr3 = sender.pingRPC().pingUDP(recv1.getPeerAddress(), cc, new DefaultConnectionConfiguration()); fr1.awaitUninterruptibly(); fr2.awaitUninterruptibly(); fr3.awaitUninterruptibly(); System.err.println(fr1.getFailedReason() + " / " + fr2.getFailedReason() + " / " + fr3.getFailedReason()); Assert.assertEquals(true, fr1.isSuccess()); Assert.assertEquals(true, fr2.isSuccess()); Assert.assertEquals(true, fr3.isSuccess()); } } catch (Throwable t) { t.printStackTrace(); } finally { if (cc != null) { cc.shutdown().await(); } if (sender != null) { sender.shutdown().await(); } if (recv1 != null) { recv1.shutdown().await(); } } } }
4506ec6b147a3062426f8751aa1163b7462792dd
[ "Java" ]
21
Java
narayana1208/TomP2P
2d093001e810763e24ececb6091d5ad0db04c75a
6bc3675fb7680947a64d17adbe30b627c0ba78bb
refs/heads/master
<file_sep>var moment = require("moment-timezone"); /* * date parser ---------------------------------------------- */ export function parse_dtLog (d) { // var m_date = moment(d, "YYYY-MM-DD-HH:mm:ss"); var m_date = moment(d); var RomeDate = moment.tz(m_date, "Europe/Rome"); // console.log("RomeDate", RomeDate.format()); // var DublinDate = RomeDate.clone().tz("Europe/Dublin"); // console.log("DublinDate", DublinDate.format()); //return moment(RomeDate, "YYYY-MM-DD-HH:mm:ss.ZZ").toISOString(); return RomeDate.format(); // return moment(d).toISOString(); } export function get_isodate(d) { return moment(d).toISOString(); } <file_sep>"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parse_dtLog = parse_dtLog; exports.get_isodate = get_isodate; var _momentTimezone = require("moment-timezone"); var momet = _interopRequireWildcard(_momentTimezone); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } var dtParser = require("./dtParser.js"); /* * date parser ---------------------------------------------- */ function parse_dtLog(d) { // var m_date = moment(d, "YYYY-MM-DD-HH:mm:ss"); var m_date = moment(d); var RomeDate = moment.tz(m_date, "Europe/Rome"); // console.log("RomeDate", RomeDate.format()); // var DublinDate = RomeDate.clone().tz("Europe/Dublin"); // console.log("DublinDate", DublinDate.format()); //return moment(RomeDate, "YYYY-MM-DD-HH:mm:ss.ZZ").toISOString(); return RomeDate; //.format(); // return moment(d).toISOString(); } function get_isodate(d) { return moment(d).toISOString(); }<file_sep>"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.list = list; require("babel-polyfill"); function list() { var m_uri = []; var Param = {}; // <NAME> Param = {}; Param.projectId = "cf51cc26-993a-4606-959f-0afe4dc97fa5"; Param.sensorId = "58dfeeda-c786-4ad0-aac6-d472debe354c"; Param.url2Call = "https://www.sentryenergyprofiler.com/esportaDatiJson/"; Param.urlUser = "voclevergy37"; Param.urlIMEI = "013949004269752"; Param.urlKeyCode = "clv2014"; Param.Descr = "<NAME>"; m_uri.push(Param); return m_uri; }<file_sep>require("babel-polyfill"); var Promise = require('bluebird'); var request = require("request"); var cnf = require("./config"); var endPointReading = cnf.endPointReading; var username = cnf.username; var password = <PASSWORD>; var auth = "Basic " + new Buffer(username + ":" + password).toString("base64"); var retVal = {"statusCode":"","body":""}; /* * IWWA request ---------------------------------------------------------*/ export async function executePost (AnzModel) { return new Promise(function (resolve, reject) { request.post({ headers : { "Authorization" : auth, "Content-Type" : "application/json" }, uri: endPointReading, json: AnzModel }, function (error, response, body) { if (!error) { retVal.statusCode=response.statusCode; retVal.body=response.body; resolve(retVal); } else { retVal.statusCode=null; retVal.body=error; resolve(retVal); } }); }); }; <file_sep>"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parse_dtLog = parse_dtLog; exports.get_isodate = get_isodate; var moment = require("moment-timezone"); /* * date parser ---------------------------------------------- */ function parse_dtLog(d) { // var m_date = moment(d, "YYYY-MM-DD-HH:mm:ss"); var m_date = moment(d); var RomeDate = moment.tz(m_date, "Europe/Rome"); // console.log("RomeDate", RomeDate.format()); // var DublinDate = RomeDate.clone().tz("Europe/Dublin"); // console.log("DublinDate", DublinDate.format()); //return moment(RomeDate, "YYYY-MM-DD-HH:mm:ss.ZZ").toISOString(); return RomeDate.format(); // return moment(d).toISOString(); } function get_isodate(d) { return moment(d).toISOString(); }<file_sep>"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.executePost = executePost; require("babel-polyfill"); var Promise = require('bluebird'); var request = require("request"); var cnf = require("./config"); var endPointReading = cnf.endPointReading; var username = cnf.username; var password = <PASSWORD>; var auth = "Basic " + new Buffer(username + ":" + password).toString("base64"); var retVal = { "statusCode": "", "body": "" }; /* * IWWA request ---------------------------------------------------------*/ function executePost(AnzModel) { return regeneratorRuntime.async(function executePost$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: return _context.abrupt("return", new Promise(function (resolve, reject) { request.post({ headers: { "Authorization": auth, "Content-Type": "application/json" }, uri: endPointReading, json: AnzModel }, function (error, response, body) { if (!error) { retVal.statusCode = response.statusCode; retVal.body = response.body; resolve(retVal); } else { retVal.statusCode = null; retVal.body = error; resolve(retVal); } }); })); case 1: case "end": return _context.stop(); } } }, null, this); };<file_sep>require("babel-polyfill"); var dtParser = require("./dtParser.js"); export function elabor (param , values) { var lastValue = values.data.length - 1; var measurements = []; var anzModel = {}; anzModel.sensorId = param.sensorId; anzModel.date = dtParser.get_isodate(values.data[lastValue].DataOra.replace(" " , "T")); var measurementsModel = {}; measurementsModel.type = "maxPower"; measurementsModel.source = "reading"; measurementsModel.value = values.data[lastValue].PotenzaAttiva; measurementsModel.unitOfMeasurement = "kW"; measurements.push(measurementsModel); measurementsModel = {}; measurementsModel.type = "activeEnergy"; measurementsModel.source = "reading"; measurementsModel.value = values.data[lastValue].EnergiaAttiva; measurementsModel.unitOfMeasurement = "kWh"; measurements.push(measurementsModel); anzModel.measurements = measurements; // console.log("anzModel" , anzModel); return anzModel; } <file_sep>"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.makerequest = makerequest; require("babel-polyfill"); var request = require("request"); var dtParser = require("./dtParser.js"); var pa = require("./prepareAnz"); var returnValue = { 'retval': false, dataObject: {}, 'message': '' }; function makerequest(param) { return regeneratorRuntime.async(function makerequest$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: return _context.abrupt("return", new Promise(function (resolve, reject) { var now = new Date(); var m_date = dtParser.parse_dtLog(now); var datetimeFrom = m_date.substring(0, 4) + "-"; datetimeFrom += m_date.substring(5, 7) + "-"; datetimeFrom += m_date.substring(8, 10); datetimeFrom += " 00:00:00"; var datetimeTo = m_date.substring(0, 4) + "-"; datetimeTo += m_date.substring(5, 7) + "-"; datetimeTo += m_date.substring(8, 10); // datetimeTo += m_date.substring(11, 19); datetimeTo += " 23:59:58"; /* var date_fromTime = new Date(); date_fromTime.setMinutes(now.getMinutes() - 15); var m_date2 = dtParser.parse_dtLog(date_fromTime); var datetimeFrom = m_date2.substring(0, 4) + "-"; datetimeFrom += m_date2.substring(5, 7) + "-"; datetimeFrom += m_date2.substring(8, 10) + " "; datetimeFrom += m_date2.substring(11, 19); */ var m_url = param.url2Call; m_url += param.urlUser + "/"; m_url += param.urlIMEI + "/"; m_url += datetimeFrom + "/"; m_url += datetimeTo + "/"; m_url += param.urlKeyCode; // console.log("m_url" , m_url); request({ uri: m_url, method: "GET", timeout: 10000, followRedirect: true, maxRedirects: 10 }, function (error, response, body) { if (!error && response.statusCode == 200) { var jsondata = JSON.parse(body); if (jsondata) { if (jsondata.Err) { returnValue.retval = false; returnValue.message = param.Descr + " " + jsondata.Err; resolve(returnValue); } else { if (jsondata.data.length > 0) { returnValue.retval = true; returnValue.dataObject = pa.elabor(param, jsondata); returnValue.message = "ok"; resolve(returnValue); } else { returnValue.retval = false; returnValue.message = param.Descr + " no data"; resolve(returnValue); } } } else { returnValue.retval = false; returnValue.message = param.Descr + " nothing received"; resolve(returnValue); } //data } else { //error returnValue.retval = false; returnValue.message = param.Descr + " " + error; resolve(returnValue); } }); })); case 1: case "end": return _context.stop(); } } }, null, this); }<file_sep>require("babel-polyfill"); import * as schedule from "node-schedule"; import * as installations from "./services/installations"; import * as mr from "./services/makerequest"; import * as ep from "./services/executePost"; var moment = require("moment"); async function main () { var m_uri = []; m_uri = await installations.list(); m_uri.forEach(function (obj) { elabor (obj); }); } async function elabor (param) { var anzModel = await mr.makerequest(param); if (anzModel.retval === true) { var response = await ep.executePost(anzModel.dataObject); console.log(moment().toISOString() , param.Descr , response.statusCode , response.body); } else { console.log(moment().toISOString() , param.Descr, anzModel.message); } } function elaborRequest () { m_uri.forEach(function (obj) { // mrae.MakeRequestActiveEnergy(obj); console.log(moment().format() + " elaborRequest" ); }); } var job2elabor = schedule.scheduleJob("*/5 * * * *", function(){ main(); }); main(); // console.log(moment().format("LT")); <file_sep>Demo for voltaide sensor.
893b10be0b77810897f36b4a45067a08054c9276
[ "Markdown", "JavaScript" ]
10
Markdown
clevergy1/demo-voltaide-readings-app
cc77a4eea725185c7df9a20d3d0e072c92fee480
059badc626cb064f790b3bef55aa34e9481f5e02
refs/heads/master
<repo_name>CalledByThe4ire/junior-course-boilerplate<file_sep>/src/components/icon/index.js import React from 'react'; import propTypes from 'prop-types'; import classnames from 'classnames'; import { renderIcon } from './utils/render-icon'; import styles from './icon.module.scss'; const Icon = props => { const { name, style: IconInlineStyles, ...restProps } = props; return ( <div className={classnames(styles.Icon)} style={IconInlineStyles}> {renderIcon({ name, ...restProps })} </div> ); }; Icon.propTypes = { name: propTypes.string }; export default Icon; <file_sep>/src/containers/products-container/index.js import ProductsContainer from './products-container'; export default ProductsContainer; <file_sep>/src/redux/modules/filter/actions.js import * as types from './types'; export const resetFilter = () => ({ type: types.RESET_FILTER }); export const updateFilterField = payload => ({ type: types.UPDATE_FILTER_FIELD, payload }); export const fillFilterWithData = payload => ({ type: types.FILL_FILTER_WITH_DATA, payload }); <file_sep>/src/components/hoc-helpers/with-input-filter-number-handler.js import React, { PureComponent } from 'react'; const withInputFilterNumberHandler = WrappedComponent => { return class extends PureComponent { addNumberMask = value => { return Number(value.replace(/\D/g, '')); }; handleChange = ({ target: { value, name: fieldName } }, groupName) => { const { updateFilterField } = this.props; const maskedValue = this.addNumberMask(value); const payload = { groupName, fieldName, fieldData: { value: maskedValue, isValid: fieldName === 'min' || fieldName === 'max' ? value > 0 : fieldName === 'total' ? value < 100 : false } }; updateFilterField(payload); }; render() { const { push, searchParams, ...restProps } = this.props; return ( <WrappedComponent handleChange={this.handleChange} {...restProps} /> ); } }; }; export default withInputFilterNumberHandler; <file_sep>/src/redux/modules/basket/index.js import basketReducer from './reducer'; import * as basketTypes from './types'; import * as basketActions from './actions'; import * as basketSelectors from './selectors'; export { basketTypes, basketActions, basketSelectors }; export default basketReducer; <file_sep>/src/containers/pagination-container/index.js import PaginationContainer from './pagination-container'; export default PaginationContainer; <file_sep>/src/index.js import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { ConnectedRouter } from 'connected-react-router'; import configureStore, { history } from './redux/store'; import AppContainer from './containers/app-container'; import WebFont from 'webfontloader'; import 'normalize.scss/normalize.scss'; import './index.scss'; const store = configureStore(); WebFont.load({ google: { families: ['Open Sans:300,600', 'sans-serif'] } }); ReactDOM.render( <Provider store={store}> <ConnectedRouter history={history}> <AppContainer /> </ConnectedRouter> </Provider>, document.getElementById('root') ); <file_sep>/src/components/input-filter-category/index.js import InputFilterCategory from './input-filter-category'; export default InputFilterCategory; <file_sep>/src/components/hoc-helpers/index.js import withInputFilterNumberHandler from './with-input-filter-number-handler'; import withApi from './with-api'; export { withApi, withInputFilterNumberHandler }; <file_sep>/src/containers/list-container/list-container.js import React, { PureComponent } from 'react'; import { connect } from 'react-redux'; import { paginationSelectors } from '../../redux/'; import List from '../../components/list'; class ListContainer extends PureComponent { render() { const { list } = this.props; return <List list={list} />; } } const mapStateToProps = state => { return { list: paginationSelectors.getVisibleProductsList(state) }; }; export default connect(mapStateToProps)(ListContainer); <file_sep>/src/redux/index.js import { combineReducers } from 'redux'; import { connectRouter as routerReducer } from 'connected-react-router'; import productsReducer from './modules/products'; import basketReducer from './modules/basket'; import filterReducer from './modules/filter'; import paginationReducer from './modules/pagination'; import { productsTypes, productsActions, productsSelectors } from './modules/products'; import { basketTypes, basketActions, basketSelectors } from './modules/basket'; import { filterTypes, filterActions, filterSelectors } from './modules/filter'; import { paginationSelectors } from './modules/pagination'; import { routerSelectors } from './modules/router'; export { productsTypes, productsActions, productsSelectors, basketTypes, basketActions, basketSelectors, filterTypes, filterActions, filterSelectors, paginationSelectors, routerSelectors }; const createRootReducer = history => combineReducers({ products: productsReducer, basket: basketReducer, filter: filterReducer, pagination: paginationReducer, router: routerReducer(history), }); export default createRootReducer; <file_sep>/src/components/products/utils/index.js import { renderList } from './render-list'; export { renderList }; <file_sep>/src/components/pagination/utils/index.js import { renderButton } from './render-button'; export { renderButton }; <file_sep>/src/containers/basket-container/index.js import BasketContainer from './basket-container'; export default BasketContainer; <file_sep>/src/components/pagination/pagination.module.scss .Pagination { display: flex; flex-flow: row nowrap; justify-content: center; &List { display: flex; justify-content: center; align-items: center; margin: 0; padding: 0; list-style: none; } &Btn { display: flex; flex-flow: row nowrap; justify-content: center; align-items: center; min-width: 34px; min-height: 32px; margin-right: 2px; font-size: 14px; line-height: 1; font-weight: 300; color: #7e8fa4; text-decoration: none; background-color: transparent; border: 1px solid #c5cfde; outline: none; transition: all 0.5s; &:hover, &Active { color: #fff; border: 1px solid #5695ed; background-color: #5695ed; } &:active { border: 1px solid darken(#5695ed, 10%); background-color: darken(#5695ed, 10%); } &Disabled { color: #fff; border: 1px solid #c5cfde; background-color: #c5cfde; cursor: not-allowed; pointer-events: none; } &Next, &Prev { padding-top: 8px; padding-bottom: 8px; padding-left: 24px; padding-right: 24px; } &Next { margin-left: 16px; } &Prev { margin-right: 16px; } } } <file_sep>/src/containers/products-container/products-container.js import React, { PureComponent } from 'react'; import { connect } from 'react-redux'; import { productsSelectors } from '../../redux/'; import Products from '../../components/products'; class ProductsContainer extends PureComponent { render() { const { productsData: { list, isLoading, error } } = this.props; const fetchData = { listLength: list.length, isLoading, error }; return <Products fetchData={fetchData} />; } } const mapStateToProps = state => { return { productsData: productsSelectors.getProducts(state) }; }; export default connect(mapStateToProps)(ProductsContainer); <file_sep>/src/components/input-filter-price/index.js import InputFilterPrice from './input-filter-price'; export default InputFilterPrice; <file_sep>/src/components/not-found/not-found.js import React from 'react'; import styles from './not-found.module.scss'; import Icon from '../icon'; import Header from '../header'; const NotFound = () => ( <div className={styles.NotFound}> <Icon name="island" style={{ marginBottom: '50px' }} /> <Header header={404} className={styles.NotFoundHeader} /> </div> ); export default NotFound; <file_sep>/src/containers/basket-container/basket-container.js import React, { PureComponent } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { basketActions, basketSelectors, productsSelectors, routerSelectors } from '../../redux/'; import Basket from '../../components/basket'; import { withApi } from '../../components/hoc-helpers'; class BasketContainer extends PureComponent { handleClick = event => { event.preventDefault(); const { target: { textContent: label } } = event; switch (label) { case 'Очистить корзину': this.props.emptyBasket(); break; case 'Cохранить корзину': this.props.saveBasket(`${this.props.apiBase}save`); break; default: throw new Error(`Unknown label: ${label}`); } }; render() { const { basketStatus: { isSending, isSuccessful }, basketList, mappedProductsList, location: { pathname } } = this.props; const sum = mappedProductsList.reduce((acc, value) => acc + value, 0); const basketListLength = basketList.length; return ( <Basket path={pathname.slice(1)} sum={sum} basketListLength={basketListLength} isSending={isSending} isSuccessful={isSuccessful} handleClick={this.handleClick} /> ); } } const mapStateToProps = state => { return { location: routerSelectors.getRouterLocation(state), basketStatus: basketSelectors.getBasketStatus(state), basketList: basketSelectors.getBasketList(state), mappedProductsList: productsSelectors.mapProductsList(state, 'price') }; }; const mapDispatchToProps = dispatch => { const { saveBasket, emptyBasket } = bindActionCreators( basketActions, dispatch ); return { saveBasket, emptyBasket }; }; export default connect( mapStateToProps, mapDispatchToProps )(withApi(BasketContainer)); <file_sep>/src/redux/modules/basket/selectors.js import { createSelector } from 'reselect'; const getBasket = ({ basket }) => basket; const getBasketStatus = createSelector(getBasket, ({ status }) => status); const getBasketList = createSelector(getBasket, ({ list }) => list); export { getBasketStatus, getBasketList }; <file_sep>/src/components/basket/basket.js import React from 'react'; import propTypes from 'prop-types'; import classnames from 'classnames'; import { Link } from 'react-router-dom'; import styles from './basket.module.scss'; import Icon from '../icon'; import Delayed from '../../containers/delayed-container'; const Basket = props => { const { path, sum, basketListLength, isSending, isSuccessful, handleClick } = props; const isDisabled = isSending || basketListLength === 0; return ( <form className={styles.Basket}> <section className={styles.BasketWrapper}> <Icon name="basket" /> <h3 className={styles.BasketHeader}>Корзина</h3> <div className={styles.BasketAmount}> Товаров <div className={styles.BasketAmountValue}>{basketListLength}</div> {isSuccessful && ( <Delayed showWhileTimeout={1000}> <Icon name="tick" /> </Delayed> )} </div> <div className={styles.BasketSum}> Всего <div className={styles.BasketSumValue}> {sum.toLocaleString('en-US').replace(/,/g, ' ')}&nbsp;&#8381; </div> </div> </section> <button className={classnames(styles.BasketButton, { [styles.BasketButtonDisabled]: isDisabled })} disabled={isDisabled} onClick={event => handleClick(event)} > Очистить корзину </button> <button className={classnames(styles.BasketButton, { [styles.BasketButtonDisabled]: isDisabled })} disabled={isDisabled} onClick={event => handleClick(event)} > Cохранить корзину </button> <Link to={{ pathname: '/basket' }} className={classnames(styles.BasketLink, { [styles.BasketLinkHidden]: path === 'basket' })} > Перейти в корзину </Link> </form> ); }; Basket.propTypes = { sum: propTypes.number, basketListLength: propTypes.number, isSending: propTypes.bool, isSuccessful: propTypes.bool, handleClick: propTypes.func }; export default Basket; <file_sep>/src/redux/modules/pagination/selectors.js import { createSelector } from 'reselect'; import { productsSelectors } from '../products'; import { routerSelectors } from '../router'; const getPagination = ({ pagination }) => { return pagination; }; const getPagesTotalCount = createSelector( [getPagination, productsSelectors.getFilteredProducts], ({ itemsPerPage }, filteredProducts) => Math.ceil(filteredProducts.length / itemsPerPage) ); const getVisibleProductsList = createSelector( [ getPagination, routerSelectors.getRouterSearchCurrentPage, productsSelectors.getFilteredProducts ], (pagination, currentPage, filteredProducts) => { const { itemsPerPage } = pagination; const lastProductIndex = currentPage * itemsPerPage; const firstProductIndex = lastProductIndex - itemsPerPage; return filteredProducts.slice(firstProductIndex, lastProductIndex); } ); export { getPagination, getVisibleProductsList, getPagesTotalCount }; <file_sep>/src/containers/filter-container/filter-container.js import React, { PureComponent } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { push } from 'connected-react-router'; import Filter from '../../components/filter'; import { filterActions, filterSelectors, routerSelectors, productsSelectors } from '../../redux'; class FilterContainer extends PureComponent { resetHistoryCurrentPage = () => { const { search, push } = this.props; const searchParams = new URLSearchParams(search); searchParams.set('currentPage', 1); push({ search: searchParams.toString() }); }; render() { const { filter, updateFilterField, resetFilter, productsList } = this.props; return ( <Filter filter={filter} updateFilterField={updateFilterField} resetFilter={resetFilter} resetHistoryCurrentPage={this.resetHistoryCurrentPage} productsList={productsList} /> ); } } const mapStateToProps = state => { return { filter: { price: filterSelectors.getFilterPrice(state), discount: filterSelectors.getFilterDiscount(state), categories: filterSelectors.getFilterCategories(state) }, search: routerSelectors.getRouterSearch(state), productsList: productsSelectors.getProductsList(state) }; }; const mapDispatchToProps = dispatch => bindActionCreators({ ...filterActions, push }, dispatch); export default connect(mapStateToProps, mapDispatchToProps)(FilterContainer); <file_sep>/src/redux/modules/basket/types.js export const SAVE_BASKET_STARTED = 'app/products/SAVE_BASKET_STARTED'; export const SAVE_BASKET_FAILURE = 'app/products/SAVE_BASKET_FAILURE'; export const SAVE_BASKET_SUCCESS = 'app/products/SAVE_BASKET_SUCCESS'; export const ADD_ITEM_TO_BASKET = 'app/products/ADD_ITEM_TO_BASKET'; export const REMOVE_ITEM_FROM_BASKET = 'app/products/REMOVE_ITEM_FROM_BASKET'; export const EMPTY_BASKET = 'app/products/EMPTY_BASKET'; <file_sep>/src/containers/product-details-container/product-details-container.js import React, { PureComponent } from 'react'; import { connect } from 'react-redux'; import { goBack } from 'connected-react-router'; import { maxBy } from 'csssr-school-utils'; import { productsSelectors } from '../../redux'; import ProductDetails from '../../components/product-details'; class ProductDetailsContainer extends PureComponent { render() { const { product = {}, maxRating, ...restProps } = this.props; return ( <ProductDetails product={product} maxRating={maxRating} {...restProps} /> ); } } const mapStateToProps = (state, { id }) => { return { product: productsSelectors.getProductsListItemById(state, id), maxRating: productsSelectors.reduceProductsList(state, maxBy, 'stars') }; }; export default connect(mapStateToProps, { goBack })(ProductDetailsContainer); <file_sep>/src/components/pages/product-details-page.js import React from 'react'; import propTypes from 'prop-types'; import ProductDetailsContainer from '../../containers/product-details-container'; const ProductDetailsPage = ({ id }) => <ProductDetailsContainer id={id} />; ProductDetailsPage.propTypes = { id: propTypes.number }; export default ProductDetailsPage; <file_sep>/src/redux/modules/basket/actions.js import * as types from './types'; export const saveBasketStarted = () => ({ type: types.SAVE_BASKET_STARTED }); export const saveBasketFailure = payload => ({ type: types.SAVE_BASKET_FAILURE, payload }); export const saveBasketSuccess = payload => ({ type: types.SAVE_BASKET_SUCCESS, payload }); export const addItemToBasket = payload => ({ type: types.ADD_ITEM_TO_BASKET, payload }); export const removeItemFromBasket = payload => ({ type: types.REMOVE_ITEM_FROM_BASKET, payload }); export const emptyBasket = () => ({ type: types.EMPTY_BASKET }); export const saveBasket = (url, basketList) => { return async dispatch => { dispatch(saveBasketStarted()); try { const response = await fetch(url, { method: 'POST', body: JSON.stringify(basketList), mode: 'cors', headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }); if (response.ok) { dispatch(saveBasketSuccess()); } else { throw new Error(`Could not fetch ${url}, received ${response.status}`); } } catch (error) { dispatch(saveBasketFailure({ error })); } }; }; <file_sep>/src/components/input-filter-category/input-filter-category.module.scss .InputFilter { &Category { display: flex; flex-flow: row nowrap; justify-content: center; align-items: center; margin: 0; padding: 0; padding-top: 8px; padding-bottom: 8px; padding-left: 16px; padding-right: 16px; font-size: 14px; line-height: 1; font-weight: 600; color: #323c48; text-decoration: none; text-transform: capitalize; background-color: transparent; border: 1px solid #323c48; border-radius: 15px; transition: all 0.5s; &:not(:last-of-type) { margin-right: 16px; } &:focus { outline: none; } &:hover, &:focus { color: #ffffff; background-color: #323c48; } &:active, &Active { color: #ffffff; background-color: darken(#323c48, 10%); border: 1px solid darken(#323c48, 10%); } } } <file_sep>/src/containers/product-toggle-container/index.js import ProductToggleContainer from './product-toggle-container'; export default ProductToggleContainer; <file_sep>/src/components/product-rating/index.js import ProductRating from './product-rating'; export default ProductRating; <file_sep>/src/components/input-filter-discount/index.js import InputFilterDiscount from './input-filter-discount'; export default InputFilterDiscount; <file_sep>/src/components/app/app.js import React from 'react'; import { Route, Switch, withRouter } from 'react-router-dom'; import classnames from 'classnames'; import styles from './app.module.scss'; import NotFound from '../not-found'; import ProductsPage from '../pages/products-page'; import ProductDetailsPage from '../pages/product-details-page'; import BasketPage from '../pages/basket-page'; const App = () => { return ( <div className={classnames(styles.App)}> <div className={classnames(styles.AppContainer)}> <Switch> <Route path="/" exact component={ProductsPage} /> <Route path="/product/:id" exact render={({ match: { params } }) => { const { id } = params; return <ProductDetailsPage id={Number(id)} />; }} /> <Route path="/basket" exact component={BasketPage} /> <Route component={NotFound} /> </Switch> </div> </div> ); }; export default withRouter(App); <file_sep>/src/redux/modules/pagination/index.js import paginationReducer from './reducer'; import * as paginationSelectors from './selectors'; export { paginationSelectors }; export default paginationReducer; <file_sep>/src/components/input-filter-discount/input-filter-discount.js import React from 'react'; import propTypes from 'prop-types'; import classnames from 'classnames'; import CSSSRSchoolInputDiscount from 'csssr-school-input-discount'; import styles from './input-filter-discount.module.scss'; import { withInputFilterNumberHandler } from '../hoc-helpers'; const InputFilterDiscount = ({ isValid, parentClassName, updateFilterField, handleChange, ...restProps }) => ( <section className={classnames( parentClassName, styles.InputFilter, styles.InputFilterDiscount, { [styles.InputFilterInvalid]: !isValid } )} > <CSSSRSchoolInputDiscount onChange={event => handleChange(event, 'discount')} {...restProps} /> </section> ); InputFilterDiscount.propTypes = { title: propTypes.string, name: propTypes.string, value: propTypes.number, parentClassName: propTypes.string, isValid: propTypes.bool, handleChange: propTypes.func, updateFilterField: propTypes.func }; export default withInputFilterNumberHandler(InputFilterDiscount); <file_sep>/src/components/list/list.module.scss .List { display: flex; flex-flow: row wrap; justify-content: flex-start; margin: 0; padding: 0; list-style: none; &Item { margin-bottom: 50px; text-decoration: none; cursor: pointer; &:not(:nth-child(3n)) { margin-right: 30px; } } } <file_sep>/src/components/icon/utils/render-icon.js import React from 'react'; import propTypes from 'prop-types'; import ArrowIcon from '../arrow-icon'; import IllPlanetIcon from '../ill-planet-icon'; import IslandIcon from '../island-icon'; import RatingIcon from '../rating-icon'; import SpinnerIcon from '../spinner-icon'; import BasketIcon from '../basket-icon'; import TickIcon from '../tick-icon'; const renderIcon = props => { const { name } = props; switch (name) { case 'arrow': return <ArrowIcon {...props} />; case 'ill-planet': return <IllPlanetIcon {...props} />; case 'island': return <IslandIcon {...props} />; case 'rating': return <RatingIcon {...props} />; case 'spinner': return <SpinnerIcon {...props} />; case 'basket': return <BasketIcon {...props} />; case 'tick': return <TickIcon {...props} />; default: return; } }; renderIcon.propTypes = { name: propTypes.string }; export { renderIcon }; <file_sep>/src/containers/basket-details-container/index.js import BasketDetailsContainer from './basket-details-container'; export default BasketDetailsContainer; <file_sep>/src/components/products/products.module.scss .Products { position: relative; display: flex; flex-flow: row wrap; justify-content: space-between; align-items: flex-start; &Sidebar { display: flex; align-items: flex-start; width: 255px; &Left { margin-right: 50px; } &Right { margin-left: 50px; } } &Main { width: 732px; &Wrapper { display: flex; flex-flow: column wrap; justify-content: center; align-items: center; } } &Header { flex-basis: 100%; margin: 0; margin-bottom: 55px; padding: 0; font-size: 36px; font-weight: 300; line-height: 1; text-align: center; color: #323c48; } &Icon { display: flex; &CenterVertically { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } } } <file_sep>/src/components/header/header.js import React from 'react'; import propTypes from 'prop-types'; import styles from './header.module.scss'; const Header = ({ header }) => <h2 className={styles.Header}>{header}</h2>; Header.propTypes = { value: propTypes.string }; export default Header; <file_sep>/src/redux/modules/filter/reducer.js import * as types from './types'; import { minBy, maxBy } from 'csssr-school-utils'; const initialState = { price: { min: { value: 0, isValid: false }, max: { value: 0, isValid: false } }, discount: { total: { value: 100, isValid: false } }, categories: {} }; export default (state = initialState, action) => { const { type, payload = {} } = action; switch (type) { case types.RESET_FILTER: return initialState; case types.UPDATE_FILTER_FIELD: const { groupName, fieldName, fieldData } = payload; return { ...state, [groupName]: { ...state[groupName], [fieldName]: fieldData } }; case types.FILL_FILTER_WITH_DATA: const { list } = payload; const minPrice = minBy(item => item.price, list).price; const maxPrice = maxBy(item => item.price, list).price; const discount = minBy(item => item.discount, list).discount; const categories = Array.from( new Set(list.map(item => item.category)) ).reduce( (acc, category) => ({ ...acc, [category]: { isActive: false } }), {} ); initialState.price = { ...initialState.price, min: { ...initialState.price.min, value: minPrice, isValid: minPrice > 0 }, max: { ...initialState.price.max, value: maxPrice, isValid: maxPrice > 0 } }; initialState.discount = { ...initialState.discount, total: { value: discount, isValid: discount < 100 } }; initialState.categories = { ...initialState.categories, ...categories }; return { ...state, ...initialState }; default: return state; } }; <file_sep>/src/components/products/utils/render-list.js import React from 'react'; import propTypes from 'prop-types'; import ListContainer from '../../../containers/list-container'; import PaginationContainer from '../../../containers/pagination-container'; import Header from '../../header'; import Icon from '../../icon'; const renderList = ({ listLength, isLoading, error }) => { if (isLoading) { return ( <Icon name="spinner" style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)' }} /> ); } else if (error) { return ( <> <Header header={error} /> <Icon name="ill-planet" /> </> ); } else if (listLength === 0) { return ( <> <Header header="Товары не найдены" /> <Icon name="ill-planet" /> </> ); } else { return ( <> <Header header="Список товаров" /> <ListContainer /> <PaginationContainer /> </> ); } }; renderList.propTypes = { listLength: propTypes.number, isLoading: propTypes.bool, error: propTypes.string }; export { renderList }; <file_sep>/src/components/pages/basket-page.js import React from 'react'; import BasketDetailsContainer from '../../containers/basket-details-container'; const BasketPage = () => <BasketDetailsContainer />; export default BasketPage; <file_sep>/src/components/pages/index.js import ProductsPage from './products-page'; import ProductDetailsPage from './product-details-page'; import BasketPage from './basket-page'; export { ProductsPage, ProductDetailsPage, BasketPage }; <file_sep>/src/components/icon/arrow-icon.js import React from 'react'; import propTypes from 'prop-types'; const ArrowIcon = ({ width = 18, height = 12 }) => ( <svg width={width} height={height}> <title>Arrow</title> <path d="M18 5H3.83l3.58-3.59L6 0 0 6l6 6 1.41-1.41L3.83 7H18V5z" fill="var(--fill, black)" /> </svg> ); ArrowIcon.propTypes = { width: propTypes.number, height: propTypes.number }; export default ArrowIcon; <file_sep>/src/components/icon/basket-icon.js import React from 'react'; import propTypes from 'prop-types'; const BasketIcon = ({ width = 14, height = 12 }) => ( <svg width={width} height={height}> <title>Basket</title> <path fillRule="evenodd" clipRule="evenodd" fill="var(--fill, black)" d="M10.80671,4.65333L7.88666,0.28C7.76,0.09333,7.54666,0,7.33333,0 C7.12,0,6.90666,0.09333,6.78,0.28667L3.86,4.65333H0.66666C0.3,4.65333,0,4.95333,0,5.32C0,5.38,0.00667,5.44,0.02667,5.5 L1.72,11.68002c0.15333,0.56,0.66666,0.9733,1.28,0.9733h8.66671c0.6133,0,1.1266-0.4133,1.2866-0.9733L14.64671,5.5l0.02-0.18 c0-0.36667-0.3-0.66667-0.6667-0.66667H10.80671z M5.33333,4.65333l2-2.93333l1.99998,2.93333H5.33333z M6,8.65333 c0,0.73334,0.6,1.33329,1.33333,1.33329s1.33333-0.59995,1.33333-1.33329c0-0.73333-0.6-1.33333-1.33333-1.33333S6,7.92,6,8.65333z" /> </svg> ); BasketIcon.propTypes = { width: propTypes.number, height: propTypes.number }; export default BasketIcon; <file_sep>/src/components/price/price.js import React from 'react'; import propTypes from 'prop-types'; import classnames from 'classnames'; import styles from './price.module.scss'; const Price = ({ price, isPrimary = true }) => ( <span className={classnames( 'ItemListsprice', styles.Price, { [styles.PricePrimary]: isPrimary }, { [styles.PriceSecondary]: !isPrimary } )} > {price.toLocaleString('en-US').replace(/,/g, ' ')}&nbsp;&#8381; </span> ); Price.propTypes = { price: propTypes.number, isPrimary: propTypes.bool }; export default Price; <file_sep>/src/components/icon/spinner-icon.js import React from 'react'; import propTypes from 'prop-types'; import Loader from 'react-loader-spinner'; import 'react-loader-spinner/dist/loader/css/react-spinner-loader.css'; const SpinnerIcon = ({ width = 100, height = 100 }) => ( <Loader type="Puff" color="#5695ED" width={width} height={height} /> ); SpinnerIcon.propTypes = { width: propTypes.number, height: propTypes.number }; export default SpinnerIcon; <file_sep>/src/components/products/products.js import React from 'react'; import propTypes from 'prop-types'; import Row from '../row'; import FilterContainer from '../../containers/filter-container/'; import BasketContainer from '../../containers/basket-container'; import { renderList } from './utils'; const Products = ({ fetchData }) => { return ( <Row left={<FilterContainer />} center={<>{renderList(fetchData)}</>} right={<BasketContainer />} /> ); }; Products.propTypes = { fetchData: propTypes.shape({ listLength: propTypes.number, isLoading: propTypes.bool, error: propTypes.string }) }; export default Products; <file_sep>/src/redux/modules/router/index.js import * as routerSelectors from './selectors'; export { routerSelectors, }; <file_sep>/src/components/product-toggle/index.js import ProductToggle from './product-toggle'; export default ProductToggle; <file_sep>/src/components/header/header.module.scss .Header { flex-basis: 100%; margin: 0; margin-bottom: 55px; padding: 0; font-size: 36px; font-weight: 300; line-height: 1; text-align: center; color: #323c48; } <file_sep>/src/components/list/list.js import React from 'react'; import { Link } from 'react-router-dom'; import propTypes from 'prop-types'; import classnames from 'classnames'; import styles from './list.module.scss'; import ProductCard from 'csssr-school-product-card'; import { maxBy } from 'csssr-school-utils'; import ProductRating from '../product-rating'; import Price from '../price'; import ProductToggleContainer from '../../containers/product-toggle-container'; const List = props => { const { list } = props; const listElements = list.map(product => { const { id, name, img, price, status, subPriceContent, maxRating = maxBy(item => item.stars, list).stars, stars } = product; return ( <Link to={`/product/${id}`} key={id} className={classnames(styles.ListItem)} > <ProductCard isInStock={status === 'IN_STOCK'} img={img} title={name} maxRating={maxRating} rating={stars} price={<Price price={price} />} subPriceContent={ subPriceContent ? ( <Price price={subPriceContent} isPrimary={false} /> ) : ( '' ) } ratingComponent={ProductRating} /> <ProductToggleContainer id={id} /> </Link> ); }); return <ul className={classnames(styles.List)}>{listElements}</ul>; }; List.propTypes = { list: propTypes.arrayOf( propTypes.shape({ id: propTypes.number, isInStock: propTypes.bool, img: propTypes.string, title: propTypes.node, price: propTypes.node, subPriceContent: propTypes.node, maxRating: propTypes.number, rating: propTypes.number, discount: propTypes.number, category: propTypes.string }) ) }; export default List; <file_sep>/src/components/filter/filter.js import React from 'react'; import { Link } from 'react-router-dom'; import propTypes from 'prop-types'; import classnames from 'classnames'; import styles from './filter.module.scss'; import InputFilterPrice from '../input-filter-price'; import InputFilterDiscount from '../input-filter-discount'; import InputFilterCategoryContainer from '../../containers/input-filter-category-container'; const Filter = props => { const { filter: { price: { min, max }, discount: { total: totalDiscount }, categories }, updateFilterField, resetFilter, resetHistoryCurrentPage, productsList } = props; const isDisabled = productsList.length === 0; const mappedCategories = Object.keys(categories).map((category, index) => ( <InputFilterCategoryContainer key={index} name={category} value={category} /> )); return ( <form className={classnames(styles.Filter)} onChange={resetHistoryCurrentPage} > <section className={classnames(styles.FilterWrapper)}> <h3 className={classnames(styles.FilterHeader)}>Цена</h3> <div className={classnames(styles.FilterInner)}> от <InputFilterPrice name="min" value={min.value} isValid={min.isValid} updateFilterField={updateFilterField} /> до <InputFilterPrice name="max" value={max.value} isValid={max.isValid} updateFilterField={updateFilterField} /> </div> </section> <InputFilterDiscount title="Скидка" name="total" value={totalDiscount.value} isValid={totalDiscount.isValid} updateFilterField={updateFilterField} parentClassName={classnames(styles.FilterWrapper)} /> {Object.keys(categories).length !== 0 && ( <section className={classnames(styles.FilterWrapper)}> <h3 className={classnames(styles.FilterHeader)}>Категории</h3> <div className={styles.FilterInner}>{mappedCategories}</div> </section> )} <Link to={{ search: 'currentPage=1' }} className={classnames(classnames(styles.FilterReset), { [classnames(styles.FilterResetDisabled)]: isDisabled })} onClick={resetFilter} > Сбросить фильтры </Link> </form> ); }; Filter.propTypes = { filter: propTypes.shape({ price: propTypes.shape({ min: propTypes.shape({ value: propTypes.number, isValid: propTypes.bool }), max: propTypes.shape({ value: propTypes.number, isValid: propTypes.bool }) }), discount: propTypes.shape({ total: propTypes.shape({ value: propTypes.number, isValid: propTypes.bool }) }), categories: propTypes.shape({ books: propTypes.shape({ isActive: propTypes.bool }), clothes: propTypes.shape({ isActive: propTypes.bool }) }) }), updateFilterField: propTypes.func, resetFilter: propTypes.func }; export default Filter; <file_sep>/src/redux/modules/products/selectors.js import { createSelector } from 'reselect'; import { filterSelectors } from '../filter'; import { routerSelectors } from '../router'; import { basketSelectors } from '../basket'; const getProducts = state => { const { products } = state; return products; }; const getProductsList = createSelector(getProducts, ({ list }) => list); const getProductsListItemById = (state, id) => createSelector(getProductsList, list => { const [item] = list.filter(value => value.id === Number(id)); return item; })(state); const reduceProductsList = (state, reducer, propName) => createSelector(getProductsList, list => { if (list.length === 0) { return 0; } return reducer(item => item.value, list)[propName]; })(state); const filterProductsListByBasketList = state => createSelector( [getProductsList, basketSelectors.getBasketList], (productsList, basketList) => productsList.filter(value => basketList.includes(value.id)) )(state); const mapProductsList = (state, propName) => createSelector(filterProductsListByBasketList, filteredProductsList => filteredProductsList.map(value => value[propName]) )(state); const getFilteredProducts = createSelector( [ filterSelectors.getFilterPrice, filterSelectors.getFilterDiscount, routerSelectors.getRouterSearchCategories, getProductsList ], (filterPrice, filterDiscount, searchCategories, list) => { const { min: { value: minValue }, max: { value: maxValue } } = filterPrice; const { total: { value: discountValue } } = filterDiscount; const filteredProducts = list.filter( ({ price, discount: productDiscount }) => price >= minValue && price <= maxValue && productDiscount >= discountValue ); if (searchCategories.length !== 0) { return filteredProducts.filter(({ category }) => searchCategories.includes(category) ); } return filteredProducts; } ); export { getProducts, getProductsList, filterProductsListByBasketList, reduceProductsList, mapProductsList, getProductsListItemById, getFilteredProducts }; <file_sep>/src/redux/modules/products/types.js export const FETCH_PRODUCTS_STARTED = 'app/products/FETCH_PRODUCTS_STARTED'; export const FETCH_PRODUCTS_SUCCESS = 'app/products/FETCH_PRODUCTS_SUCCESS'; export const FETCH_PRODUCTS_FAILURE = 'app/products/FETCH_PRODUCTS_FAILURE'; <file_sep>/src/redux/modules/router/selectors.js import { createSelector } from 'reselect'; const getRouter = ({ router }) => router; const getRouterLocation = createSelector(getRouter, ({ location }) => location); const getRouterSearch = createSelector( getRouterLocation, ({ search }) => search ); const getRouterSearchCategories = createSelector(getRouterSearch, search => new URLSearchParams(search).getAll('category') ); const getRouterSearchCurrentPage = createSelector(getRouterSearch, search => { const searchParams = new URLSearchParams(search); return searchParams.has('currentPage') ? Number(searchParams.get('currentPage')) || 1 : 1; }); export { getRouterSearch, getRouterLocation, getRouterSearchCategories, getRouterSearchCurrentPage }; <file_sep>/src/redux/modules/products/index.js import productsReducer from './reducer'; import * as productsTypes from './types'; import * as productsActions from './actions'; import * as productsSelectors from './selectors'; export { productsTypes, productsActions, productsSelectors, }; export default productsReducer; <file_sep>/src/redux/modules/filter/index.js import filterReducer from './reducer'; import * as filterTypes from './types'; import * as filterActions from './actions'; import * as filterSelectors from './selectors'; export { filterTypes, filterActions, filterSelectors }; export default filterReducer; <file_sep>/src/components/input-filter-price/input-filter-price.js import React from 'react'; import propTypes from 'prop-types'; import classnames from 'classnames'; import styles from './input-filter-price.module.scss'; import { withInputFilterNumberHandler } from '../hoc-helpers'; const InputFilterPrice = ({ isValid, updateFilterField, handleChange, ...restProps }) => ( <input className={classnames(styles.InputFilter, styles.InputFilterPrice, { [styles.InputFilterInvalid]: !isValid })} onChange={event => handleChange(event, 'price')} {...restProps} /> ); InputFilterPrice.propTypes = { name: propTypes.string, value: propTypes.number, isValid: propTypes.bool, handleChange: propTypes.func, updateFilterField: propTypes.func }; export default withInputFilterNumberHandler(InputFilterPrice); <file_sep>/src/components/product-rating/product-rating.module.scss .ProductRating { --stroke: #323c48; display: inline-flex; margin-right: 10px; cursor: pointer; &IsFilled { --fill: #323c48; } } <file_sep>/src/components/basket-details/basket-details.js import React from 'react'; import { Link } from 'react-router-dom'; import propTypes from 'prop-types'; import classnames from 'classnames'; import styles from './basket-details.module.scss'; import Row from '../row'; import Icon from '../icon'; import Header from '../header'; import BasketContainer from '../../containers/basket-container'; import List from '../list'; const BasketDetails = props => { const { list, goBack } = props; return ( <Row center={ <div className={classnames(styles.BasketDetails)}> <div className={classnames(styles.BasketDetailsWrapper)}> <Link to="/" onClick={goBack} className={classnames(styles.BasketDetailsLink)} > <Icon name="arrow" /> </Link> <Header header="Корзина" /> </div> <List list={list} /> </div> } right={<BasketContainer />} /> ); }; BasketDetails.propTypes = { list: propTypes.arrayOf( propTypes.shape({ id: propTypes.number, isInStock: propTypes.bool, img: propTypes.string, title: propTypes.node, price: propTypes.node, subPriceContent: propTypes.node, maxRating: propTypes.number, rating: propTypes.number, discount: propTypes.number, category: propTypes.string }) ), goBack: propTypes.func }; export default BasketDetails; <file_sep>/src/components/input-filter-category/input-filter-category.js import React from 'react'; import { Link } from 'react-router-dom'; import propTypes from 'prop-types'; import classnames from 'classnames'; import styles from './input-filter-category.module.scss'; const InputFilterCategory = ({ name, value, isActive, updateSearchWithCategory }) => ( <Link to={updateSearchWithCategory(name)} className={classnames(styles.InputFilter, styles.InputFilterCategory, { [styles.InputFilterCategoryActive]: isActive })} > {value} </Link> ); InputFilterCategory.propTypes = { value: propTypes.string, isActive: propTypes.bool, updateSearchWithCategory: propTypes.func }; export default InputFilterCategory; <file_sep>/src/components/icon/tick-icon.js import React from 'react'; import propTypes from 'prop-types'; const TickIcon = ({ width = 18, height = 14 }) => ( <svg width={width} height={height}> <title>Tick</title> <path d="M5.6 10.6L1.4 6.4 0 7.8l5.6 5.6 12-12L16.2 0 5.6 10.6z" fill="var(--fill, black)" /> </svg> ); TickIcon.propTypes = { width: propTypes.number, height: propTypes.number }; export default TickIcon; <file_sep>/src/components/product-details/product-details.module.scss .ProductDetails { display: flex; flex-flow: column nowrap; align-items: center; &Wrapper { display: flex; flex-flow: row nowrap; align-items: center; height: 100%; } &Link { display: flex; align-items: center; height: 100%; margin-right: 20px; margin-bottom: 50px; transition-duration: 1s; transition-property: all; svg { --fill: #000000; width: 18px; height: 12px; transition-duration: inherit; transition-property: inherit; } &:hover { svg { --fill: #5695ed; } } } } <file_sep>/src/containers/input-filter-category-container/index.js import InputFilterCategoryContainer from './input-filter-category-container'; export default InputFilterCategoryContainer; <file_sep>/src/components/product-toggle/product-toggle.js import React from 'react'; import styles from './product-toggle.module.scss'; import classnames from 'classnames'; import propTypes from 'prop-types'; const ProductToggle = ({ label, id, handleClick }) => { return ( <button className={classnames(styles.ProductToggle)} onClick={event => handleClick(event, id)} > {label} </button> ); }; ProductToggle.propTypes = { id: propTypes.number, label: propTypes.string, handleClick: propTypes.func }; export default ProductToggle; <file_sep>/src/containers/product-details-container/index.js import ProductDetailsContainer from './product-details-container'; export default ProductDetailsContainer; <file_sep>/src/containers/delayed-container/index.js import Delayed from './delayed-container'; export default Delayed; <file_sep>/src/containers/delayed-container/delayed-container.js import { PureComponent } from 'react'; import propTypes from 'prop-types'; class Delayed extends PureComponent { state = { isVisible: true }; componentDidMount() { this.timer(); } componentWillUnmount() { clearTimeout(this.timer); } timer = () => setTimeout(() => { this.setState({ isVisible: false }); }, this.props.showWhileTimeout); render() { return this.state.isVisible ? this.props.children : ''; } } Delayed.propTypes = { showWhileTimeout: propTypes.number }; export default Delayed; <file_sep>/src/redux/modules/filter/types.js export const RESET_FILTER = 'app/products/RESET_FILTER'; export const UPDATE_FILTER_FIELD = 'app/products/UPDATE_FILTER_FIELD'; export const FILL_FILTER_WITH_DATA = 'app/products/FILL_FILTER_WITH_DATA';
81b018942de8bf22ac63e44350ead03b8373727a
[ "SCSS", "JavaScript" ]
70
SCSS
CalledByThe4ire/junior-course-boilerplate
de89e59b25a3911dd03ca0f04ef84e863258160c
277eb4ec55b51032569b4ec543f4a407911dc11e
refs/heads/master
<repo_name>esogin/organicC-worm-uptake<file_sep>/Scripts/DataProcessing.R ## GC-MS Data ANALYSIS ## August 23 2016 ## Author: <NAME> ## Description ## Goals of code are to do a general metabolome comparison bewteen treatments and to detect metabolites with stable isotope labels ## Set up working space rm(list=ls()) dir<-"/home/maggie/Documents/ResearchProjects/OlaXSeagrass_Analysis/OrganicC-worm-uptake/" setwd(file.path(dir)) library(vegan); library(ggplot2); library(beyonce); library(xcms); library(X13CMS); library(metaMS); library(metaMSdata) source('~/Documents/ResearchProjects/GCMS_Database/Scripts/Parameters.R') ## Source parametesr file load('~/Documents/ResearchProjects/GCMS_Database/Results/non_salt_db.R')## Source GC-MS non-salt database source('./Scripts/functions.R') ## Load metadata setwd(file.path(dir,'Data', 'April_2016')) metadata<-read.csv('metadata_april2016_incubations.csv', header=T) ############################################## ######### GENERAL PROFILE COMPARISON ######### ############################################## ## PEAK PICKING WITH runGC using paramters and database from GCMS_Database directory setwd(file.path(dir, 'Data', 'April_2016', 'GCMS')) files<-list.files(pattern='.CDF', recursive = T, full.names=T) # select datafiles gcData<-runGC(files = files, settings = TSXLS.GC.custom, DB=DB, returnXset = T) ## Does peak picking and annotation setwd(file.path(dir,'Results')) save(gcData, file= 'runGC_results_allincubations.R') # save processing load(file = 'runGC_results_allincubations.R') ## loads gc run results ## FORMAT PEAK TABLE FOR ANALYSIS peak.table<-gcData$PeakTable head(peak.table); dim(peak.table) ## Reformat peak table and associate metadata peak.table.t<-data.frame(t(peak.table[,grep('X', colnames(peak.table))])) colnames(peak.table.t)<-peak.table$Name head(peak.table.t[,1:10]) ## Normalize to Ribitol peak dd<-sweep(peak.table.t, MARGIN = 1, STATS = peak.table.t$`Ribitol 5TMS`,FUN = '/') head(dd) df<-data.frame(File=gsub('X','',rownames(dd)),dd) df[,1:10] df<-df[complete.cases(df),] ## removes samples with NA values indicating ribitol derivitization didn't work ## Create dataframe with metadata dim(df); dim(metadata[metadata$File %in% df$File,]) #sanity check vars<-c('File','Treatment','Factor1','TargetTimePoint_hours') #variables of interest in metadata df.m<-merge(metadata[,vars], df, by = 'File'); dim(df.m) head(df.m[,1:10]) stds<-c('Ribitol.5TMS','Cholestane.1TMS') df.m<-df.m[,!colnames(df.m)%in%stds]; dim(df.m) #removed standards ###### Statistical Analysis ##### ##************ Variation in control samples ********************## ## Select data XY<-df.m[df.m$Factor1=='Control',]; dim(XY) ## Select Samples XD<-XY[,!colnames(XY) %in% vars] ## Selects data X<-XD[,!sapply(XD, function(x) {sd(x)==0})] ## Removes non-infomrative variables Y<-as.vector(XY$TargetTimePoint_hours) ## nmds/pcoa d<-vegdist(X, method='bray') pcoa<-cmdscale(d) plot(pcoa, pch=16) pca<-prcomp(X,center = T, scale=T) pts<-pca$x PC1<-signif(summary(pca)$importance['Proportion of Variance','PC1'],2)*100 PC2<-signif(summary(pca)$importance['Proportion of Variance','PC2'],2)*100 xlab<-paste('PC1 = ',PC1,'%',sep=''); ylab<-paste('PC2 = ',PC2,'%',sep='') plot(pts,pch=16, xlab=xlab, ylab=ylab, xlim=c(-30,30), ylim=c(-20,20)) ordiellipse(pca,groups=XY$Factor1, kind = 'sd', col='red') text(pts,pos = 3,labels = XY$Treatment, cex=0.75) ## *********** Variation in samples across time ****************## ## SUCROSE ## ## Select data i<-'Oxic' ## Select conditions j<-'Sucrose 13C6' # Select treatment XY<-df.m[df.m$Factor1==i&df.m$Treatment==j,]; dim(XY) ## Select Samples XD<-XY[,!colnames(XY) %in% vars] ## Selects data X<-XD[,!sapply(XD, function(x) {sd(x)==0})] ## Removes non-infomrative variables Y<-as.numeric(as.vector(XY$TargetTimePoint_hours)) ## PCA pca<-prcomp(X,center = T, scale=T); pts<-data.frame(pca$x,Y=as.factor(Y)) PC1<-signif(summary(pca)$importance['Proportion of Variance','PC1'],2)*100; PC2<-signif(summary(pca)$importance['Proportion of Variance','PC2'],2)*100 p1<-ggplot(data=pts, aes(x=PC1, y=PC2, color=Y)) + geom_point(size=3) + xlab(paste('PC1 = ',PC1,'%',sep='')) + ylab(paste('PC2 = ',PC2,'%',sep='')) + ggtitle(paste(i,j,sep='-')) + scale_color_manual(values=beyonce_palette(66,n = 4, type = 'continuous')) + theme_gray() adonis(X~Y);anosim(X,Y) ## Select data i<-'Anoxic' ## Select conditions j<-'Sucrose 13C6' # Select treatment XY<-df.m[df.m$Factor1==i&df.m$Treatment==j,]; dim(XY) ## Select Samples XD<-XY[,!colnames(XY) %in% vars] ## Selects data X<-XD[,!sapply(XD, function(x) {sd(x)==0})] ## Removes non-infomrative variables Y<-as.numeric(as.vector(XY$TargetTimePoint_hours)) ## PCA pca<-prcomp(X,center = T, scale=T); pts<-data.frame(pca$x,Y=as.factor(Y)) PC1<-signif(summary(pca)$importance['Proportion of Variance','PC1'],2)*100; PC2<-signif(summary(pca)$importance['Proportion of Variance','PC2'],2)*100 p2<-ggplot(data=pts, aes(x=PC1, y=PC2, color=Y)) + geom_point(size=3) + xlab(paste('PC1 = ',PC1,'%',sep='')) + ylab(paste('PC2 = ',PC2,'%',sep='')) + ggtitle(paste(i,j,sep='-')) + scale_color_manual(values=beyonce_palette(66,n = 4, type = 'continuous')) + theme_gray() adonis(X~Y);anosim(X,Y) ## Myo-Inositol ## Select data i<-'Oxic' ## Select conditions j<-'Myo_Inositol C_D6' # Select treatment XY<-df.m[df.m$Factor1==i&df.m$Treatment==j,]; dim(XY) ## Select Samples XD<-XY[,!colnames(XY) %in% vars] ## Selects data X<-XD[,!sapply(XD, function(x) {sd(x)==0})] ## Removes non-infomrative variables Y<-as.numeric(as.vector(XY$TargetTimePoint_hours)) ## PCA pca<-prcomp(X,center = T, scale=T); pts<-data.frame(pca$x,Y=as.factor(Y)) PC1<-signif(summary(pca)$importance['Proportion of Variance','PC1'],2)*100; PC2<-signif(summary(pca)$importance['Proportion of Variance','PC2'],2)*100 p3<-ggplot(data=pts, aes(x=PC1, y=PC2, color=Y)) + geom_point(size=3) + xlab(paste('PC1 = ',PC1,'%',sep='')) + ylab(paste('PC2 = ',PC2,'%',sep='')) + ggtitle(paste(i,j,sep='-')) + scale_color_manual(values=beyonce_palette(66,n = 4, type = 'continuous')) + theme_gray() adonis(X~Y);anosim(X,Y) ## Select data i<-'Anoxic' ## Select conditions XY<-df.m[df.m$Factor1==i&df.m$Treatment==j,]; dim(XY) ## Select Samples XD<-XY[,!colnames(XY) %in% vars] ## Selects data X<-XD[,!sapply(XD, function(x) {sd(x)==0})] ## Removes non-infomrative variables Y<-as.numeric(as.vector(XY$TargetTimePoint_hours)) ## PCA pca<-prcomp(X,center = T, scale=T); pts<-data.frame(pca$x,Y=as.factor(Y)) PC1<-signif(summary(pca)$importance['Proportion of Variance','PC1'],2)*100; PC2<-signif(summary(pca)$importance['Proportion of Variance','PC2'],2)*100 p4<-ggplot(data=pts, aes(x=PC1, y=PC2, color=Y)) + geom_point(size=3) + xlab(paste('PC1 = ',PC1,'%',sep='')) + ylab(paste('PC2 = ',PC2,'%',sep='')) + ggtitle(paste(i,j,sep='-')) + scale_color_manual(values=beyonce_palette(66,n = 4, type = 'continuous')) + theme_gray() adonis(X~Y);anosim(X,Y) ## Bicarbonate ## Select data i<-'Oxic' ## Select conditions j<-'Bicarbonate 13C1' # Select treatment XY<-df.m[df.m$Factor1==i&df.m$Treatment==j,]; dim(XY) ## Select Samples XD<-XY[,!colnames(XY) %in% vars] ## Selects data X<-XD[,!sapply(XD, function(x) {sd(x)==0})] ## Removes non-infomrative variables Y<-as.numeric(as.vector(XY$TargetTimePoint_hours)) ## PCA pca<-prcomp(X,center = T, scale=T); pts<-data.frame(pca$x,Y=as.factor(Y)) PC1<-signif(summary(pca)$importance['Proportion of Variance','PC1'],2)*100; PC2<-signif(summary(pca)$importance['Proportion of Variance','PC2'],2)*100 p5<-ggplot(data=pts, aes(x=PC1, y=PC2, color=Y)) + geom_point(size=3) + xlab(paste('PC1 = ',PC1,'%',sep='')) + ylab(paste('PC2 = ',PC2,'%',sep='')) + ggtitle(paste(i,j,sep='-')) + scale_color_manual(values=beyonce_palette(66,n = 4, type = 'continuous')) + theme_gray() adonis(X~Y);anosim(X,Y) ## Select data i<-'Anoxic' ## Select conditions XY<-df.m[df.m$Factor1==i&df.m$Treatment==j,]; dim(XY) ## Select Samples XD<-XY[,!colnames(XY) %in% vars] ## Selects data X<-XD[,!sapply(XD, function(x) {sd(x)==0})] ## Removes non-infomrative variables Y<-as.numeric(as.vector(XY$TargetTimePoint_hours)) ## PCA pca<-prcomp(X,center = T, scale=T); pts<-data.frame(pca$x,Y=as.factor(Y)) PC1<-signif(summary(pca)$importance['Proportion of Variance','PC1'],2)*100; PC2<-signif(summary(pca)$importance['Proportion of Variance','PC2'],2)*100 p6<-ggplot(data=pts, aes(x=PC1, y=PC2, color=Y)) + geom_point(size=3) + xlab(paste('PC1 = ',PC1,'%',sep='')) + ylab(paste('PC2 = ',PC2,'%',sep='')) + ggtitle(paste(i,j,sep='-')) + scale_color_manual(values=beyonce_palette(66,n = 4, type = 'continuous')) + theme_gray() adonis(X~Y);anosim(X,Y) ## Combine in multiplot multiplot(p1,p2,p3,p4,p5,p6,cols=3) ## *********** Variation in samples with Oxygen conditions *****## ## Sucrose ## Select data j<-'Sucrose 13C6' # Select treatment XY<-df.m[df.m$Treatment==j,]; dim(XY) ## Select Samples XD<-XY[,!colnames(XY) %in% vars] ## Selects data X<-XD[,!sapply(XD, function(x) {sd(x)==0})] ## Removes non-infomrative variables Y<-as.vector(XY$Factor1) ## PCA pca<-prcomp(X,center = T, scale=T); pts<-data.frame(pca$x,Y=as.factor(Y)) PC1<-signif(summary(pca)$importance['Proportion of Variance','PC1'],2)*100; PC2<-signif(summary(pca)$importance['Proportion of Variance','PC2'],2)*100 p1<-ggplot(data=pts, aes(x=PC1, y=PC2, color=Y)) + geom_point(size=3) + xlab(paste('PC1 = ',PC1,'%',sep='')) + ylab(paste('PC2 = ',PC2,'%',sep='')) + ggtitle(paste(j,sep='-')) + scale_color_manual(values=beyonce_palette(51,n = 2, type = 'continuous')) + theme_gray() adonis(X~Y);anosim(X,Y) ## Myo-inositol ## Select data j<-'Myo_Inositol C_D6' # Select treatment XY<-df.m[df.m$Treatment==j,]; dim(XY) ## Select Samples XD<-XY[,!colnames(XY) %in% vars] ## Selects data X<-XD[,!sapply(XD, function(x) {sd(x)==0})] ## Removes non-infomrative variables Y<-as.vector(XY$Factor1) ## PCA pca<-prcomp(X,center = T, scale=T); pts<-data.frame(pca$x,Y=as.factor(Y)) PC1<-signif(summary(pca)$importance['Proportion of Variance','PC1'],2)*100; PC2<-signif(summary(pca)$importance['Proportion of Variance','PC2'],2)*100 p2<-ggplot(data=pts, aes(x=PC1, y=PC2, color=Y)) + geom_point(size=3) + xlab(paste('PC1 = ',PC1,'%',sep='')) + ylab(paste('PC2 = ',PC2,'%',sep='')) + ggtitle(paste(j,sep='-')) + scale_color_manual(values=beyonce_palette(51,n = 2, type = 'continuous')) + theme_gray() adonis(X~Y);anosim(X,Y) ## Bicarbonate j<-'Bicarbonate 13C1' # Select treatment XY<-df.m[df.m$Treatment==j,]; dim(XY) ## Select Samples XD<-XY[,!colnames(XY) %in% vars] ## Selects data X<-XD[,!sapply(XD, function(x) {sd(x)==0})] ## Removes non-infomrative variables Y<-as.vector(XY$Factor1) ## PCA pca<-prcomp(X,center = T, scale=T); pts<-data.frame(pca$x,Y=as.factor(Y)) PC1<-signif(summary(pca)$importance['Proportion of Variance','PC1'],2)*100; PC2<-signif(summary(pca)$importance['Proportion of Variance','PC2'],2)*100 p3<-ggplot(data=pts, aes(x=PC1, y=PC2, color=Y)) + geom_point(size=3) + xlab(paste('PC1 = ',PC1,'%',sep='')) + ylab(paste('PC2 = ',PC2,'%',sep='')) + ggtitle(paste(j,sep='-')) + scale_color_manual(values=beyonce_palette(51,n = 2, type = 'continuous')) + theme_gray() adonis(X~Y);anosim(X,Y) multiplot(p1,p2,p3,cols=3) ## *********** Variation in samples with substrate *************## i<-'48' j<-'Oxic' k<-'Control' df.m<-df.m[-grep('MPI',df.m$Treatment),] XY<-df.m[df.m$TargetTimePoint_hours==i & df.m$Factor1==j|df.m$Factor1=='Control',]; dim(XY) XD<-XY[,!colnames(XY) %in% vars] ## Selects data Y<-as.vector(XY$Treatment) table(Y) Y[grep('Bucket',Y)]<-'Control' X<-XD[,which(colSums(XD>0)>3)] ## selects variables occuring in more then 3 samples ## PCA pca<-prcomp(X,center = T, scale=T); pts<-data.frame(pca$x,Y=as.factor(Y)) PC1<-signif(summary(pca)$importance['Proportion of Variance','PC1'],2)*100; PC2<-signif(summary(pca)$importance['Proportion of Variance','PC2'],2)*100 ggplot(data=pts, aes(x=PC1, y=PC2, color=Y)) + geom_point(size=3) + xlab(paste('PC1 = ',PC1,'%',sep='')) + ylab(paste('PC2 = ',PC2,'%',sep='')) + scale_color_manual(values=beyonce_palette(40,n = 6, type = 'continuous')) + theme_gray() adonis(X~Y);anosim(X,Y) ## Heatmap heatmap.2(t(log10(as.matrix(X+1))),labCol = Y , trace='none', cexRow = 0.75, cexCol = 0.75) ######################################################## ## X13CMS Stable Isotope Anlaysis ## Peak Picking using XCMS -- Sucrose Experiment control samples vs. 48 hr setwd(file.path(dir, 'Data','April_2016','GCMS','Oxic', 'Sucrose', 'isotope')) xs.sucrose<-xcmsSet(files=c('./12C','./13C'),snthresh=2,max=100,step=0.1, steps=2, fwhm=30, mzdiff=1, method='matchedFilter') xs<-group(xs.sucrose) xsa<-xsAnnotate(xs) xsa.g<-groupFWHM(xsa, perfwhm=2) xset.sucrose<-xsa.g@xcmsSet <file_sep>/Scripts/MetaData Manipulation .R ## <NAME> ## MetaData Manipulation ## April 2016 ## Elba Field Trip ## Set up working space mainDir<-"/Users/esogin/Documents/ResearchProjects/Elba_2016/OlavXSeaGrass" setwd(file.path(mainDir, 'Data')) library('reshape2') library('ggplot2') ## Import sampling data df<-read.csv(file = 'sampling_data.csv') head(df) ## Melt DF into long format df.melt<-melt(df,id.vars = c('Hungate.Tube.ID', 'Treatment','Factor1','TargetTimePoint','StartDate','StartTime', 'EndDate','EndTime')) ## Count number of samples ## Num Metabolomics samples head(df.melt) df.met<-df.melt[which(df.melt$variable=='WormID_B'|df.melt$variable=='WormID_A'|df.melt$variable=='WormID_C'),] dim(na.omit(df.met)) ## 742 metabolomics samples df.RNA<-df.melt[which(df.melt$variable=='RNA_ID_A'|df.melt$variable=='RNA_ID_B'),] dim(na.omit(df.RNA)) ## 336 RNA samples df.Media<-df.melt[which(df.melt$variable=='Media_ID'|df.melt$variable=='Wash_Media_ID'),] dim(na.omit(df.Media)) ## 294 Media samples df.FISH<-df.melt[which(df.melt$variable=='FISH_ID'),] dim(na.omit(df.FISH)) ## 126 Fish samples Total<-length(df.RNA$value) + length(df.Media$value) + length(df.met$value) + length(df.FISH$value) Total ## Plot Oxygen Concentrations df.melt.O2<-df.melt[which(df.melt$variable=='Oxygen_Concentration_umol_ml'),] df.melt.O2<-na.omit(df.melt.O2) head(df.melt.O2) df.melt.O2$value<-as.numeric(df.melt.O2$value) df.melt.O2<-df.melt.O2[order(df.melt.O2$Treatment, decreasing=T),] ggplot(df.melt.O2, aes(TargetTimePoint,value)) + geom_point(position=position_jitter(width = .5), aes(col=Treatment, shape=Factor1, size=3)) + theme_bw() + scale_color_brewer(palette = 'Paired') + theme(panel.grid.minor=element_blank()) + xlab('Time In Treatment') + ylab('Oxygen Concentration in umol/mL') controls<-df.melt.O2[which(df.melt.O2$Factor1=='Dead Control'|df.melt.O2$Factor1=='Sea Water Control'),] <file_sep>/Scripts/Database.R ## GCMS Database ## EMSOGIN ## Generate inhouse database dir<-"/home/maggie/Documents/ResearchProjects/OlaXSeagrass_Analysis/OrganicC-worm-uptake/" setwd(file.path(dir)) library(metaMS) source('./Scripts/Parameters.R') ## runGC parameters ###################################################################### setwd(file.path(dir,'Database')) ## FIX NISTDB system("sed 's/CAS#/CASNO/g' inhousedb.MSP > inhousedb-2.MSP") #fixes the CAS# Problem system("sed '/CASNO/s/-//g' inhousedb-2.MSP > inhousedb-3.MSP") #Fixes the - system("sed 's/; NIST.*//g' inhousedb-3.MSP > inhousedb-cleaned.MSP") #Fixes the mult. entries per line system('tail inhousedb-cleaned.MSP') NISTdb<-read.msp(file='inhousedb-cleaned.MSP') std<-read.csv(file = 'inhouseDB.csv') std$Name<-as.character(std$Name) std$monoMW<-as.numeric(std$monoMW) std$SpectraID<-paste(std$SpectraID,'.CDF', sep='') files<-list.files(pattern='.CDF', full.names=T) ## List all GC-MS cdf files in directory, make sure all are present f<-data.frame(files=files, ProfileID=gsub('./',replacement = '',x=files)) ## Make a lookup table std$stdFile<-as.vector(f[match(std$SpectraID, f$ProfileID),'files']) #put them into the file data DB <- createSTDdbGC(std, TSXLS.GC.custom,extDB = NISTdb) ## Creates database ## VALIDATION #test<-runGC(files = files, settings = TSXLS.GC.custom, DB=DB) #peak.table<-test$PeakTable #std[which(!std$CAS %in% peak.table$CAS),] #peak.table <file_sep>/Scripts/Elba Summary.R ## Worm Collection On Elba ## <NAME> ## April 2016 ## Set up working space dir<-"/Users/esogin/Documents/ResearchProjects/Elba_2016/OlavXSeaGrass" setwd(file.path(dir,'Data')) ## Import worm collection data worm_per_day<-read.csv('worm_collection_per_day.csv', header=T) worm_per_day$BetterDate<-as.Date(as.vector(worm_per_day$Day), format='%e-%B-%y') ##Visualize collection details par(mfrow=c(3,1), oma=c(0,1,1,0), mar=c(3,2,1,1), bg='black', bty='n',col.axis='white',col.main='white', col.lab='white') plot(worm_per_day$BetterDate, worm_per_day$NoOlavious, las=1, xlab='', ylab='No. Olavius Found', pch=16, col='goldenrod', xaxt='n', yaxt='n') axis.Date(1, x=worm_per_day$BetterDate, col='white', labels=F, format = '%e-%B') axis(2,col='white') plot(worm_per_day$BetterDate, worm_per_day$NoParacetenula, pch=16, col='lightblue', xlab='', ylab='No. Paracatenula found', xaxt='n', yaxt='n') axis.Date(1, x=worm_per_day$BetterDate, col='white', labels=F, format = '%e-%B') axis(2,col='white') plot(worm_per_day$BetterDate, worm_per_day$NoBuckets, pch=16, col='darkseagreen1', xlab='', ylab='No. Buckets Sorted', yaxt='n', xaxt='n') axis.Date(1, x=worm_per_day$BetterDate, col='white', labels=T,tick = T, format = '%e-%B') axis(2,col='white') ## Get Summary sum(worm_per_day$NoParacetenula) sum(worm_per_day$NoOlavious) sum(worm_per_day$NoBuckets) <file_sep>/Scripts/MainCode.R ## GC-MS Data ANALYSIS ## August 23 2016 ## Author: <NAME> ## Description ## Goals of code are to do a general metabolome comparison bewteen treatments and to detect metabolites with stable isotope labels ## Set up working space rm(list=ls()) dir<-"/home/maggie/Documents/ResearchProjects/OlaXSeagrass_Analysis/OrganicC-worm-uptake/" setwd(file.path(dir)) library(vegan); library(ggplot2); library(beyonce); library(xcms); library(X13CMS) source('~/Documents/ResearchProjects/GCMS_Database/Scripts/Parameters.R') ## Source parametesr file load('~/Documents/ResearchProjects/GCMS_Database/Results/non_salt_db.R')## Source GC-MS non-salt database source('./Scripts/functions.R') ## Load metadata setwd(file.path(dir,'Data', 'April_2016')) metadata<-read.csv('metadata_april2016_incubations.csv', header=T) ########################################################### ## GENERAL PROFILE COMPARISONS ## ########################################################### ## TREATMENT COMPARISION AFTER 48HR EXPOSURE ## Peak Picking setwd(file.path(dir, 'Data','April_2016','GCMS','sugar_comparision')) files<-list.files(pattern='.CDF', recursive = T, full.names=T) # select datafiles gcrun<-runGC(files = files, settings = TSXLS.GC.custom,findUnknowns = T,DB=DB) setwd(file.path(dir,"Results")) ##save(gcrun,file = 'gcrun_48hr_sugar_comp.R') load('gcrun_48hr_sugar_comp.R') ## Set up peak table peaks<-gcrun$PeakTable; peaks[1:10,1:10] ribitol<-peaks[which(peaks$Name=='Ribitol 5TMS'),grep('X',colnames(peaks))] cholestane<-peaks[which(peaks$Name=='Cholestane 1TMS'),grep('X',colnames(peaks))] peaks.dd<-peaks[,grep('X',colnames(peaks))] dd<-sweep(peaks.dd, MARGIN = 2, STATS = as.numeric(as.vector(ribitol)),FUN = '/') ## normalizes to ribitol area dd<-dd[,complete.cases(colSums(dd))] ## removes spectra without ribitol --> check these on machine head(dd) df<-data.frame(t(dd)) ## Normalized dataframe colnames(df)<-peaks$Name df<-df[,apply(df, 2, var, na.rm=TRUE) != 0] ## Removes columns with constant variance df<-df[,-which(colnames(df)=='Cholestane 1TMS')] ## Removes cholestane head(df) ##---- Data Quality Check/Exploration par(mfrow=(c(1,3))) rib<-as.numeric(as.vector(ribitol)); cho<-as.numeric(as.vector(cholestane)) barplot(height=rib,names.arg = colnames(ribitol), main="ribitol", ylab='Ion Intensity', cex.names=0.5, las=2) barplot(height=cho,names.arg = colnames(cholestane), main="Cholestane", ylab='Ion Intensity', cex.names=0.5, las=2) barplot(height=rib/cho,names.arg = colnames(cholestane), main="ribitol/cholestane", ylab='Ion Intensity', cex.names=0.5, las=2) abline(h=0.2, col='red') ## Remove samples with poor QC (rib / cho < 0.5) samps<-colnames(cholestane)[which(rib/cho > 0.5)] df.reduced<-df[rownames(df) %in% samps,] dim(df.reduced) ##---- Set up datatable with metadata df.reduced$File<-gsub("X",'',rownames(df.reduced)) vars<-c('Treatment','Factor1','TargetTimePoint_hours','File') df.merged<-merge(metadata[,colnames(metadata) %in% vars],df.reduced,'File') df.merged$TargetTimePoint_hours<-as.factor(df.merged$TargetTimePoint_hours) head(df.merged[,1:10]); dim(df.merged) df.merged$Treatment<-as.vector(df.merged$Treatment) df.merged$Treatment[grep('Bucket', df.merged$Treatment)]<-'Control' ##----- Statistical Comparisions myCols<-beyonce_palette(66, length(unique(df.merged$Treatment)), type='continuous') names(myCols)<-levels(df.merged$Treatment) colScale <- scale_colour_manual(name = "Treatment",values = myCols) ## PCA ## -- treatment comparison --- ## X<-df.merged[,sapply(df.merged,is.numeric)] ## selects only data columns Y<-df.merged$Treatment Y2<-df.merged$Factor1 pca<-prcomp(X,center = T, scale=T); pts<-data.frame(pca$x,trt=as.factor(Y),fac1=as.factor(Y2)) PC1<-signif(summary(pca)$importance['Proportion of Variance','PC1'],2)*100; PC2<-signif(summary(pca)$importance['Proportion of Variance','PC2'],2)*100 neworder<-c('Bicarbonate 13C1', 'Myo_Inositol C_D6', 'Sucrose 13C6', 'Sodium Acetate 13C2', 'Sodium lactate 13C3', 'Control') pts<-arrange(transform(pts,trt=factor(trt,levels=neworder)),trt) ## re-order to make plot pretty / match up ggplot(data=pts, aes(x=PC1, y=PC2, color=trt, shape=fac1,label=rownames(pts))) + geom_point(size=4) + xlab(paste('PC1 = ',PC1,'%',sep='')) + ylab(paste('PC2 = ',PC2,'%',sep='')) + ggtitle('All Conditions after 48 hr') + colScale + theme_gray() ggsave(filename = 'All conditions after 48hr.pdf', device = 'pdf', width=8, height=8) ## --- Oxic Conditions Only --- ## xdf<-df.merged[which(df.merged$Factor1=='Oxic'),] X<-xdf[,sapply(xdf,is.numeric)] X<-X[,apply(X, 2, var, na.rm=TRUE) != 0] ## Removes columns with constant variance Y<-as.factor(df.merged[which(df.merged$Factor1=='Oxic'),'Treatment']) pca<-prcomp(X,center = T, scale=T); pts<-data.frame(pca$x,trt=Y) PC1<-signif(summary(pca)$importance['Proportion of Variance','PC1'],2)*100; PC2<-signif(summary(pca)$importance['Proportion of Variance','PC2'],2)*100 neworder<-c('Bicarbonate 13C1', 'Myo_Inositol C_D6', 'Sucrose 13C6', 'Sodium Acetate 13C2', 'Sodium lactate 13C3') pts<-arrange(transform(pts,trt=factor(trt,levels=neworder)),trt) ## re-order to make plot pretty / match up ggplot(data=pts, aes(x=PC1, y=PC2, color=trt,label=rownames(pts))) + geom_point(size=4) + xlab(paste('PC1 = ',PC1,'%',sep='')) + ylab(paste('PC2 = ',PC2,'%',sep='')) + ggtitle('Oxic Conditions') + colScale + theme_gray() ggsave(filename = 'Oxic 48hr.pdf', device = 'pdf', width=8, height=8) ## -- Anoxic Conditions Only -- ## xdf<-df.merged[which(df.merged$Factor1=='Anoxic'),] X<-xdf[,sapply(xdf,is.numeric)] X<-X[,apply(X, 2, var, na.rm=TRUE) != 0] ## Removes columns with constant variance Y<-xdf$Treatment pca<-prcomp(X,center = T, scale=T); pts<-data.frame(pca$x,trt=as.factor(Y)) neworder<-c('Bicarbonate 13C1', 'Myo_Inositol C_D6', 'Sucrose 13C6') pts<-arrange(transform(pts,trt=factor(trt,levels=neworder)),trt) ## re-order to make plot pretty / match up PC1<-signif(summary(pca)$importance['Proportion of Variance','PC1'],2)*100; PC2<-signif(summary(pca)$importance['Proportion of Variance','PC2'],2)*100 ggplot(data=pts, aes(x=PC1, y=PC2, color=trt,label=rownames(pts))) + geom_point(size=4) + xlab(paste('PC1 = ',PC1,'%',sep='')) + ylab(paste('PC2 = ',PC2,'%',sep='')) + ggtitle('Anoxic Conditions') + colScale+ theme_gray() ggsave(filename = 'Anoxic 48hr.pdf', device = 'pdf', width=8, height=8) ##-- Oxic Sucrose vs. Anoxic Sucrose --## xdf<-df.merged[which(df.merged$Treatment=='Sucrose 13C6'),] X<-xdf[,sapply(xdf,is.numeric)] X<-X[,apply(X, 2, var, na.rm=TRUE) != 0] ## Removes columns with constant variance Y<-xdf$Factor1 pca<-prcomp(X,center = T, scale=T); pts<-data.frame(pca$x,trt=as.factor(Y)) PC1<-signif(summary(pca)$importance['Proportion of Variance','PC1'],2)*100; PC2<-signif(summary(pca)$importance['Proportion of Variance','PC2'],2)*100 ggplot(data=pts, aes(x=PC1, y=PC2, color=trt,label=rownames(pts))) + geom_point(size=4) + xlab(paste('PC1 = ',PC1,'%',sep='')) + ylab(paste('PC2 = ',PC2,'%',sep='')) + ggtitle('Oxic vs. Anoxic, Sucrose') + scale_color_manual(values=beyonce_palette(21, 2, type='continuous'))+ theme_gray() ggsave(filename = 'Oxic vs. Anoxic sucrose.pdf', device = 'pdf', width=8, height=8) ##-- Oxic Bicarbonate vs. Anoxic Bicarbonate --## xdf<-df.merged[which(df.merged$Treatment=='Bicarbonate 13C1'),] X<-xdf[,sapply(xdf,is.numeric)] X<-X[,apply(X, 2, var, na.rm=TRUE) != 0] ## Removes columns with constant variance Y<-xdf$Factor1 pca<-prcomp(X,center = T, scale=T); pts<-data.frame(pca$x,trt=as.factor(Y)) PC1<-signif(summary(pca)$importance['Proportion of Variance','PC1'],2)*100; PC2<-signif(summary(pca)$importance['Proportion of Variance','PC2'],2)*100 ggplot(data=pts, aes(x=PC1, y=PC2, color=trt,label=rownames(pts))) + geom_point(size=4) + xlab(paste('PC1 = ',PC1,'%',sep='')) + ylab(paste('PC2 = ',PC2,'%',sep='')) + ggtitle('Oxic vs. Anoxic, Bicarbonate') + scale_color_manual(values=beyonce_palette(21, 2, type='continuous'))+ theme_gray() ggsave(filename = 'Oxic vs. Anoxic bicarbonate.pdf', device = 'pdf', width=8, height=8) ##-- Oxic Bicarbonate vs. Anoxic Myo-Inositol --## xdf<-df.merged[which(df.merged$Treatment=='Myo_Inositol C_D6'),] X<-xdf[,sapply(xdf,is.numeric)] X<-X[,apply(X, 2, var, na.rm=TRUE) != 0] ## Removes columns with constant variance Y<-xdf$Factor1 pca<-prcomp(X,center = T, scale=T); pts<-data.frame(pca$x,trt=as.factor(Y)) PC1<-signif(summary(pca)$importance['Proportion of Variance','PC1'],2)*100; PC2<-signif(summary(pca)$importance['Proportion of Variance','PC2'],2)*100 ggplot(data=pts, aes(x=PC1, y=PC2, color=trt,label=rownames(pts))) + geom_point(size=4) + xlab(paste('PC1 = ',PC1,'%',sep='')) + ylab(paste('PC2 = ',PC2,'%',sep='')) + ggtitle('Oxic vs. Anoxic, Myo-inositol') + scale_color_manual(values=beyonce_palette(21, 2, type='continuous'))+ theme_gray() ggsave(filename = 'Oxic vs. Anoxic Myoinositol.pdf', device = 'pdf', width=8, height=8) #########--------------------------------------------------- ## COMPARE PROFILES ACROSS TIME WITHIN SUCROSE EXPERIMENT ## Peak Picking setwd(file.path(dir, 'Data','April_2016','GCMS','General','Oxic','Sucrose')) files<-list.files(pattern='.CDF', recursive = T, full.names=T) # select datafiles gcrunTime<-runGC(files = files, settings = TSXLS.GC.custom,findUnknowns = T,DB=DB) setwd(file.path(dir,"Results")) save(gcrunTime,file = 'gcrun_time_sucrose_oxic.R') ## Set up peak table peaks<-gcrunTime$PeakTable; peaks[1:10,1:10] ribitol<-peaks[which(peaks$Name=='Ribitol 5TMS'),grep('X',colnames(peaks))] cholestane<-peaks[which(peaks$Name=='Cholestane 1TMS'),grep('X',colnames(peaks))] peaks.dd<-peaks[,grep('X',colnames(peaks))] dd<-sweep(peaks.dd, MARGIN = 2, STATS = as.numeric(as.vector(ribitol)),FUN = '/') ## normalizes to ribitol area dd<-dd[,complete.cases(colSums(dd))] ## removes spectra without ribitol --> check these on machine head(dd) df<-data.frame(t(dd)) ## Normalized dataframe colnames(df)<-peaks$Name df<-df[,apply(df, 2, var, na.rm=TRUE) != 0] ## Removes columns with constant variance df<-df[,-which(colnames(df)=='Cholestane 1TMS')] ## Removes cholestane head(df) ##---- Data Quality Check/Exploration par(mfrow=(c(1,3))) rib<-as.numeric(as.vector(ribitol)); cho<-as.numeric(as.vector(cholestane)) barplot(height=rib,names.arg = colnames(ribitol), main="ribitol", ylab='Ion Intensity', cex.names=0.5, las=2) barplot(height=cho,names.arg = colnames(cholestane), main="Cholestane", ylab='Ion Intensity', cex.names=0.5, las=2) barplot(height=rib/cho,names.arg = colnames(cholestane), main="ribitol/cholestane", ylab='Ion Intensity', cex.names=0.5, las=2) abline(h=0.2, col='red') ## Remove samples with poor QC (rib / cho < 0.5) samps<-colnames(cholestane)[which(rib/cho > 0.5)] df.reduced<-df[rownames(df) %in% samps,] dim(df.reduced) ##---- Set up datatable with metadata df.reduced$File<-gsub("X",'',rownames(df.reduced)) vars<-c('Treatment','Factor1','TargetTimePoint_hours','File') df.merged<-merge(metadata[,colnames(metadata) %in% vars],df.reduced,'File') df.merged$TargetTimePoint_hours<-as.factor(df.merged$TargetTimePoint_hours) head(df.merged[,1:10]); dim(df.merged) df.merged$Treatment<-as.vector(df.merged$Treatment) ##----- Statistical Comparisions myCols<-beyonce_palette(40, length(unique(df.merged$TargetTimePoint_hours)), type='discrete') names(myCols)<-levels(df.merged$Treatment) colScale <- scale_colour_manual(name = "Treatment",values = myCols) ## PCA ## -- treatment comparison --- ## X<-df.merged[,sapply(df.merged,is.numeric)] ## selects only data columns Y<-df.merged$TargetTimePoint_hours pca<-prcomp(X,center = T, scale=T); pts<-data.frame(pca$x,tp=as.factor(Y)) neworder<-c('1','3','24','48') pts<-arrange(transform(pts,tp=factor(tp,levels=neworder)),tp) ## re-order to make plot pretty / match up PC1<-signif(summary(pca)$importance['Proportion of Variance','PC1'],2)*100; PC2<-signif(summary(pca)$importance['Proportion of Variance','PC2'],2)*100 ggplot(data=pts, aes(x=PC1, y=PC2, color=tp, label=rownames(pts))) + geom_point(size=6) + xlab(paste('PC1 = ',PC1,'%',sep='')) + ylab(paste('PC2 = ',PC2,'%',sep='')) + ggtitle('Sucrose, Oxic') + colScale + theme_gray() ggsave(filename = 'Sucrose Across Time.pdf', device = 'pdf', width=8, height=8) ######################################################################## ## X13CMS ANALYSIS library(vegan); library(ggplot2); library(beyonce); library(xcms); library(X13CMS) ## Select files of interest ## Sucrose Data setwd(file.path(dir, 'Data','April_2016','GCMS','isotope','Sucrose')) #48 hr samples in 12C folder files<-list.files(pattern='.CDF', recursive = T, full.names=T) # select datafiles ## Redo peak picking xs<-xcmsSet(files=files,snthresh=2,max=100,step=0.1, steps=2, fwhm=5, mzdiff=1, method='matchedFilter') xs1<-group(xs,method='density', minfrac=1) xs1<-retcor(xs1, family='s', plottype='deviation') xs2<-group(xs1,method='density', minfrac=1) xs2<-fillPeaks(xs2) xsa<-xsAnnotate(xs2) xsa.g<-groupFWHM(xsa, perfwhm=2) xset<-xsa.g@xcmsSet # Setting variables for X13CMS sN = rownames(xset@phenoData) # sample names # labeling report for control samples: labelsCtrl <- getIsoLabelReport(xcmsSet = xset, sampleNames = sN, unlabeledSamples = "12C", labeledSamples = "13C", isotopeMassDiff = 1.00335, RTwindow = 10, ppm = 50, massOfLabeledAtom = 12, noiseCutoff = 10000, intChoice = "maxo", varEq = FALSE, alpha = 0.05, singleSample = FALSE, compareOnlyDistros = F, monotonicityTol = FALSE, enrichTol = 0.1) classes <- as.vector(xs2@phenoData$class) setwd(file.path(dir,'Results')) plotLabelReport(isoLabelReport = labelsCtrl, intOption = "rel", classes, labeledSamples = "13C", outputfile = "Sucrose-Incubation-Isotopes-48hr.pdf") printIsoListOutputs(listReport = labelsCtrl, outputfile = "isotope-sucrose-results-48hr.txt") ## Bicarbonate Data setwd(file.path(dir, 'Data','April_2016','GCMS','isotope','Bicarbonate')) #now with both 24 hr and 48 hr samples in 12C folder files<-list.files(pattern='.CDF', recursive = T, full.names=T) # select datafiles ## Redo peak picking xs<-xcmsSet(files=files,snthresh=2,max=100,step=0.1, steps=2, fwhm=30, mzdiff=1, method='matchedFilter') xs1<-group(xs,minfrac=1,mzwid=0.1,method='density') xs1<-retcor(xs1, plottype='m') xs2<-group(xs1,minfrac=1,mzwid=0.1,method='density') xs2<-fillPeaks(xs2) xsa<-xsAnnotate(xs2) xsa.g<-groupFWHM(xsa, perfwhm=2) xset<-xsa.g@xcmsSet # Setting variables for X13CMS sN = rownames(xset@phenoData) # sample names # labeling report for control samples: labelsCtrl <- getIsoLabelReport(xcmsSet = xset, sampleNames = sN, unlabeledSamples = "12C", labeledSamples = "13C", isotopeMassDiff = 1.00335, RTwindow = 10, ppm = 50, massOfLabeledAtom = 12, noiseCutoff = 10000, intChoice = "maxo", varEq = FALSE, alpha = 0.05, singleSample = FALSE, compareOnlyDistros = F, monotonicityTol = FALSE, enrichTol = 0.1) classes <- as.vector(xset@phenoData$class) setwd(file.path(dir,'Results')) plotLabelReport(isoLabelReport = labelsCtrl, intOption = "rel", classes, labeledSamples = "13C", outputfile = "Bicarbonate-Incubation-Isotopes-48hr.pdf") printIsoListOutputs(listReport = labelsCtrl, outputfile = "bicarbonate-isotope-results-48hr.txt") ## Myo-Inositol Data setwd(file.path(dir, 'Data','April_2016','GCMS','isotope','Sucrose')) #now with both 24 hr and 48 hr samples in 12C folder files<-list.files(pattern='.CDF', recursive = T, full.names=T) # select datafiles ## Redo peak picking xs<-xcmsSet(files=files,snthresh=2,max=100,step=0.1, steps=2, fwhm=30, mzdiff=1, method='matchedFilter') xs1<-group(xs,minfrac=1,mzwid=0.1,method='density') xs1<-retcor(xs1, plottype='m') xs2<-group(xs1,minfrac=1,mzwid=0.1,method='density') xs2<-fillPeaks(xs2) xsa<-xsAnnotate(xs2) xsa.g<-groupFWHM(xsa, perfwhm=2) xset<-xsa.g@xcmsSet # Setting variables for X13CMS sN = rownames(xset@phenoData) # sample names # labeling report for control samples: labelsCtrl <- getIsoLabelReport(xcmsSet = xset, sampleNames = sN, unlabeledSamples = "12C", labeledSamples = "13C", isotopeMassDiff = 1.00335, RTwindow = 10, ppm = 50, massOfLabeledAtom = 1, noiseCutoff = 10000, intChoice = "maxo", varEq = FALSE, alpha = 0.05, singleSample = FALSE, compareOnlyDistros = F, monotonicityTol = FALSE, enrichTol = 0.1) classes <- as.vector(xset@phenoData$class) setwd(file.path(dir,'Results')) plotLabelReport(isoLabelReport = labelsCtrl, intOption = "rel", classes, labeledSamples = "13C", outputfile = "MyoInositol-Incubation-Isotopes-48hr.pdf") printIsoListOutputs(listReport = labelsCtrl, outputfile = "MyoInositol-sucrose-results-48hr.txt")
9bd8c06b11dcb9cbafef7f6ae313574b573a6eea
[ "R" ]
5
R
esogin/organicC-worm-uptake
f2d298a5d0ca0d89a2bff7467dab849b946791c0
d1300356362d8e564bf322ac13af720534000f99
refs/heads/master
<file_sep>import numpy as np import pandas as pd import json from flask import Flask, abort, jsonify, request import _pickle as pickle from sklearn import utils from sklearn.linear_model import LogisticRegression import gensim import gensim.models.doc2vec as doc2vec from gensim.models.doc2vec import Doc2Vec from gensim.models.doc2vec import TaggedDocument import re # pickled multiple regression model logreg = pickle.load(open('logreg.pkl','rb')) model_dbow = Doc2Vec.load('doc2vec_model.pkl') application = app = Flask(__name__) # AWS EBS expects variable name "application" @app.route('/api', methods=['POST']) def make_predict(): # read in data lines = request.get_json(force=True) # get variables title = lines['title'] body = lines['body'] image = lines['image'] # not sure what to do with this yet # combine text = title + ' ' + body text = re.sub(r'http\S+|www.\S+', 'link', text) text = list(text) # label sentences so doc2vec doesn't hate us def label_sentences(corpus, label_type): """ Gensim's Doc2Vec implementation requires each document/paragraph to have a label associated with it. We do this by using the TaggedDocument method. The format will be "TRAIN_i" or "TEST_i" where "i" is a dummy index of the post. """ labeled = [] for i, v in enumerate(corpus): label = label_type + '_' + str(i) labeled.append(doc2vec.TaggedDocument(v.split(), [label])) return labeled # function to vectorize input data def get_vectors(model, corpus_size, vectors_size, vectors_type): """ Get vectors from trained doc2vec model :param doc2vec_model: Trained Doc2Vec model :param corpus_size: Size of the data :param vectors_size: Size of the embedding vectors :param vectors_type: Training or Testing vectors :return: list of vectors """ vectors = np.zeros((corpus_size, vectors_size)) for i in range(0, corpus_size): prefix = vectors_type + '_' + str(i) vectors[i] = model.docvecs[prefix] return vectors # prep text for prediction user_input = model_dbow.infer_vector(text, steps=20).reshape(1, -1) # make prediction and convert it to list so that jsonify is happy output = pd.DataFrame(logreg.predict_proba(user_input), columns=logreg.classes_).T.nlargest(5, [0])[0].reset_index().values.tolist() # send back the top 5 subreddits and their associated probabilities return jsonify(top_five = output) if __name__ == '__main__': app.run(port = 8080, debug = True)<file_sep># Post Here: The Subreddit Predictor This project is a part of the Lambda School Build Week April 2019 -- Project Status: [Completed] # Project Intro/Objective Post Here helps you find the best place to share your post on Reddit. The user enters their post and Post Here finds the subreddit that is most appropriate for that post using data science methods. # Methods Used Natural Language Processing Predictive Modeling # Technologies - AWS - PRAW ## Python Libraries - SpaCy - Sci-kit Learn - NLTK - String - Flask - Pickle - Re - Pandas - URLlib # Needs of this project Frontend developer to provide a layout for theme/color scheme, integrating content and creating user form for input. Backend developer for securing endpoints, authenticated login, and routing user input and output of DS API. Access to AWS to host Flask app with API and Reddit post data. Data exploration/descriptive statistics Data processing/cleaning Word vectorizing Statistical modeling # Getting Started Clone this repo If you want more recent data you will need to: - Request access to Reddit API: https://docs.google.com/forms/d/e/1FAIpQLSezNdDNK1-P8mspSbmtC2r86Ee9ZRbC66u929cG2GX0T9UMyw/viewform - Pull posts from the Reddit API using PRAW and store in a database or a csv file. - Retrain the model and create a new .pkl file. You can host the Flask app locally or use another platform like AWS.
558b5b3f9cba5c3733accab5cc120db9e6db9367
[ "Markdown", "Python" ]
2
Markdown
lambda-post-here/build-post-here-DS
db47f58d6c502a071997d6d19774817359e18b64
d8286528556eb6bba158d3c7d1a48b2d9505da6f
refs/heads/master
<repo_name>teachteamgithub/Industry-Accelerator-Education<file_sep>/README.md # Microsoft Dynamics 365 Announces Industry Accelerators Dynamics 365 announced the Microsoft Power Platform, a connected app platform that unifies access to your data to enable ISVs, SIs, Partners and Customers to build intelligent, data driven, task focused business and analytic applications. Microsoft is focused on enabling a data culture where the Microsoft Power Platform acts as the glue across Dynamics 365 (CE, F&O, Talent), Office 365 (SharePoint, Teams), Power BI, Power Apps, Microsoft Flow, Azure and other 3rd party on-premise and cloud based solutions. With the Power Platform providing a unified approach to building data driven solutions, the team is taking it one step further by introducing Industry Solution Accelerators. Accelerators are industry focused foundational components that enable ISVs and other solution providers, a way to build solutions that are based on industry standards supported and driven by Microsoft. Along with our Health Accelerator that was released during Inspire 2018, which you can read about here, we are focused on delivering accelerators for the following industries (but not limited too): ## Overview of the Industry Higher Education Accelerator The Microsoft Higher Education Accelerator is the second Industry Accelerator from Microsoft following the release of the Healthcare Accelerator earlier this summer. Industry Accelerators are foundation components within the Microsoft Power platform and Dynamics 365 that enable ISVs and other solution providers to quickly build industry vertical solutions. The Higher Education data model, solutions, data samples, Power BI examples, SDK extensions, and more are provided as part of the open source creative license and available on GitHub. The development of the Higher Education model was done in collaboration with leading industry expert solution providers focused on Higher Education and Microsoft is committed to working with the higher education community to provide regular updates to Accelerator. The Higher Education Accelerator, Microsoft Power platform and Dynamics 365 provide the building blocks for ISVs to build solutions to address the unique needs in Higher Education. In this blog post, Iím delighted to highlight some of the early adopters of the Higher Education Accelerator. [Learn more](https://community.dynamics.com/365/b/dynamics365isvsuccess/archive/2018/10/30/early-isvs-building-on-the-new-higher-education-accelerator-and-the-microsoft-power-platform) ## Get to know about other Industry Accelerators | Industry Accelerators | Description | |-------------|----------------------| | [Industry Accelerator (Main)](https://github.com/Microsoft/Dynamics-365-Industry-Accelerators) | As we have moved and separated the repository, we will soon retire this repository.| | [Health Accelerator](https://github.com/Microsoft/Industry-Accelerator-Health) | Rapidly develop healthcare solutions using FHIR entities such as patient, condition, and care plan. The Microsoft Health Accelerator enables partners and customers to create new use cases and workflows using a FHIR-based data model. Get more details from [Dynamics 365 ISV Success community](https://community.dynamics.com/365/b/dynamics365isvsuccess)| | [Nonprofit Accelerator](https://github.com/Microsoft/Industry-Accelerator-Nonprofit) | Rapidly develop nonprofit fundraising, grant/award and program/results management solutions.The Microsoft Nonprofit Accelerator enables partners and customers to create new integrated use cases and workflows across the funding to outcomes cycle. Get more details from [Dynamics 365 ISV Success community](https://community.dynamics.com/365/b/dynamics365isvsuccess)| ## Contributing This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com. When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA. This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [<EMAIL>](mailto:<EMAIL>) with any additional questions or comments. ## License Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact <EMAIL> with any additional questions or comments.
5d4efe854c564c53c27feb97b634c246b2029430
[ "Markdown" ]
1
Markdown
teachteamgithub/Industry-Accelerator-Education
ad6a210e2d65fb58232142858224ef76fb3448dd
152dbe73015ab2b46db900681d78f9351406dab2
refs/heads/master
<file_sep>version: '2' volumes: unstructured_data: semistructured_data: services: logstash: build: ./logstash volumes: - command: bin/logstash -f pipeline/logstash.conf depends_on: - elasticsearch elasticsearch: build: ./elasticsearch ports: - 9200:9200 command: bin/elasticsearch <file_sep>FROM docker.elastic.co/logstash/logstash:6.2.4 ADD config/ /usr/share/logstash/config/ ADD pipeline/ /usr/share/logstash/pipeline/ ADD twitter.csv /tmp/logs/ WORKDIR /usr/share/logstash <file_sep># elastic_bi - logstash - elasticsearch ## gist (unstructuredData|semistructuredData) -> logstash -> elasticsearch ## memo https://github.com/KentFujii/loghub https://github.com/efkbook/blog-sample
15d763e8a9b5581d2794bd38669b7a28bf054bd0
[ "Markdown", "Dockerfile", "YAML" ]
3
Markdown
KentFujii/elastic_bi
09874ce5e161bb6a9b1e00b859b355fb2d2f1ff6
ca525a070c6126b3c053655ff63518c676fb4dc9
refs/heads/master
<file_sep># Complier For my Compiler Design class. Contains a basic code compiler
af99cfda9538e2ae01023c1225d292457bf8560c
[ "Markdown" ]
1
Markdown
yimmit303/Complier
e730804de51299d95a6b7fa2c52c9a2d36314d07
5b7123926b1c8036ddc4cf2660d7e0a632a07bf6
refs/heads/master
<file_sep>#include "tabledialog.h" tableDialog::tableDialog() { lableColumn = new QLabel(tr("&Column :")); lineEditColumn = new QLineEdit; lableColumn->setBuddy(lineEditColumn); lableRow = new QLabel(tr("&Row : ")); lineEditRow = new QLineEdit; lableRow->setBuddy(lineEditRow); okButton = new QPushButton(tr("OK")); okButton->setEnabled(false); closeButton = new QPushButton(tr("Close")); QHBoxLayout *topLeft = new QHBoxLayout; topLeft->addWidget(lableRow); topLeft->addWidget(lineEditRow); QHBoxLayout *bottomLeft = new QHBoxLayout; bottomLeft->addWidget(lableColumn); bottomLeft->addWidget(lineEditColumn); QVBoxLayout *left = new QVBoxLayout; left->addLayout(topLeft); left->addLayout(bottomLeft); QVBoxLayout *right = new QVBoxLayout; right->addWidget(okButton); right->addWidget(closeButton); QHBoxLayout *mainLayout = new QHBoxLayout; mainLayout->addLayout(left); mainLayout->addLayout(right); setLayout(mainLayout); connect(closeButton, SIGNAL(clicked()), this, SLOT(close())); connect(okButton, SIGNAL(clicked()), this, SLOT(dealOk())); connect(lineEditColumn, SIGNAL(textChanged(QString)), this, SLOT(enableOkButton(QString))); connect(lineEditRow, SIGNAL(textChanged(QString)), this, SLOT(enableOkButton(QString))); } void tableDialog::dealOk() { columnNumber = lineEditColumn->text().toInt(); rowNumber = lineEditRow->text().toInt(); emit insertTable(rowNumber, columnNumber); } void tableDialog::enableOkButton(QString text) { if(!(lineEditColumn->text().isEmpty() || lineEditRow->text().isEmpty())) okButton->setEnabled(!text.isEmpty()); } <file_sep>#include "demoWindow.h" demoWindow::demoWindow() { setWindowTitle(tr("Demo")); resize(QSize(800, 600)); cenWidget = new QWidget(this); text = new QTextEdit(cenWidget); createEdit(text); createTextDis(); //setCentralWidget(text); createActions(); createToolBars(); //initTrans(); createLayout(); Markdown = false; cenWidget->setLayout(mainLayout); this->setCentralWidget(cenWidget); firstTime = true; transProcess = new QProcess; } void demoWindow::createToolBars() { //fileTool = addToolBar(tr("File")); fileTool = new QToolBar(tr("File")); fileTool->addAction(save); fileTool->addAction(open); fileTool->addAction(font); fileTool->addAction(find); fileTool->addAction(openMarkdown); editTool = new QToolBar(tr("Edit")); editTool->addAction(bold); editTool->addAction(italic); editTool->addAction(underline); editTool->addAction(color); editTool->addAction(insertImg); editTool->addAction(table); } void demoWindow::createActions() { save = new QAction(tr("Save"),cenWidget); connect(save,SIGNAL(triggered()),this,SLOT(dealSave())); open = new QAction(tr("Open"),cenWidget); connect(open,SIGNAL(triggered()),this,SLOT(dealOpen())); font = new QAction(tr("Font"),cenWidget); connect(font, SIGNAL(triggered()), this, SLOT(dealFont())); find = new QAction(tr("find"), cenWidget); connect(find, SIGNAL(triggered()), this, SLOT(dealfind())); bold = new QAction(QIcon("./images/text-bold.png"),tr("Bold"),this); connect(bold, SIGNAL(triggered()), this, SLOT(dealBold())); italic = new QAction(QIcon("./images/italic.png"),tr("Italic"),this); connect(italic, SIGNAL(triggered()), this, SLOT(dealItalic())); underline = new QAction(QIcon("./images/underline.png"),tr("Unberline"),this); connect(underline, SIGNAL(triggered()), this, SLOT(dealUnderline())); color = new QAction(QIcon("./images/letter-c.png"),tr("Color"),this); connect(color, SIGNAL(triggered()), this, SLOT(dealColor())); insertImg = new QAction(QIcon("./images/image.png"),tr("inserImage"),this); connect(insertImg, SIGNAL(triggered()), this, SLOT(dealInsertImg())); table = new QAction(QIcon("./images/table.png"),tr("Table"), this); connect(table, SIGNAL(triggered()), this, SLOT(dealTable())); openMarkdown = new QAction(tr("Markdown"),this); connect(openMarkdown, SIGNAL(triggered()), this, SLOT(dealOpenMarkDown())); } void demoWindow::createEdit(QTextEdit *edit) { edit->setTabStopWidth(40); edit->setPlainText(tr("Title:\n")); QTextCursor cursor = edit->textCursor(); cursor.setPosition(6); edit->setTextCursor(cursor); edit->ensureCursorVisible(); QFont initFont; initFont.setPixelSize(20); initFont.setFamily("Droid Sans Mono"); edit->setFont(initFont); scrolltext = edit->verticalScrollBar(); } void demoWindow::createLayout() { mainLayout = new QGridLayout; mainLayout->addWidget(fileTool,0,0); mainLayout->addWidget(editTool,1,0); mainLayout->addWidget(text,2,0); } void demoWindow::createTextDis() { textDisplay = new QTextEdit; textDisplay-> setTabStopWidth(40); QFont initFont; initFont.setPixelSize(20); initFont.setFamily("Droid Sans Mono"); textDisplay->setFont(initFont); scrolltextDis = textDisplay->verticalScrollBar(); } demoWindow::~demoWindow() { delete text ; delete fileTool; delete editTool; delete save; delete open; delete bold; delete italic; delete font; delete underline; delete color; delete insertImg; delete find; delete table; delete mainLayout; delete cenWidget; delete finddialog; delete insertTable; //deal the diaplay sync delete scrolltext; delete scrolltextDis; delete transProcess; } void demoWindow::dealSave() { QStringList list = text->toPlainText().split("\n"); QString fileName = "/home/vergil/"+list[0]+".note"; fileName.remove("Title:"); QFile *file; file = new QFile(fileName); file->open(QIODevice::WriteOnly); QTextStream out(file); out << text->toHtml(); file->close(); } void demoWindow::dealOpen() { QString noteName = QFileDialog::getOpenFileName(this, tr("Open File"), "/home/vergil", tr("Notes (*.note *.txt)")); QFile *file; file = new QFile(noteName); file->open(QIODevice::ReadOnly); text->clear(); QByteArray data = file->readAll(); QTextCodec *codec = Qt::codecForHtml(data); QString str = codec->toUnicode(data); if (Qt::mightBeRichText(str)) { text->setHtml(str); } else { str = QString::fromLocal8Bit(data); text->setPlainText(str); } } void demoWindow::dealBold() { QTextCursor cursor = text->textCursor(); QTextCharFormat format; format.setFontWeight(QFont::Bold); cursor.mergeCharFormat(format); } void demoWindow::dealItalic() { QTextCursor cursor = text->textCursor(); QTextCharFormat format; format.setFontItalic(true); cursor.mergeCharFormat(format); } void demoWindow::dealUnderline() { QTextCursor cursor = text->textCursor(); QTextCharFormat format; format.setFontUnderline(true); cursor.mergeCharFormat(format); } void demoWindow::dealColor() { QTextCursor cursor = text->textCursor(); QColor col = QColorDialog::getColor(text->textColor(), this); if (!col.isValid()) return; QTextCharFormat fmt; fmt.setForeground(col); cursor.mergeCharFormat(fmt); } void demoWindow::dealInsertImg() { QString file = QFileDialog::getOpenFileName(this, tr("Select an image"), ".", tr("Bitmap Files (*.bmp)/n" "JPEG (*.jpg *jpeg)/n" "GIF (*.gif)/n" "PNG (*.png)/n")); QUrl Uri ( QString ( "file://%1" ).arg ( file ) ); QImage image = QImageReader ( file ).read(); QTextDocument * textDocument = text->document(); textDocument->addResource( QTextDocument::ImageResource, Uri, QVariant ( image ) ); QTextCursor cursor = text->textCursor(); QTextImageFormat imageFormat; imageFormat.setWidth( image.width() ); imageFormat.setHeight( image.height() ); imageFormat.setName( Uri.toString() ); cursor.insertImage(imageFormat); } void demoWindow::dealfind() { finddialog = new findDialog(); finddialog->show(); connect(finddialog, SIGNAL(findNext(QString,Qt::CaseSensitivity)), this, SLOT(dealFindText(QString,Qt::CaseSensitivity))); } void demoWindow::dealFindText(const QString &str, Qt::CaseSensitivity cs) { QTextDocument *doc = text->document(); bool found = false; if (firstTime == false) doc->undo(); QTextCursor highlightCursor(doc); QTextCursor cursor(doc); // QString test = doc->toPlainText(); cursor.beginEditBlock(); QTextCharFormat plainFormat(highlightCursor.charFormat()); QTextCharFormat colorFormat = plainFormat; colorFormat.setForeground(Qt::red); while (!highlightCursor.isNull() && !highlightCursor.atEnd()) { highlightCursor = doc->find(str, highlightCursor, QTextDocument::FindWholeWords); if (!highlightCursor.isNull()) { found = true; highlightCursor.movePosition(QTextCursor::WordRight, QTextCursor::KeepAnchor); highlightCursor.mergeCharFormat(colorFormat); } } cursor.endEditBlock(); firstTime = false; if (found == false) { QMessageBox::information(this, tr("Word Not Found"), "Sorry, the word cannot be found."); } } void demoWindow::dealTable() { insertTable = new tableDialog; insertTable->show(); connect(insertTable, SIGNAL(insertTable(int,int)), this, SLOT(dealInsertTable(int,int))); //text->insertHtml("<html><table border=\"1\"><tr><th>Month</th><th>Savings</th></tr><tr><td>January</td><td>$100</td></tr></table></html>"); } void demoWindow::dealInsertTable(int row, int column) { QString html; html = "<html><table border=\"1\">"; for(int i = 0; i < row; i++){ html += "<tr>"; for(int j = 0; j< column; j++){ html += "<th>&nbsp;&nbsp;&nbsp;&nbsp;</th>"; } html += "</tr>"; } html += "</table></html>"; text->insertHtml(html); } void demoWindow::dealDisplaySync(int positon) { int maxInDisWindow = scrolltextDis->maximum(); int maxInEditWindow = scrolltext->maximum(); int newPos = int(positon/maxInEditWindow*maxInDisWindow); scrolltextDis->setValue(newPos); } void demoWindow::dealTranslate() { QString fileName = "/home/vergil/trans.md"; QFile transFrom (fileName); transFrom.open(QIODevice::WriteOnly); QTextStream textout(&transFrom); textout << text->toPlainText(); transFrom.close(); QString command = "pandoc -t html /home/vergil/trans.md"; transProcess->start(command); transProcess->waitForFinished(); QByteArray data = transProcess->readAllStandardOutput(); QString str = Qt::codecForHtml(data)->toUnicode(data); if (Qt::mightBeRichText(str)) { textDisplay->clear(); textDisplay->setHtml(str); } else { str = QString::fromLocal8Bit(data); textDisplay->clear(); textDisplay->setPlainText(str); } } void demoWindow::dealOpenMarkDown() { bool markd = Markdown; if(markd == false){ textDisplay = new QTextEdit; textDisplay-> setTabStopWidth(40); QFont initFont; initFont.setPixelSize(20); initFont.setFamily("Droid Sans Mono"); textDisplay->setFont(initFont); scrolltextDis = textDisplay->verticalScrollBar(); mainLayout->addWidget(textDisplay,2,1); connect(text, SIGNAL(textChanged()), this, SLOT(dealTranslate())); connect(scrolltext ,SIGNAL(valueChanged(int)), this, SLOT(dealDisplaySync(int))); } else { mainLayout->removeWidget(textDisplay); textDisplay->deleteLater(); disconnect(text, SIGNAL(textChanged()), this, SLOT(dealTranslate())); disconnect(scrolltext ,SIGNAL(valueChanged(int)), this, SLOT(dealDisplaySync(int))); } Markdown = !markd; } void demoWindow::dealFont() { QTextCursor cursor = text->textCursor(); QTextCharFormat format; bool ok; QFont font = QFontDialog::getFont( &ok, this ); if ( ok ) { format.setFont(font); cursor.mergeCharFormat(format); } } <file_sep>#ifndef TABLEDIALOG #define TABLEDIALOG #include <QDialog> #include <QLabel> #include <QPushButton> #include <QLineEdit> #include <QLayout> #include <QString> class tableDialog : public QDialog{ Q_OBJECT public: tableDialog(); private slots: void dealOk(); void enableOkButton(QString text); signals: void insertTable(int row, int column); private: QLineEdit *lineEditRow; QLineEdit *lineEditColumn; QPushButton *okButton; QPushButton *closeButton; QLabel *lableRow; QLabel *lableColumn; int rowNumber; int columnNumber; }; #endif // TABLEDIALOG <file_sep>#include <QApplication> #include <QDesktopWidget> #include "demoWindow.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); demoWindow * demo; demo = new demoWindow(); demo->show(); demo->move((QApplication::desktop()->width() - demo->width())/2, (QApplication::desktop()->height() - demo->height())/2); return a.exec(); } <file_sep>#ifndef DEMOWINDOW_H #define DEMOWINDOW_H #include <QMainWindow> #include <QFile> #include <QTextEdit> #include <QToolBar> #include <QAction> #include <QTextStream> #include <QTextCursor> #include <QFileDialog> #include <QLayout> #include <QWidget> #include <QFontDialog> #include <QTextDocumentWriter> #include <QTextCodec> #include <QColorDialog> #include <QImage> #include <QImageReader> #include <QMessageBox> #include <QScrollBar> #include <QProcess> #include <iostream> #include "finddialog.h" #include "tabledialog.h" class demoWindow : public QMainWindow{ Q_OBJECT public: demoWindow(); void createToolBars(); void createActions(); void createEdit(QTextEdit *edit); void createLayout(); void createTextDis(); void dealSignals(); ~demoWindow(); public slots: void dealSave(); void dealOpen(); void dealBold(); void dealItalic(); void dealFont(); void dealUnderline(); void dealColor(); void dealInsertImg(); void dealfind(); void dealFindText(const QString &str, Qt::CaseSensitivity cs); void dealTable(); void dealInsertTable(int row, int column); void dealDisplaySync(int); void dealTranslate(); void dealOpenMarkDown(); private: QTextEdit *text ; QTextEdit *textDisplay; QToolBar *fileTool; QToolBar *editTool; QAction *save; QAction *open; QAction *bold; QAction *italic; QAction *font; QAction *underline; QAction *color; QAction *insertImg; QAction *find; QAction *table; QAction *openMarkdown; QGridLayout *mainLayout; QWidget *cenWidget; findDialog *finddialog; tableDialog *insertTable; bool firstTime; bool Markdown; //deal the diaplay sync QScrollBar *scrolltext; QScrollBar *scrolltextDis; QProcess *transProcess; //QFile *transFrom; }; #endif // DEMOWINDOW_H <file_sep>#------------------------------------------------- # # Project created by QtCreator 2015-08-14T21:13:06 # #------------------------------------------------- QT += core QT += gui QT += widgets TARGET = demo CONFIG += console TEMPLATE = app SOURCES += main.cpp \ demoWindow.cpp \ finddialog.cpp \ tabledialog.cpp HEADERS += \ demoWindow.h \ finddialog.h \ tabledialog.h
af51e2b609f3072ee1a7a1308a0b14799d9aec1a
[ "C++", "QMake" ]
6
C++
vergil5750/QMarkDown
8c7e37b4072fa50437db7a43ddfe4223e00f51f8
cd0c8728142d90118e835349894959c5681a1c60
refs/heads/master
<repo_name>DotBowder/fudge<file_sep>/README.md # fudge ***Summary:*** <br> An application for skewing image color. Go ahead, hold your mouse click down... ***Required Software:*** <br> processing js <br> http://processingjs.org/ ***Required Code Config:*** <br> Place an image in the directory you are running fudge from. In the Setup function,insert the image name into the loadImage function, and, change the size function values to be (2 * width of image, height of image). <pre> size(2258, 750); img_before = loadImage("img.jpg"); </pre> ***Inspiration:*** <br> YouTube Coding Train Challenge #90: Floyd-Steinberg Dithering <br> https://www.youtube.com/watch?v=0L2n8Tg2FwI Every pixel is adjusted based on the values of the pixels around it. As the pixel dist value is adjusted by holding the mouse click, the red, green, and blue colors of the image are dispersed into different directions. <pre> RED [p1r * 1/8],[p2r * 2/8],[p3r * 3/8] [p4r * 4/8],[ new val ],[p5r * 5/8] [p6r * 6/8],[p7r * 7/8],[p8r * 8/8] GREEN [p1r * 4/8],[p2r * 5/8],[p3r * 6/8] [p4r * 7/8],[ new val ],[p5r * 8/8] [p6r * 1/8],[p7r * 2/8],[p8r * 3/8] BLUE [p1r * 8/8],[p2r * 7/8],[p3r * 6/8] [p4r * 5/8],[ new val ],[p5r * 4/8] [p6r * 3/8],[p7r * 2/8],[p8r * 1/8] PIXEL MAP: [p1] [p2] [p3] [p4] [p ] [p5] [p6] [p7] [p8] [x - dist, y - dist] [ x, y - dist] [x + dist, y - dist] [x - dist, y ] [ val ] [x + dist, y ] [x - dist, y + dist] [ x, y + dist] [x + dist, y + dist] </pre> ![Example](https://raw.githubusercontent.com/DotBowder/fudge/master/example/End.png) <file_sep>/fudge.pde PImage img_before; PImage img_after; int dist = 4; void setup() { // Set Window Size size(2880, 1000); // Load Image img_before = loadImage("img.jpg"); // Draw Original Image image(img_before, 0, 0); // Generate New image updateImages(); } int index(int x, int y) { return x + y * img_after.width; } void updateImages() { // Blank the distorted image img_after = createImage(img_before.width, img_before.height, RGB); // Loop through pixels. img_after.loadPixels(); for (int y = 1 + dist; y < img_after.height - dist; y++) { for (int x = 1 + dist; x < img_after.width - dist; x++) { // Center Pixel int i = index(x,y); color p = img_before.pixels[i]; float r = red(p); float g = green(p); float b = blue(p); // Pixel 1 int i1 = index(x,y-dist); color p1 = img_before.pixels[i1]; float p1r = red(p1); float p1g = green(p1); float p1b = blue(p1); // Pixel 2dist int i2 = index(x+dist,y-dist); color p2 = img_before.pixels[i2]; float p2r = red(p2); float p2g = green(p2); float p2b = blue(p2); // Pixel 3 int i3 = index(x-dist,y); color p3 = img_before.pixels[i3]; float p3r = red(p3); float p3g = green(p3); float p3b = blue(p3); // Pixel 4 int i4 = index(x,y); color p4 = img_before.pixels[i4]; float p4r = red(p4); float p4g = green(p4); float p4b = blue(p4); // Pixel 5 int i5 = index(x+dist,y); color p5 = img_before.pixels[i5]; float p5r = red(p5); float p5g = green(p5); float p5b = blue(p5); // Pixel 6 int i6 = index(x-dist,y+dist); color p6 = img_before.pixels[i6]; float p6r = red(p6); float p6g = green(p6); float p6b = blue(p6); // Pixel 7 int i7 = index(x,y+dist); color p7 = img_before.pixels[i7]; float p7r = red(p7); float p7g = green(p7); float p7b = blue(p7); // Pixel 8 int i8 = index(x+dist,y+dist); color p8 = img_before.pixels[i8]; float p8r = red(p8); float p8g = green(p8); float p8b = blue(p8); // Distort the r, g, b values float r_new_unscaled = p1r * (1/8) + p2r * (2/8) + p3r * (3/8) + p4r * (4/8) + p5r * (5/8) + p6r * (6/8) + p7r * (7/8) + p8r * (8/8); float g_new_unscaled = p1r * (4/8) + p2r * (5/8) + p3r * (6/8) + p4r * (7/8) + p5r * (8/8) + p6r * (1/8) + p7r * (2/8) + p8r * (3/8); float b_new_unscaled = p1r * (8/8) + p2r * (7/8) + p3r * (6/8) + p4r * (5/8) + p5r * (4/8) + p6r * (3/8) + p7r * (2/8) + p8r * (1/8); // If the Distortion needs to be scaled, we can adjust the following scale values. // We want the output, the end, from 0 to 255. float min_start = 0; float max_start = 255; float min_end = 0; float max_end = 255; // Scale the r, g, b values after distortion, mapping them from 0 to 255 int r_new = round(map(r_new_unscaled, min_start, max_start, min_end, max_end)); int g_new = round(map(g_new_unscaled, min_start, max_start, min_end, max_end)); int b_new = round(map(b_new_unscaled, min_start, max_start, min_end, max_end)); // Set the new Pixel Value for x, y img_after.pixels[index(x,y)] = color(r_new, g_new, b_new); } } img_after.updatePixels(); } void draw() { if (mousePressed && (mouseButton == LEFT)) { if (dist < 250) { dist += 1; updateImages(); } } else if (mousePressed && (mouseButton == RIGHT)) { if (dist > 1) { dist -= 1; updateImages(); } } // Draw images again image(img_before, 0, 0); image(img_after, img_before.width, 0); }
7a8501f3a53a627633669b000a4d76b20f10a422
[ "Processing", "Markdown" ]
2
Processing
DotBowder/fudge
65dea6a3def9d12ebbeaf9c8d01a28eb4e26a6f7
8843b83e35a0bbd5b7c17df25b16a0b69e1b20ea
refs/heads/master
<repo_name>paulopalacio1/Crud_Cadastro_Clientes<file_sep>/frontendd/projeto/src/styles/global.js import { createGlobalStyle } from 'styled-components' export default createGlobalStyle` @import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@100;200;400;500;600&display=swap'); *body /* CSS reset */ *, *:before, *:after { margin:0; padding:0; font-family: 'Montserrat', sans-serif;; } body{ margin:0px; background-color:rgb(247, 247, 247); } a{ text-decoration: none; } /* content que contem os formulários */ .content{ margin: 0px auto; position: relative; } /* formatando o cabeçalho dos formulários */ header{ margin: 0px auto; position: relative; background-color:#066a75; height: 100px; text-align: center; padding: 20px; } h1{ font-size: 48px; color: blanchedalmond; padding: 10px 0; font-family: 'montserrat'; font-weight: 200; text-align: center; padding-bottom: 30px; } .caixa{ max-width:600px; margin: 0px auto; position: relative; align-items:center; } .caixa1{ background: white; margin: 40px auto; max-width: 350px; min-height: 10vw; box-shadow: 5px 5px 10px rgba(49, 38, 25, 0.5); padding: 2rem; border-radius: 8px; } p{ margin-bottom:4px; font-weight:200; font-size: 10px; } p:first-child{ margin: 0px; } /**** advanced input styling ****/ /* placeholder */ form{ display: flex; flex-direction: column; } form .input-field{ position: relative; } form .input-field{ margin-bottom: 1.5rem; } .input-field .underline::before { content: ''; position: absolute; height: 2px; width: 100%; bottom: -5px; left: 0; background: rgba(94, 75, 53, 0.2); } .input-field .underline::after { content: ''; position: absolute; height: 2px; width: 100%; bottom: -5px; left: 0; background: linear-gradient(45deg, rgb(187, 170, 152), rgb(94, 75, 53) ); transform: scaleX(0); transition: all .3s ease-in-out; transform-origin: left; } .input-field input:focus ~ .underline::after { transform: scaleX(1); } .input-field input::placeholder { color: #066a75; } .input-field input[type='text']{ outline:none; font-size: 0.9rem; color: #066a75 ; } input:not([type="checkbox"]){ width:90%; margin-top: 4px; padding: 10px; border: 0px; background-color: white; outline: none; } /*estilo do botão submit */ input[type="submit"]{ width: 90%!important; cursor: pointer; background: #066a75; padding: 8px 5px; color: #fff; font-size: 20px; border: 1px solid #fff; margin-bottom: 10px auto; text-shadow: 0 1px 1px #333; -webkit-border-radius: 10px; border-radius: 10px; transition: all 0.2s linear; } input[type="submit"]:hover{ background: #088896; } /* estilos para o formulário */ #cadastro, #login{ -webkit-animation-duration: 0.5s; -webkit-animation-timing-function: ease; -webkit-animation-fill-mode: both; animation-duration: 0.5s; animation-timing-function: ease; animation-fill-mode: both; } .adiciona{ padding: 10px; border-radius: 10px; width: 250px; margin: 10px auto; color:white; font-size: 20px; color:white; text-align:center; background: #066a75; text-decoration: none; } .adiciona:hover{ background: #088896; } .link{ padding: 8px 5px; color: #fff; font-size: 20px; margin-bottom: 10px auto; text-shadow: 0 1px 1px #333; } table { font-weight: 400; min-width: 420px; width: 100%; margin: 40px auto; background-color: white; thead { display: none; font-weight: 500; color:#066a75; } tbody { box-shadow: 5px 5px 10px rgba(49, 38, 25, 0.5); tr { border: 1px solid #dad6eb; border-radius: 5px; display: block; padding: 30px; margin-bottom: 30px; td { display: block; font-weight: 500; padding: 5px; position: relative; text-align: right; color: #066a75; button { background: #066a75; border: none; border-radius: 5px; box-shadow: 0 4px 8px transparentize(#222, .8); bottom: -30px; color: #fff; font-weight: 700; left: 50%; padding: 10px 0; position: absolute; transform: translate(-50%, 50%); width: 50%; margin:3px; &:hover, &:focus { background: lighten(#927cfe, 5%); cursor: pointer; } } } } } } @media all and (min-width: 768px) { table { border: 1px solid #eee; border-collapse: collapse; max-width: 992px; text-align: left; width: 100%; thead { display: table-header-group; th { padding: 10px; } } tbody { font-size: .875em; tr { border: none; display: table-row; &:nth-child(odd) { background: #eee; } td { display: table-cell; font-weight: 400; padding: 10px; text-align: left; button { display: inline-block; padding: 10px 15px; position: initial; transform: translate(0); width: auto; } &:before { display: none; } &:last-child { text-align: right; } } } } } } `;<file_sep>/backend/app/controllers/controller.js const db = require('../config/db.config.js'); const Cliente = db.Cliente; exports.createCliente = (req, res) => { let cliente = {}; try{ // Building Customer object from upoading request's body cliente.nome = req.body.nome; cliente.idade = req.body.idade; cliente.email = req.body.email; // Save to MySQL database Cliente.create(cliente, {attributes: ['id', 'nome', 'idade', 'email']}) .then(result => { res.status(200).json(result); }); }catch(error){ res.status(500).json({ message: "Fail!", error: error.message }); } } exports.getCliente = (req, res) => { Cliente.findByPk(req.params.id, {attributes: ['id', 'nome', 'idade','email']}) .then(cliente => { res.status(200).json(cliente); }).catch(error => { // log on console console.log(error); res.status(500).json({ message: "Error!", error: error }); }) } exports.clientes = (req, res) => { // find all Customer information from try{ Cliente.findAll({attributes: ['id', 'nome', 'idade', 'email']}) .then(clientes => { res.status(200).json(clientes); }) }catch(error) { // log on console console.log(error); res.status(500).json({ message: "Error!", error: error }); } } exports.deleteCliente = async (req, res) => { try{ let clienteId = req.params.id; let cliente = await Cliente.findByPk(clienteId); if(!cliente){ res.status(404).json({ message: "Does Not exist a Customer with id = " + clienteId, error: "404", }); } else { await cliente.destroy(); res.status(200).json('cliente deletado com sucesso.'); } } catch(error) { res.status(500).json({ message: "Error -> Can NOT delete a customer with id = " + req.params.id, error: error.message }); } } exports.updateCliente = async (req, res) => { try{ let cliente = await Cliente.findByPk(req.body.id); if(!cliente){ // return a response to client res.status(404).json({ message: "Not Found for updating a customer with id = " + clienteId, error: "404" }); } else { // update new change to database let updatedObject = { nome: req.body.nome, idade: req.body.idade, email: req.body.email, } let result = await Cliente.update(updatedObject, { returning: true, where: {id: req.body.id}, attributes: ['id', 'nome', 'idade', 'email'] } ); // return the response to client if(!result) { res.status(500).json({ message: "Error -> Can not update a customer with id = " + req.params.id, error: "Can NOT Updated", }); } res.status(200).json(result); } } catch(error){ res.status(500).json({ message: "Error -> Can not update a customer with id = " + req.params.id, error: error.message }); } }<file_sep>/backend/server.js const express = require('express'); const app = express(); const db = require('./app/config/db.config.js'); const Cliente = db.Cliente; var bodyParser = require('body-parser'); let router = require('./app/routes/router.js'); const cors = require('cors') const corsOptions = { origin: 'http://localhost:3000', optionsSuccessStatus: 200 } app.use(cors(corsOptions)); app.use(bodyParser.json()); app.use(express.static('resources')); app.use('/', router); const server = app.listen(8080, function () { let host = server.address().address let port = server.address().port console.log("App está rodando no endereço http://%s:%s", host, port); }) db.sequelize.sync({ force: true }).then(() => { console.log('Apaga e recria a tabela usando { force: true }'); Cliente.sync().then(() => { const clientes = [ { nome: 'Pedro', idade: 23, email: '<EMAIL>' }, { nome: 'Sara', idade: 31, email: '<EMAIL>' }, { nome: 'Emilly', idade: 18, email: '<EMAIL>' }, ] clientes.map(cliente => { Cliente.create(cliente); }); }) }); <file_sep>/frontendd/projeto/src/pages/AddClientes/index.js import { Component } from "react"; import api from '../../service/api'; export default class CadastroCliente extends Component { state = { cad_nome: '', cad_idade: '', cad_email: '', }; handleNomeChange = e => { this.setState({ cad_nome: e.target.value }); }; handleIdadeChange = e => { this.setState({ cad_idade: e.target.value }); }; handleEmailChange = e => { this.setState({ cad_email: e.target.value }); }; handleOnSubmit = async e => { const { cad_nome, cad_idade, cad_email } = this.state; e.preventDefault(); const Cliente = { 'nome': cad_nome, 'idade': cad_idade, 'email': cad_email } await api.post(`/cliente`, Cliente) .then(console.log(Cliente)) alert('usuário adicionado com sucesso.'); } render() { const { cad_nome, cad_idade, cad_email } = this.state; return ( <div className="container" > <div className="content"> <header> <h1> CADASTRO </h1> </header> <div className="caixa1"> <div id="cadastro"> <form onSubmit={this.handleOnSubmit}> <div class="input-field"> <input required="required" type="text" placeholder="Digite seu nome" value={cad_nome} onChange={this.handleNomeChange} /> <div class="underline"></div> </div> <div class="input-field"> <input required="required" type="text" placeholder="Digite seu email" autocomplete="off" value={cad_idade} onChange={this.handleIdadeChange} /> <div class="underline"></div> </div> <div class="input-field"> <input required="required" type="text" placeholder="Digite sua idade" value={cad_email} onChange={this.handleEmailChange} /> <div class="underline"></div> </div> <p> <input type="submit" value="Cadastrar" /> </p> </form> </div> </div> </div> // </div> ) } }
db184b73526aab004b104447cdcb130538a8ddbc
[ "JavaScript" ]
4
JavaScript
paulopalacio1/Crud_Cadastro_Clientes
d4bf3d35083f37ebc046f2d2f2cb8df9a1f2d50b
c665f1e41aeb937fd1c1fb42351c533d47c61fa2
refs/heads/master
<repo_name>chane1994/OperationHarvest<file_sep>/Assets/Scripts/LevelScripts/BonusCollectable.cs using UnityEngine; using System.Collections; using System.IO; public class BonusCollectable : MonoBehaviour { const int NUM_BUTTONS = 10; bool alarmHasBeenTriggered = false; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public void UpdateFile() { /*if (!alarmHasBeenTriggered) { string[,] text = new string[NUM_BUTTONS, 2]; using (StreamReader file = new StreamReader("./Assets/Lore/LoreManager.txt")) { string line = ""; for (int i = 0; i < NUM_BUTTONS; i++) { line = file.ReadLine(); text[i, 0] = line.Split(' ')[0]; text[i, 1] = line.Split(' ')[1]; if (text[i, 0] == gameObject.name) { text[i, 1] = "true"; } } } using (StreamWriter file = new StreamWriter("./Assets/Lore/LoreManager.txt")) { file.Flush(); for (int i = 0; i < NUM_BUTTONS; i++) { file.WriteLine(text[i, 0] + " " + text[i, 1]); } } print("File updated"); }*/ } public void AlarmWasTriggered() { alarmHasBeenTriggered = true; } } <file_sep>/Assets/Scripts/CharacterScripts/MainMenuCharacterCrawling.cs using UnityEngine; using System.Collections; public class MainMenuCharacterCrawling : MonoBehaviour { public Animator charAnimator; public GameObject player; public float timer; bool walk; // Use this for initialization void Start () { charAnimator.SetBool("crouching", true); // Means that the character is not movin, genrally in the idle charAnimator.SetBool("ground", true);// Character is on the ground charAnimator.SetBool("running", false);// Character is Running charAnimator.SetBool("climbing", false); walk = false; } // Update is called once per frame void Update () { timer += Time.deltaTime; if (timer > 1 && !walk) { timer = 0; walk = !walk; } charAnimator.SetBool("moving", walk); //Y Size of the Box collider on the player is equal to 15.2215, center y is = 7.1102 /*Vector3 temp = this.gameObject.GetComponent<BoxCollider>().size; this.gameObject.GetComponent<BoxCollider>().size = new Vector3(temp.x, 10f, temp.z); temp = this.gameObject.GetComponent<BoxCollider>().center; this.gameObject.GetComponent<BoxCollider>().center = new Vector3(temp.x, 4.5f, temp.z);*/ } } <file_sep>/Assets/Scripts/MainMenuLight.cs using UnityEngine; using System.Collections; using System; public class MainMenuLight : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (gameObject.transform.position.x < -35) { gameObject.transform.position = new Vector3(30, gameObject.transform.position.y, gameObject.transform.position.z); } gameObject.transform.position = new Vector3(gameObject.transform.position.x-0.3f, gameObject.transform.position.y, gameObject.transform.position.z); } } <file_sep>/Assets/Scripts/GrenadeScript.cs using UnityEngine; using System.Collections; public class GrenadeScript : MonoBehaviour { Rigidbody rigid; public float age; public float explosiveForce; public float explosiveRadius; // Use this for initialization void Start () { rigid = this.gameObject.GetComponent<Rigidbody>(); explosiveForce = 10000; explosiveRadius = 10000; } // Update is called once per frame void Update () { age -= Time.deltaTime; if (age <= 0) { rigid.AddExplosionForce(explosiveForce,this.transform.position,explosiveRadius); Destroy(this.gameObject); } } } <file_sep>/Assets/Scripts/LevelScripts/CollectableScript.cs using UnityEngine; using System.Collections; using System.IO; using System.Text; public class CollectableScript : MonoBehaviour { const int NUM_BUTTONS = 10; // Use this for initialization void Start () { } // Update is called once per frame void Update () { gameObject.transform.Rotate(0f, 1f, 0f); } void OnTriggerEnter(Collider col) { if (col.gameObject.tag == "Player") { //col.GetComponent<CharacterMovementScript>().AddLore(gameObject.name); UpdateFile(); Destroy(gameObject); } } void UpdateFile() { /*string[,] text = new string[NUM_BUTTONS, 2]; StreamReader read = null; //TextAsset file1 = Resources.Load("LoreManager") as TextAsset; read = new StreamReader("./Assets/Lore/LoreManager.txt"); string line = ""; for (int i = 0; i < NUM_BUTTONS; i++) { line = read.ReadLine(); text[i, 0] = line.Split(' ')[0]; text[i, 1] = line.Split(' ')[1]; if (text[i, 0] == gameObject.name) { text[i, 1] = "true"; } } read.Close(); //StringBuilder stringBuilder = new StringBuilder(file1.text); // StringWriter write = new StringWriter(stringBuilder); using (StreamWriter file = new StreamWriter("./Assets/Lore/LoreManager.txt")) { file.Flush(); for (int i = 0; i < NUM_BUTTONS; i++) { file.WriteLine(text[i, 0] + " " + text[i, 1]); Debug.Log(text[i, 0] + " " + text[i, 1]); } //write.Close(); print("File updated"); }*/ } } <file_sep>/Assets/Scripts/HandlerScript.cs using UnityEngine; using System.Collections; using UnityEngine.UI; using UnityEngine.EventSystems; //Used to handle a bunch of basic Handler stuff. Things like sound can be add to it later. public class HandlerScript : MonoBehaviour, IPointerDownHandler { public GameObject globalTimerButton; public GameObject mapButton; public GameObject computerButton; public GameObject inputTimer; public Animator parentAnimator; int animationState; bool activeHandler; // Helps handle the animation and stops it from doing the animations repeately bool wasClicked; bool isOn; // Use this for initialization void Start () { wasClicked = false; parentAnimator = this.transform.parent.GetComponent<Animator>(); globalTimerButton.SetActive(wasClicked); mapButton.SetActive(wasClicked); computerButton.SetActive(wasClicked); inputTimer.SetActive(false); activeHandler = false; animationState = 2; isOn = false; } // Update is called once per frame void Update () { if (Input.GetMouseButtonDown(0)) { if (Vector3.Distance(this.transform.position, Input.mousePosition) < 5f) { wasClicked = !wasClicked; } } if(wasClicked){ StartCoroutine(Yield(1f)); globalTimerButton.SetActive(true); mapButton.SetActive(true); computerButton.SetActive(true); isOn = true; } else { globalTimerButton.SetActive(false); mapButton.SetActive(false); computerButton.SetActive(false); isOn = false; } if (isOn) { inputTimer.SetActive(globalTimerButton.GetComponent<UIButtonScript>().WasClicked); } } public void OnPointerDown(PointerEventData eventData) { wasClicked = !wasClicked; parentAnimator.SetBool("wasClicked", wasClicked); } public bool WasClicked { get { return wasClicked; } set { wasClicked = value; } } IEnumerator Yield(float x) { yield return new WaitForSeconds(x); } } <file_sep>/Assets/Scripts/BulletMovement.cs using UnityEngine; using System.Collections; public class BulletMovement : MonoBehaviour { int moveSpeed; float age; GameObject attacker; bool direction; //if direction is true, bullet goes right. Else, it goes right bool aimMode; Vector3 position; TestIKScript testIKScript; public GameObject explosion; // Use this for initialization void Start () { age = 0; moveSpeed = 1; //attacker = GameObject.FindGameObjectWithTag ("Player"); //direction = attacker.GetComponent<CharacterMovementScript>().Direction; //aimMode = attacker.GetComponent<CharacterMovementScript>().AimMode; //Debug.Log("My direction is" + direction); // Debug.Log("Aimmode is currently" + aimMode); } public void SetAttacker(GameObject g) { attacker = g; if (attacker.gameObject.tag == "Player") { direction = attacker.GetComponent<CharacterMovementScript>().Direction; aimMode = attacker.GetComponent<CharacterMovementScript>().AimMode; if (aimMode) { testIKScript = GameObject.FindGameObjectWithTag("Player").GetComponent<TestIKScript>(); position = testIKScript.lookObj.position; this.transform.LookAt(position); } else { //Debug.Log("Tossed Grenade"); position = GameObject.FindGameObjectWithTag("LookAtObj").transform.position; this.transform.LookAt(position); } } else if (attacker.GetComponent<GuardController>()) { if (attacker.GetComponent<GuardController>().movingSpeed < 0) direction = true; else direction = false; } else { position = GameObject.FindGameObjectWithTag("Player").transform.position; this.transform.LookAt(position); } } // Update is called once per frame public Vector3 Position { set { position = value; } } void Update () { if (attacker.tag == "Player") { age += Time.deltaTime; if (this.gameObject.tag == "Grenade") { this.transform.Translate((moveSpeed * Vector3.forward * Vector3.Distance(GameObject.FindGameObjectWithTag("Player").transform.position, GameObject.FindGameObjectWithTag("LookAtObj").transform.position)) / 25); if (age > 4) { GameObject temp = (GameObject)Instantiate(explosion, this.transform.position, Quaternion.identity); Destroy(this.gameObject); if (Vector3.Distance(GameObject.FindGameObjectWithTag("Player").transform.position, temp.transform.position) < 15f) { GameObject.FindGameObjectWithTag("Player").GetComponent<CharacterMovementScript>().TakeHit(50f); } foreach (GameObject g in GameObject.FindGameObjectsWithTag("Enemy")) { if (Vector3.Distance(g.transform.position, temp.transform.position) < 15f) { if (g.gameObject.GetComponent<GuardController>()) { g.gameObject.GetComponent<GuardController>().TakeHit(10f); } else if (g.gameObject.GetComponent<TurretController>()) { g.gameObject.GetComponent<TurretController>().TakeHit(10f); } } } } } else { this.transform.Translate(Vector3.forward); if (age > 4 || Vector3.Distance(this.gameObject.transform.position,GameObject.FindGameObjectWithTag("Player").transform.position) >200) { Destroy(this.gameObject); } } } else { //Debug.Log("I going towards "+ position); if (attacker.name == "Turrent") { this.transform.Translate(Vector3.forward / 2); if (age > 6) Destroy(this.gameObject); } else { age += Time.deltaTime; if (direction) { this.transform.Translate(Vector3.down / 2); } else { this.transform.Translate(Vector3.down / 2); } if (age > 6) Destroy(this.gameObject); } } transform.position = new Vector3(transform.position.x, transform.position.y, attacker.transform.position.z); } void OnCollisionEnter(Collision col) { if (col.gameObject != attacker && this.gameObject.tag != "Grenade") { if (col.gameObject.tag == "Player") { col.gameObject.GetComponent<CharacterMovementScript>().TakeHit(100f); } else if (col.gameObject.tag == "Enemy") { if (col.gameObject.GetComponent<GuardController>()) { col.gameObject.GetComponent<GuardController>().TakeHit(10f); //Added to fix player colliding with dead enemy //Physics.IgnoreCollision(col.gameObject.GetComponent<Collider>(), GameObject.FindGameObjectWithTag("Player").GetComponent<Collider>()); } else if (col.gameObject.GetComponent<TurretController>()) { col.gameObject.GetComponent<TurretController>().TakeHit(10f); } } Destroy(gameObject); } else if (this.gameObject.tag == "Grenade" && col.gameObject != attacker) { if (col.gameObject.tag == "Player") { col.gameObject.GetComponent<CharacterMovementScript>().TakeHit(10f); } else if (col.gameObject.tag == "Enemy") { if (col.gameObject.GetComponent<GuardController>()) { col.gameObject.GetComponent<GuardController>().TakeHit(10f); } else if (col.gameObject.GetComponent<TurretController>()) { col.gameObject.GetComponent<TurretController>().TakeHit(10f); } } else if (col.gameObject.tag == "Floor") { moveSpeed = 0; } } } //this prevents the bullet from spawning on the model it comes from IEnumerable startAsTrigger() { this.GetComponent<Rigidbody>().detectCollisions = false; yield return new WaitForSeconds(0.5f); this.GetComponent<Rigidbody>().detectCollisions = true; } //void OnDestroy() //{ // print("WORKED"); // gameObject.GetComponent<AudioSource>().Play(); //} } <file_sep>/Assets/Scripts/LookAtTarget.cs using UnityEngine; using System.Collections; public class LookAtTarget : MonoBehaviour { public Transform lookAt; public Vector3 oldPos; public bool lookForTarget; // Use this for initialization void Start () { oldPos = this.transform.localPosition; lookAt = GameObject.FindGameObjectWithTag("LookAtObj").transform; lookForTarget = true; } // Update is called once per frame void Update() { this.transform.localPosition = Vector3.zero; transform.LookAt(lookAt.position); transform.Rotate(new Vector3(1.0f, 0, 0), -90); } } <file_sep>/Assets/Scripts/EnemyScripts/Controller.cs using UnityEngine; using System.Collections; public class Controller : MonoBehaviour { //Used to trigger walking animation bool _move; //Used to trigger firing animation bool _seePlayer; //Animation of the enemy public Animator animate; public GameObject player; public float movingSpeed; public int count = 0; // Use this for initialization void Start() { _move = false; _seePlayer = false; animate = this.gameObject.GetComponent<Animator>(); animate.SetBool("seePlayer", _seePlayer); animate.SetBool("move", _move); } // Update is called once per frame void Update() { if ((player.transform.position.x - this.gameObject.transform.position.x <= 30 && movingSpeed > 0) || (this.gameObject.transform.position.x - player.transform.position.x <= 30 && movingSpeed < 0)) { Debug.Log("banana"); _move = false; _seePlayer = true; Attack(); animate.SetBool("seePlayer", _seePlayer); } else { _move = true; _seePlayer = false; Move(); } } //Will add the direction into a seperate method later void Move() { count++; //handles the direction of the enemy if (movingSpeed > 0) { this.gameObject.transform.eulerAngles = new Vector3(0, 0, 0); this.gameObject.transform.Translate(new Vector3(-movingSpeed, 0, 0)); } else { this.gameObject.transform.eulerAngles = new Vector3(0, 180, 0); this.gameObject.transform.Translate(new Vector3(movingSpeed, 0, 0)); } if (count >= 500) { movingSpeed *= -1; count = 0; } } void Attack() { if (movingSpeed > 0) { this.gameObject.transform.eulerAngles = new Vector3(0, 0, 0); } else { this.gameObject.transform.eulerAngles = new Vector3(0, 180, 0); } } } <file_sep>/Assets/Scripts/MainMenuScript.cs using UnityEngine; using System.Collections; using UnityEngine.UI; public class MainMenuScript : MonoBehaviour { public GameObject start; public GameObject credits; public GameObject TutorialLevelButton; public GameObject startImages; public GameObject LevelImages; public GameObject creditImages; public GameObject dataFileButton; public GameObject level1; public int nextStage; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (start.GetComponent<UIButtonScript>().WasClicked) { LevelImages.SetActive(true); startImages.SetActive(false); } if (credits.GetComponent<UIButtonScript>().WasClicked) { Application.LoadLevel("Credits"); } if (TutorialLevelButton.GetComponent<UIButtonScript>().WasClicked) { Application.LoadLevel("CurrentLevel"); } if (level1.GetComponent<UIButtonScript>().WasClicked) { Application.LoadLevel("TutorialStealthScene1"); } if (dataFileButton.GetComponent<UIButtonScript>().WasClicked) { Application.LoadLevel("DataFiles"); } } } <file_sep>/Assets/GPSScript.cs using UnityEngine; using System.Collections; using UnityEngine.UI; public class GPSScript : MonoBehaviour { public GameObject goalObj; public GameObject player; public Vector3 lookPos; // Use this for initialization void Start () { goalObj = GameObject.Find("Goal"); player = GameObject.FindGameObjectWithTag("Player"); } // Update is called once per frame void Update () { lookPos = new Vector3(goalObj.transform.position.x, goalObj.transform.position.y); lookPos = lookPos - player.transform.position; lookPos.Normalize(); float rot_z = Mathf.Atan2(lookPos.y, lookPos.x) * Mathf.Rad2Deg; transform.rotation = Quaternion.Euler(0f, 0f, rot_z - 90); } } <file_sep>/Assets/Scripts/CharacterScripts/CharacterMovementScript.cs using UnityEngine; using System.Collections; using System.Collections.Generic; using UnityEngine.UI; public class CharacterMovementScript : MonoBehaviour { public Animator charAnimator; //Access to Agent Controller, the animation controller of the model public GameObject player;// Will be set to private private Camera camera; // Will be set to private private List<string> obtainedLore = new List<string>();//used to track which lore the player has unlocked float zaxis; public float movingSpeed, jumpingSpeed; bool _moving, _ground, _running, _climbing, _crouch; Rigidbody rigidBody; int currentWeapon; public bool paused; public Transform muzzleLocation; public Transform grenadeLocation; public GameObject currentBullet; public GameObject currentGrenade; Event shotEvent; public float health; bool direction; public float soundIntensity; GameObject menu; Image healthBar; public Texture2D cursorTexture; public CursorMode cursorMode; public Vector2 hotSpot; public TestIKScript testIKScript; bool aimBool; // Determines whether the game is in aiming mode public float fireRate; //Gives a set fire rate to attacks bool canfire; //Used to stop certain attacks from firing into the time is right (mainly used for shooting); // Use this for initialization void Start () { player = this.gameObject; paused = false; rigidBody = player.GetComponent<Rigidbody> (); _moving = false; _ground = true; _crouch = false; camera = GameObject.FindGameObjectWithTag ("MainCamera").GetComponent<Camera> (); canfire = false; aimBool = false; //This Script handles IK Stuff testIKScript = this.gameObject.GetComponent<TestIKScript>(); player.transform.eulerAngles = new Vector3 (0, 180, 0);// This means that the player will start facing left charAnimator = player.GetComponent<Animator> (); charAnimator.SetBool ("moving", _moving); // Means that the character is not movin, genrally in the idle charAnimator.SetBool ("ground", _ground);// Character is on the ground charAnimator.SetBool ("running", _running);// Character is Running charAnimator.SetBool ("climbing", _climbing); charAnimator.SetBool("crouching", _crouch); currentWeapon = 2; charAnimator.SetInteger("currentWeapon", currentWeapon); //Set from 100->10 to make demo seem difficult. Maybe make permenant? health = 100f; menu = GameObject.FindGameObjectWithTag ("Menu"); healthBar = GameObject.FindGameObjectWithTag("HealthBar").GetComponent<Image>(); menu.SetActive (false); //Health (); } public List<string> GetLore { get { return obtainedLore; } } void Health() { healthBar.fillAmount = health * .01f; } public bool Crouch { get { return _crouch; } } public GameObject Menu { get { return menu; } set { menu = value; } } public Image HealthBar { get { return healthBar; } set { healthBar = value; } } void HandleMenu() { Health(); Cursor.visible = paused; Cursor.SetCursor(null, hotSpot, cursorMode); if (Input.GetButtonDown ("Menu")) { paused = !paused; menu.SetActive(paused); } } void HandleMovement() { if (Input.GetButton ("Horizontal")) { //Debug.Log ("Moving"); //Debug.Log (Input.GetAxis("Horizontal")); _moving = true; if (Input.GetButton("Running")) { _running = true; charAnimator.SetBool("running",_running); } else { AnimationHandler (0); _running = false; charAnimator.SetBool("running",_running); } if (Input.GetAxis ("Horizontal") > 0) { direction = true; } else { direction = false; player.transform.eulerAngles = new Vector3 (0, -90, 0); } if(_running) { player.transform.Translate (Vector3.left * movingSpeed * 2*-Input.GetAxis ("Horizontal"), camera.transform); charAnimator.SetBool("running", _running); } else { player.transform.Translate (Vector3.left * movingSpeed * -Input.GetAxis ("Horizontal"), camera.transform); charAnimator.SetBool("running", _running); } //player.transform.Translate(Vector3.left); transform.position = new Vector3(transform.position.x, transform.position.y, transform.position.z); } else { _moving = false; _running = false; charAnimator.SetBool("running",_running); //Debug.Log ("Not Moving"); AnimationHandler (0); } //Handles the jump of the character if (Input.GetButton("Jump")) { if (_ground) { //Debug.Log ("Jumping"); _ground = false; AnimationHandler(1); StartCoroutine(jumpDelay(.30f)); } } if (Input.GetAxis("Vertical") < 0 && _ground) { _crouch = true; charAnimator.SetBool("crouching", _crouch); //Y Size of the Box collider on the player is equal to 15.2215, center y is = 7.1102 Vector3 temp = this.gameObject.GetComponent<BoxCollider>().size; this.gameObject.GetComponent<BoxCollider>().size = new Vector3(temp.x, 10f, temp.z); temp = this.gameObject.GetComponent<BoxCollider>().center; this.gameObject.GetComponent<BoxCollider>().center = new Vector3(temp.x, 4.5f, temp.z); } else if (Input.GetAxis("Vertical") >0) { _crouch = false; charAnimator.SetBool("crouching", _crouch); Vector3 temp = this.gameObject.GetComponent<BoxCollider>().size; this.gameObject.GetComponent<BoxCollider>().size = new Vector3(temp.x, 15.2215f, temp.z); temp = this.gameObject.GetComponent<BoxCollider>().center; this.gameObject.GetComponent<BoxCollider>().center = new Vector3(temp.x, 7.1102f, temp.z); } } void HandleAimMode(float fireRate) { Cursor.visible = true; Cursor.SetCursor(cursorTexture, hotSpot, cursorMode); testIKScript.ikActive = true; } public bool AimMode { get { return aimBool; } set { aimBool = value; } } // Update is called once per frame void Update () { //Handles's Basic movement of the Character fireRate += Time.deltaTime; Health(); //TakeHit(1.0f); if (health <= 0) { charAnimator.SetBool("dead", true); GameObject.FindGameObjectWithTag("Respawn").GetComponent<SpawnerScript>().Spawner(this.gameObject); } // used for aiming mode HandleMenu (); if (!paused) { HandleMovement(); //Handles Switching wapons if (Input.GetButtonDown("switchWeapon")) { if (currentWeapon < 2) { currentWeapon++; //Debug.Log("current weapon is" + currentWeapon); } else { currentWeapon = 0; } } if (currentWeapon == 1) { aimBool = false; Cursor.visible = true; Cursor.SetCursor(cursorTexture, hotSpot, cursorMode); } else if (currentWeapon == 0) { aimBool = false; } else { aimBool = true; } if (_climbing) { transform.rotation = Quaternion.Euler(0, 0, 0); this.gameObject.GetComponent<Rigidbody>().useGravity = false; if (Input.GetAxis("Vertical") == 0 && Input.GetAxis("Horizontal") == 0) { charAnimator.speed = 0; this.gameObject.GetComponent<Rigidbody>().Sleep(); this.gameObject.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezePositionY; this.gameObject.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezePositionX; } else { charAnimator.speed = 1; this.gameObject.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.None; } } else { this.gameObject.GetComponent<Rigidbody>().useGravity = true; this.gameObject.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezePositionZ; this.gameObject.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeRotationZ; } // Handles Firing weapons if (Input.GetButton("Fire1") && fireRate > 1.5f) { fireRate = 0; if (currentWeapon == 0)//This is the melee attack, usally with a sword { //Debug.Log("MeleeAttack"); charAnimator.SetTrigger("canAttack"); charAnimator.SetInteger("currentWeapon", currentWeapon); aimBool = false; } if (currentWeapon == 1)//This is the grenade { aimBool = false; //Debug.Log("GrenadeAttack"); charAnimator.SetTrigger("canAttack"); charAnimator.SetInteger("currentWeapon", currentWeapon); GameObject instance = (GameObject)Instantiate(currentGrenade, grenadeLocation.position, Quaternion.identity); instance.GetComponent<BulletMovement>().SetAttacker(this.gameObject); } if (currentWeapon == 2)//This is the pistol { aimBool = true; //Debug.Log("PistolAttack"); //charAnimator.SetTrigger("canAttack"); // charAnimator.SetInteger("currentWeapon", currentWeapon); canfire = true; Debug.Log("Fire a shot!"); GameObject instance = (GameObject)Instantiate(currentBullet, muzzleLocation.position, muzzleLocation.rotation); instance.GetComponent<BulletMovement>().SetAttacker(this.gameObject); gameObject.GetComponent<AudioSource>().Play(); } } if (!aimBool) { testIKScript.ikActive = false; } else { HandleAimMode(fireRate); } } } void OnCollisionEnter(Collision col) { if (col.gameObject.tag == "Floor") { _ground = true; charAnimator.speed = 1; AnimationHandler(1); Debug.Log ("Landed on the ground"); } } void OnTriggerEnter(Collider col) { if (col.gameObject.tag == "Climable" ) { if (Input.GetButton ("Vertical") &&Input.GetButton ("Vertical") ) { //Debug.Log ("Try Climbing"); _climbing = true; charAnimator.SetBool("climbing",_climbing); player.transform.Translate (Vector3.up * movingSpeed * Input.GetAxis ("Vertical"), camera.transform); } } } void OnTriggerStay(Collider col) { if (col.gameObject.tag == "Climable") { if (Input.GetButton("Vertical") && Input.GetButton("Vertical")) { //Debug.Log ("Try Climbing"); _climbing = true; charAnimator.SetBool("climbing",_climbing); player.transform.Translate (Vector3.up * movingSpeed * Input.GetAxis ("Vertical"), camera.transform); } } } void OnTriggerExit(Collider col) { if (col.gameObject.tag == "Climable") { _climbing = false; charAnimator.SetBool("climbing",_climbing); this.rigidBody.useGravity = true; } } void AnimationHandler(int aniState ) { if (aniState == 0) { charAnimator.SetBool("moving", _moving); } if (aniState == 1) { charAnimator.SetBool("ground", _ground); } } //Right=true //Left=false public bool Direction { get {return direction;} set { direction = value; } } IEnumerator jumpDelay(float x) { yield return new WaitForSeconds(x); charAnimator.speed = 0; rigidBody.AddForce(Vector3.up * jumpingSpeed); } public void TakeHit(float f) { health -= f; } public void AddLore(string s) { print(s+".txt"); obtainedLore.Add(s+".txt"); } }<file_sep>/Assets/SpawnerScript.cs using UnityEngine; using System.Collections; using UnityEngine.UI; public class SpawnerScript : MonoBehaviour { public GameObject player; public GameObject temp; public GameObject gameOver; public GameObject button; public GameObject button2; public bool spawn; // Use this for initialization void Start () { gameOver.SetActive(false); } // Update is called once per frame void Update () { if (gameOver.activeSelf) { if (button.GetComponent<UIButtonScript>().WasClicked) { button.GetComponent<UIButtonScript>().WasClicked = false; gameOver.SetActive(false); HandleNewScene(temp); } if (button2.GetComponent<UIButtonScript>().WasClicked) { Application.LoadLevel("MainMenuScene"); } } } public void Spawner(GameObject g) { temp = g; temp.GetComponent<CharacterMovementScript>().enabled = false; StartCoroutine(Delay(3)); } IEnumerator Delay(float x) { yield return new WaitForSeconds(x); gameOver.SetActive(true); } void HandleNewScene(GameObject g) { Application.LoadLevel(Application.loadedLevel); } } <file_sep>/Assets/RagDollScript.cs using UnityEngine; using System.Collections; public class RagDollScript : MonoBehaviour { GameObject player; float age; // Use this for initialization void Start () { player = GameObject.FindGameObjectWithTag("Player"); //Physics.IgnoreCollision(gameObject.GetComponent<Collider>(), player.GetComponent<Collider>()); age = 0; } // Update is called once per frame void Update () { age += Time.deltaTime; if (age > 3) Destroy(this.gameObject); } } <file_sep>/Assets/Scripts/EnemyScripts/LightManager.cs using UnityEngine; using System.Collections; using System.Diagnostics; public class LightManager : MonoBehaviour { /*public Light light1; public Light light2; public Light light3; public Light light4; public Light light5;*/ public Light[] lights; /*public AudioSource audio1; public AudioSource audio2; public AudioSource audio3; public AudioSource audio4; public AudioSource audio5;*/ //public Light cameraLight; public GameObject player; public bool currentlyPlaying = false; // Use this for initialization void Start () { lights = gameObject.GetComponentsInChildren<Light>(); foreach (Light l in lights) { if (l.name != "EnemyCamera") { l.color = Color.white; l.intensity = 1; l.GetComponent<AudioSource>().loop = true; } else { l.color = Color.green; l.intensity = 10; } } } // Update is called once per frame void Update () { /*if (player.transform.position.y >= 6 && player.transform.position.x>-2.7 && player.transform.position.x<6.2 && !currentlyPlaying) { cameraLight.color = Color.red; light1.intensity = 8; light2.intensity = 8; light3.intensity = 8; light4.intensity = 8; light5.intensity = 8; audio1.Play(); audio2.Play(); audio3.Play(); audio4.Play(); audio5.Play(); currentlyPlaying = true; }*/ } public void SetAlarm(bool status) { StackTrace st = new StackTrace(); print(st.GetFrame(1).GetMethod().Name); //print("ALARM SET"); if (status) { foreach (Light l in lights) { l.intensity = 8; l.color = Color.red; if(l.name != "EnemyCamera") l.GetComponent<AudioSource>().Play(); } } else { foreach (Light l in lights) { if (l.name != "EnemyCamera") { l.intensity = 1; l.color = Color.white; l.GetComponent<AudioSource>().Pause(); } else { l.color = Color.green; l.intensity = 10; } } } } public bool AlarmStatus() { if (lights[0].color == Color.red) { return true; } else { return false; } } }<file_sep>/Assets/CollectedData.cs using UnityEngine; using System.Collections; public class CollectedData : MonoBehaviour { public GameObject button; public GameObject door; public GameObject winScreen; public GameObject[] shutters; // Use this for initialization void Start () { shutters = GameObject.FindGameObjectsWithTag("Shutters"); //winScreen = GameObject.Find("Winscreen"); if(this.gameObject.name == "Goal") winScreen.SetActive(false); } // Update is called once per frame void Update () { } void OnTriggerStay(Collider col) { if (col.gameObject.tag == "Player" && button.GetComponent<UIButtonScript>().WasClicked && this.gameObject.name == "Goal" ) { winScreen.SetActive(true); StartCoroutine(Delay(3f)); //GameObject.FindGameObjectWithTag("Bonus Collectable").GetComponent<BonusCollectable>().UpdateFile(); } if (col.gameObject.tag == "Player" && button.GetComponent<UIButtonScript>().WasClicked && this.gameObject.name != "Goal") { button.GetComponent<UIButtonScript>().WasClicked = false; Debug.Log("It worked!"); door.SetActive(false); if (shutters.Length != 0) { foreach (GameObject g in shutters) { g.SetActive(false); } } } } IEnumerator Delay(float x) { yield return new WaitForSeconds(x); Application.LoadLevel("MainMenuScene"); } } <file_sep>/Assets/Scripts/LevelScripts/ZLock.cs using UnityEngine; using System.Collections; public class ZLock : MonoBehaviour { GameObject Player; float mainZ; // Use this for initialization void Start () { Player= GameObject.FindGameObjectWithTag("Player"); mainZ = Player.transform.position.z; } // Update is called once per frame void Update () { Player.transform.position = new Vector3(Player.transform.position.x, Player.transform.position.y, mainZ); GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy"); for (int i = 0; i < enemies.Length; i++) { enemies[i].transform.position = new Vector3(enemies[i].transform.position.x, enemies[i].transform.position.y, mainZ); } } } <file_sep>/Assets/Scripts/MenuScript.cs using UnityEngine; using System.Collections; using UnityEngine.UI; public class MenuScript : MonoBehaviour { // Use this for initialization Image healthBar; void Start() { healthBar = GameObject.FindGameObjectWithTag("HealthBar").GetComponent<Image>(); } // Update is called once per frame void Update () { healthBar.fillAmount = GameObject.FindGameObjectWithTag("Player").GetComponent<CharacterMovementScript>().health * 0.01f; } } <file_sep>/Assets/Scripts/TestIKScript.cs using UnityEngine; using System.Collections; public class TestIKScript : MonoBehaviour { protected Animator animator; public bool ikActive = false; public Transform rightHandObj; public Transform lookObj; public GameObject gun; void Start () { animator = GetComponent<Animator>(); rightHandObj = GameObject.FindGameObjectWithTag("LookAtObj").transform; lookObj = GameObject.FindGameObjectWithTag("LookAtObj").transform; gun = GameObject.FindGameObjectWithTag("Gun"); } void Update() { if (lookObj.position.x > this.gameObject.transform.position.x) { this.gameObject.transform.eulerAngles = new Vector3(0, 90, 0); this.gameObject.GetComponent<CharacterMovementScript>().Direction = true; } else{ this.transform.eulerAngles = new Vector3(0, 270, 0); this.gameObject.GetComponent<CharacterMovementScript>().Direction = false; } } //a callback for calculating IK void OnAnimatorIK() { if(animator) { //if the IK is active, set the position and rotation directly to the goal. if(ikActive) { if (gun != null) { gun.GetComponent<LookAtTarget>().lookForTarget = true; } // Set the look target position, if one has been assigned if(lookObj != null) { animator.SetLookAtWeight(1); animator.SetLookAtPosition(lookObj.position); } // Set the right hand target position and rotation, if one has been assigned if(rightHandObj != null) { animator.SetIKPositionWeight(AvatarIKGoal.RightHand,1); animator.SetIKRotationWeight(AvatarIKGoal.RightHand,1); animator.SetIKPosition(AvatarIKGoal.RightHand,rightHandObj.position); animator.SetIKRotation(AvatarIKGoal.RightHand,Quaternion.LookRotation(rightHandObj.position)); } } //if the IK is not active, set the position and rotation of the hand and head back to the original position else { animator.SetIKPositionWeight(AvatarIKGoal.RightHand,0); animator.SetIKRotationWeight(AvatarIKGoal.RightHand,0); animator.SetLookAtWeight(0); if (gun != null) { gun.GetComponent<LookAtTarget>().lookForTarget = false; } } } } } <file_sep>/Assets/Scripts/EnemyScripts/TurretController.cs using UnityEngine; using System.Collections; public class TurretController : MonoBehaviour { public GameObject player; public GameObject currentBullet; public Transform muzzleLocation; float health = 20; bool canfire=true; int movingSpeed; // Use this for initialization void Start() { gameObject.tag = "Enemy"; player = GameObject.FindGameObjectWithTag("Player"); } // Update is called once per frame void Update() { } //Will add the direction into a seperate method later void Attack() { if (movingSpeed > 0) { // this.gameObject.transform.eulerAngles = new Vector3(0, 0, 0); // StartCoroutine(Delay(1f)); } else { // this.gameObject.transform.eulerAngles = new Vector3(0, 180, 0); // StartCoroutine(Delay(1f)); } } public void TakeHit(float f) { health -= f; print(health); if (health <= 0) { Destroy(this.gameObject); } } IEnumerator Delay(float x) { //Debug.Log ("I waited"); //Original Bullet /*yield return new WaitForSeconds(x); Instantiate(currentBullet,muzzleLocation.position,muzzleLocation.rotation); canfire = false;*/ //New Bullet yield return new WaitForSeconds(x); GameObject instance = (GameObject)Instantiate(currentBullet, muzzleLocation.position, muzzleLocation.rotation); //instance.GetComponent<BulletMovement>().Position = position; instance.GetComponent<BulletMovement>().SetAttacker(this.gameObject); canfire = false; } } <file_sep>/Assets/LorePanel.cs using UnityEngine; using System.Collections.Generic; public class LorePanel : MonoBehaviour { GameObject player; public GameObject lorePrefab; List<string> obtLore; RectTransform myRect; // Use this for initialization void Awake() { } void Start() { player = GameObject.FindGameObjectWithTag("Player"); obtLore = player.GetComponent<CharacterMovementScript>().GetLore; myRect = gameObject.GetComponent<RectTransform>(); myRect.offsetMin = new Vector2(0, -500); myRect.offsetMax = new Vector2(0, 0); int numberOfItems = 5; for (int i = 0; i < numberOfItems; i++) { GameObject lore = (GameObject)Instantiate(lorePrefab); RectTransform loreRect = lore.GetComponent<RectTransform>(); lore.transform.SetParent(this.transform,false); loreRect.offsetMin = new Vector2(0, -(i * 65f)); loreRect.offsetMax = new Vector2(0, -(i * 65f)); } } // Update is called once per frame void Update() { } public void GenerateLoreItems() { } } <file_sep>/Assets/UIButtonScript.cs using UnityEngine; using System.Collections; using UnityEngine.EventSystems; public class UIButtonScript : MonoBehaviour, IPointerDownHandler { bool wasClicked; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public void OnPointerDown(PointerEventData eventData) { wasClicked = !wasClicked; } public bool WasClicked { get { return wasClicked; } set { wasClicked = value; } } } <file_sep>/Assets/Scripts/CameraScripts/BoundryBasedCamera.cs using UnityEngine; using System.Collections; public class BoundryBasedCamera : MonoBehaviour { public GameObject player; public float zoom; public float cameraShift = 0; // Use this for initialization void Start () { player = GameObject.FindGameObjectWithTag ("Player"); //transform.position = new Vector3 (player.transform.position.x, player.transform.position.y +2 , player.transform.position.z-zoom); } void LateUpdate() { if ((Input.GetAxis("Horizontal") > 0 || Input.GetKey(KeyCode.Z))&& cameraShift < 2) { cameraShift += 0.05f; } else if ((Input.GetAxis("Horizontal") < 0 || Input.GetKey(KeyCode.C)) && cameraShift > -2) { cameraShift -= 0.05f; } else if (Input.GetAxis ("Horizontal") == 0) { if (cameraShift < 0.25 && cameraShift > -0.25) { cameraShift = 0; } else if (cameraShift > 0) { cameraShift -= 0.05f; } else if (cameraShift < 0) { cameraShift += 0.05f; } } if (!player.GetComponent<CharacterMovementScript>().Crouch) transform.position = new Vector3(player.transform.position.x + cameraShift, player.transform.position.y + 2, player.transform.position.z - zoom); else transform.position = new Vector3(player.transform.position.x + cameraShift, player.transform.position.y, player.transform.position.z - zoom); } // Update is called once per frame void Update () { if (player == null) { player = GameObject.FindGameObjectWithTag("Player"); } } } <file_sep>/Assets/Scripts/EnemyScripts/TempTrigger.cs using UnityEngine; using System.Collections; public class TempTrigger : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } void OnTriggerEnter(Collider col) { if (col.gameObject.tag == "Player") { GameObject.FindGameObjectWithTag("Light Manager").GetComponent<LightManager>().SetAlarm(true); } } } <file_sep>/Assets/Scripts/Computer.cs using UnityEngine; using System.Collections; public class Computer : MonoBehaviour { void OnCollisionEnter(Collision col) { print("collided"); if (col.gameObject.tag == "Player") ; GameObject.FindGameObjectWithTag("Light Manager").GetComponent<LightManager>().SetAlarm(false); } } <file_sep>/Assets/Scripts/LorePageParser.cs using UnityEngine; using System.Collections; using System.IO; public class LorePageParser : MonoBehaviour { GameObject pages; int count; // Use this for initialization void Start () { pages = GameObject.Find("Pages"); //GameObject[] allPages = pages.GetComponentsInChildren<GameObject>(); count = pages.transform.childCount; string[,] text = new string[count,2]; StreamReader file = new StreamReader("./Assets/loreFiles/LoreManager.txt"); using (file) { string line = ""; for (int i = 0; i < count; i++) { line = file.ReadLine(); text[i,0] = line.Split(' ')[0]; text[i, 1] = line.Split(' ')[1]; } } for (int i = 0; i <count; i++) { print(text[i, 0] + " " + text[i, 1]); } } // Update is called once per frame void Update () { } } <file_sep>/Assets/Scripts/CameraScripts/SlightCameraFollow.cs using UnityEngine; using System.Collections; public class SlightCameraFollow : MonoBehaviour { public GameObject player; public float zoom; // Use this for initialization void Start () { player = GameObject.FindGameObjectWithTag ("Player"); transform.position = new Vector3 (player.transform.position.x, player.transform.position.y +2 , player.transform.position.z-zoom); } void LateUpdate() { //Debug.Log("Player's Position: "+player.transform.position); // Debug.Log("Camera Position: "+gameObject.transform.position); if (player.transform.position.x - gameObject.transform.position.x >= 2) transform.position = new Vector3 (player.transform.position.x-2, player.transform.position.y +2 , player.transform.position.z-zoom); else if (player.transform.position.x - gameObject.transform.position.x <= -2) transform.position = new Vector3(player.transform.position.x + 2, player.transform.position.y + 2, player.transform.position.z - zoom); else transform.position = new Vector3(transform.position.x, player.transform.position.y + 2, player.transform.position.z - zoom); } // Update is called once per frame void Update () { } } <file_sep>/Assets/Scripts/EnemyScripts/GuardWaypoint.cs using UnityEngine; using System.Collections; public class GuardWaypoint : MonoBehaviour { GameObject parent; // Use this for initialization void Start () { parent = gameObject.transform.parent.gameObject; gameObject.transform.parent = null; } void OnTriggerEnter(Collider col) { if (col.gameObject == parent) { //print("TRIGGERED"); parent.GetComponent<GuardController>().ChangeDirection(); } } } <file_sep>/Assets/Scripts/CameraScripts/CameraMovementScript.cs using UnityEngine; using System.Collections; public class CameraMovementScript : MonoBehaviour { public GameObject player; // Use this for initialization void Start () { player = GameObject.FindGameObjectWithTag ("Player"); transform.position = new Vector3 (player.transform.position.x, player.transform.position.y +2 , player.transform.position.z-5); } void LateUpdate() { Debug.Log("Player's Position: "+player.transform.position); transform.position = new Vector3 (player.transform.position.x, player.transform.position.y +2 , player.transform.position.z-5); } // Update is called once per frame void Update () { } } <file_sep>/Assets/Scripts/EnemyScripts/GuardController.cs using UnityEngine; using System.Collections; public class GuardController : MonoBehaviour { //Used to trigger walking animation bool _move; //Used to trigger firing animation bool _seePlayer; //Animation of the enemy public Animator animate; public GameObject player; public GameObject currentBullet; public Transform muzzleLocation; public GameObject Ragdoll; public float movingSpeed; public int count = 0; public float health = 10; bool canfire = true; public int direction; static bool alarmActive = false; public int paceDistance; public GameObject pointA; public GameObject pointB; // Use this for initialization void Start() { _move = false; _seePlayer = false; animate = this.gameObject.GetComponent<Animator>(); animate.SetBool("seePlayer", _seePlayer); animate.SetBool("move", _move); gameObject.tag = "Enemy"; //gameObject.transform.position = new Vector3(gameObject.transform.position.x, gameObject.transform.position.y, -0.77f); player = GameObject.FindGameObjectWithTag("Player"); this.gameObject.transform.position = new Vector3(this.transform.position.x, this.transform.position.y, player.transform.position.z); if (movingSpeed > 0) direction = -1; else direction = 1; } // Depricated Update from before waypoint system /*void Update() { if (health > 0) { //Need to add a way to make sure they are on the same vertical plane //if (((player.transform.position.y - gameObject.transform.position.y < 4 && player.transform.position.x > gameObject.transform.position.x && movingSpeed < 0) || (gameObject.transform.position.y - player.transform.position.y < 4 && player.transform.position.x < gameObject.transform.position.x && movingSpeed > 0))) //{ // if (canfire) // { // _move = false; // _seePlayer = true; // Attack(); // animate.SetBool("seePlayer", _seePlayer); // animate.SetBool("move", _move); // canfire = false; // } //} direction = 0; RaycastHit hit; if (movingSpeed > 0) direction = -1; else direction = 1; Debug.DrawRay(muzzleLocation.position, new Vector3(7 * direction, 0, 0), Color.blue); // if (Physics.Raycast(transform.position, new Vector3(direction, 0, 0), 7.0f)) if (Physics.Raycast(muzzleLocation.position, new Vector3(direction, 0, 0), out hit, 7.0f) && hit.collider.tag == "Player" && player.GetComponent<CharacterMovementScript>().health > 0) { if (canfire) { print("Player hp " + player.GetComponent<CharacterMovementScript>().health); _move = false; _seePlayer = true; animate.SetBool("seePlayer", _seePlayer); animate.SetBool("move", _move); this.gameObject.transform.position = new Vector3(this.transform.position.x, this.transform.position.y, player.transform.position.z); Attack(); canfire = false; } } else { _move = true; _seePlayer = false; Move(); animate.SetBool("move", _move); animate.SetBool("seePlayer", _seePlayer); } if (Physics.Raycast(muzzleLocation.position, new Vector3(direction, 0, 0), out hit, 7.0f) && hit.collider.tag == "Player" && !GameObject.FindGameObjectWithTag("Light Manager").GetComponent<LightManager>().AlarmStatus()) { ActivateAlarm(); } } //print("Can fire: " + canfire); }*/ void Update() { if (player == null) { player = GameObject.FindGameObjectWithTag("Player"); } if (health > 0) { RaycastHit hit; Debug.DrawRay(muzzleLocation.position, new Vector3(7 * direction, 0, 0), Color.blue); // if (Physics.Raycast(transform.position, new Vector3(direction, 0, 0), 7.0f)) if (Physics.Raycast(muzzleLocation.position, new Vector3(direction, 0, 0), out hit, 7.0f) && hit.collider.tag == "Player" && player.GetComponent<CharacterMovementScript>().health > 0) { if (canfire) { print("Player hp " + player.GetComponent<CharacterMovementScript>().health); _move = false; _seePlayer = true; animate.SetBool("seePlayer", _seePlayer); animate.SetBool("move", _move); this.gameObject.transform.position = new Vector3(this.transform.position.x, this.transform.position.y, player.transform.position.z); Attack(); canfire = false; } } else { _move = true; _seePlayer = false; Move(); animate.SetBool("move", _move); animate.SetBool("seePlayer", _seePlayer); } if (Physics.Raycast(muzzleLocation.position, new Vector3(direction, 0, 0), out hit, 21.0f) && hit.collider.tag == "Player" && !GameObject.FindGameObjectWithTag("Light Manager").GetComponent<LightManager>().AlarmStatus()) { ActivateAlarm(); GameObject.FindGameObjectWithTag("Bonus Collectable").GetComponent<BonusCollectable>().AlarmWasTriggered(); } else { //DeactivateAlarm(); } } //print("Can fire: " + canfire); } //Depricated Move from before we had waypoints /*void Move() { count++; //handles the direction of the enemy //NOTE: Had to modify due to the scene being on a different angle that was originally. I think? if (movingSpeed < 0) { this.gameObject.transform.eulerAngles = new Vector3(0, 90, 0); this.gameObject.transform.Translate(new Vector3(0, 0, -movingSpeed)); //this.gameObject.transform.Translate(new Vector3(0, -movingSpeed, 0)); //print("Walk a"); //gameObject.transform.Translate(Vector3.right * movingSpeed); } else { this.gameObject.transform.eulerAngles = new Vector3(0, 270, 0); this.gameObject.transform.Translate(new Vector3(0, 0, movingSpeed)); //this.gameObject.transform.Translate(new Vector3(0, movingSpeed, 0)); //print("Walk b"); //gameObject.transform.Translate(Vector3.left * movingSpeed); } if (count >= paceDistance) { movingSpeed *= -1; count = 0; } }*/ void Move() { //handles the direction of the enemy //NOTE: Had to modify due to the scene being on a different angle that was originally. I think? if (direction > 0) { this.gameObject.transform.eulerAngles = new Vector3(0, 90, 0); this.gameObject.transform.Translate(new Vector3(0, 0, -movingSpeed)); //this.gameObject.transform.Translate(new Vector3(0, -movingSpeed, 0)); //print("Walk a"); //gameObject.transform.Translate(Vector3.right * movingSpeed); } else { this.gameObject.transform.eulerAngles = new Vector3(0, 270, 0); this.gameObject.transform.Translate(new Vector3(0, 0, movingSpeed)); //this.gameObject.transform.Translate(new Vector3(0, movingSpeed, 0)); //print("Walk b"); //gameObject.transform.Translate(Vector3.left * movingSpeed); } /*if (count >= paceDistance) { movingSpeed *= -1; count = 0; }*/ //this.gameObject.transform.position = new Vector3(this.gameObject.transform.position.x, 0.07f, this.gameObject.transform.position.z); } void Attack() { Debug.Log("I left"); Vector3 lookPos = new Vector3(player.transform.position.x, this.transform.position.y, this.transform.position.z); this.transform.LookAt(lookPos); StartCoroutine(Delay(1.0f)); //canfire = true; } public void TakeHit(float f) { health -= f; if (health <= 0) { DeactivateAlarm(); //this.gameObject.GetComponent<Rigidbody>().useGravity = false; //this.gameObject.transform.position= new Vector3(this.transform.gameObject.transform.position.x,this.transform.gameObject.transform.position.y-50,this.transform.gameObject.transform.position.z); Instantiate(Ragdoll, this.transform.position, this.transform.rotation); Destroy(this.gameObject); } } IEnumerator Delay(float x) { Debug.Log("before wait"); //New Bullet yield return new WaitForSeconds(x); GameObject instance = (GameObject)Instantiate(currentBullet, muzzleLocation.position, muzzleLocation.rotation); Debug.Log("Hit"); //this.gameObject.transform.eulerAngles = new Vector3(0, 270, 0); //StartCoroutine(Delay(1f)); gameObject.GetComponent<AudioSource>().Play(); //GameObject instance = (GameObject)Instantiate(currentBullet, muzzleLocation.position, muzzleLocation.rotation); //instance.GetComponent<BulletMovement>().Position = position; instance.GetComponent<BulletMovement>().SetAttacker(this.gameObject); canfire = true; } void ActivateAlarm() { GameObject.FindGameObjectWithTag("Light Manager").GetComponent<LightManager>().SetAlarm(true); } void DeactivateAlarm() { GameObject.FindGameObjectWithTag("Light Manager").GetComponent<LightManager>().SetAlarm(false); } public void ChangeDirection() { direction *= -1; movingSpeed *= -1; } } <file_sep>/Assets/Scripts/DataFileScript.cs using UnityEngine; using System.Collections; using System.IO; using UnityEngine.UI; public class DataFileScript : MonoBehaviour { const int NUM_BUTTONS = 10; public Sprite notObtained; public GameObject words; GameObject offButton; // Use this for initialization void Start() { words.GetComponent<Text>().text = ""; StreamReader file = new StreamReader("./Assets/Lore/LoreManager.txt"); string[,] text = new string[NUM_BUTTONS, 2]; offButton = GameObject.Find("OffButton"); //Requires that File be in the same order as the objects string line = ""; for (int i = 0; i < NUM_BUTTONS; i++) { line = file.ReadLine(); text[i, 0] = line.Split(' ')[0]; text[i, 1] = line.Split(' ')[1]; if (text[i, 1] != "true") { //gameObject.transform.GetChild(0).GetChild(i+1).GetComponent<Image>().sprite=notObtained; //Allows the file to be out of order if needed gameObject.transform.GetChild(0).FindChild(text[i, 0]).GetComponent<Image>().sprite = notObtained; } } file.Close(); } // Update is called once per frame void Update() { if (offButton.GetComponent<UIButtonScript>().WasClicked) { Application.LoadLevel("MainMenuScene"); } for (int i = 1; i < NUM_BUTTONS + 1; i++) { //TODO:change the file to only contain true values if (gameObject.transform.GetChild(0).GetChild(i).GetComponent<UIButtonScript>().WasClicked && gameObject.transform.GetChild(0).GetChild(i).GetComponent<Image>().sprite != notObtained) { gameObject.transform.GetChild(0).GetChild(i).GetComponent<UIButtonScript>().WasClicked = false; words.GetComponent<Text>().text = ""; using (StreamReader file = new StreamReader("./Assets/Lore/" + gameObject.transform.GetChild(0).GetChild(i).name + ".txt")) { string line; do { line = file.ReadLine(); words.GetComponent<Text>().text += line + "\n"; } while (line != null); } } } } } <file_sep>/Assets/Scripts/LevelScripts/NextRoom.cs using UnityEngine; using System.Collections; public class NextRoom : MonoBehaviour { public GameObject player; public int nextRoom; // Use this for initialization void Start () { player = GameObject.FindGameObjectWithTag ("Player"); } // Update is called once per frame void Update () { } void OnCollisonEnter(Collision col) { if (col.gameObject.tag == player.tag) { Application.LoadLevel(nextRoom); } } } <file_sep>/Assets/Scripts/InteractableScripts.cs using UnityEngine; using System.Collections; public class InteractableScripts : MonoBehaviour { GameObject player; // Use this for initialization void Start () { player = GameObject.FindGameObjectWithTag("Player"); } // Update is called once per frame void Update () { this.transform.Rotate(new Vector3(0, -1, 0)); if (Vector3.Distance(this.gameObject.transform.position, player.transform.position) < 10 && this.tag == "Briefcase") { Destroy(this.gameObject); } } } <file_sep>/Assets/HandleTutorialLevel.cs using UnityEngine; using System.Collections; using UnityEngine.UI; public class HandleTutorialLevel : MonoBehaviour { public Sprite WASD; public Sprite clickFire; public Sprite GPS; public Sprite UseComputer; public Sprite MissionComplete; public Sprite DataServer; public Sprite DoorLocked; public Image thisImage; public Sprite remainStealth; public Sprite howtoFinishLevel; public Sprite GPSExplanation; public Sprite howtoAccessHud; public Sprite dataFileExplain; public GameObject gpsObject; bool removeImage; float age; void Awake() { if (Application.loadedLevelName != "CurrentLevel") { this.enabled = false; } } // Use this for initialization void Start () { // thisImage= this.gameObject.GetComponent<Image>(); age = 0; gpsObject = GameObject.Find("GPSExplantaion"); gpsObject.SetActive(false); } // Update is called once per frame void Update () { if (removeImage) { age += Time.deltaTime; if (age > 3) { age = 0; removeImage = false; } } } void OnTriggerEnter(Collider col) { if (col.gameObject.name == "DataServer") { thisImage.sprite = DataServer; Destroy(col.gameObject); } if (col.gameObject.name == "GPSHandler") { thisImage.sprite = GPS; Destroy(col.gameObject); } if (col.gameObject.name == "UseComputer") { thisImage.sprite = UseComputer; Destroy(col.gameObject); gpsObject.SetActive(true); } if (col.gameObject.name == "WASD") { thisImage.sprite = WASD; Destroy(col.gameObject); } if (col.gameObject.name == "DoorLocked") { Destroy(col.gameObject); thisImage.sprite = DoorLocked; } if (col.gameObject.name == "clickFire") { Destroy(col.gameObject); thisImage.sprite = clickFire; } if (col.gameObject.name == "MissionComplete") { Destroy(col.gameObject); thisImage.sprite = MissionComplete; } if (col.gameObject.name == "remainStealth") { Destroy(col.gameObject); thisImage.sprite = remainStealth; } if (col.gameObject.name == "FinishLevel") { thisImage.sprite = howtoFinishLevel; Destroy(col.gameObject); } if (col.gameObject.name == "GPSExplantaion") { thisImage.sprite = GPSExplanation; Destroy(col.gameObject); } if (col.gameObject.name == "accessHud") { thisImage.sprite = howtoAccessHud; Destroy(col.gameObject); } if (col.gameObject.name == "DataFileExplain") { thisImage.sprite = dataFileExplain; Destroy(col.gameObject); } } } <file_sep>/Assets/Scripts/CreditsScript.cs using UnityEngine; using System.Collections; public class CreditsScript : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update() { if(Input.GetKeyDown(KeyCode.Mouse0)) Application.LoadLevel("MainMenuScene"); } }
7d8343a3f1811c6642e7d5dff29c9ecc97b45e7c
[ "C#" ]
35
C#
chane1994/OperationHarvest
c3178213610cf9906276cefd587007f0d9dd5026
44e1dafe46281038ea46604b1d398956c4ed3465
refs/heads/main
<file_sep># Machine-learning Simple Linear Regression
8c816e0879613ed114ac125a131103bd3efd5617
[ "Markdown" ]
1
Markdown
Narendernayak/Machine-learning
833acb611df81cf4ef03170281031e88148ebdbb
be31c49e6582bdba921287437f5fed5d03f480aa
refs/heads/master
<repo_name>gelsondeveloper/toDoList<file_sep>/README.md # toDoList Lista de Tarefas criada com Javascript
8cbb75fdfcc5e5790ae19c811f5a14d27de293b9
[ "Markdown" ]
1
Markdown
gelsondeveloper/toDoList
b6c644e73991c980c5de998ae2092a35fdb7b17d
23d7020673f0462e0f41bd2295871268ce12dfa1
refs/heads/master
<repo_name>GUDN/anblock<file_sep>/extension/src/rule.ts export interface Rule { url: string disabled: boolean } <file_sep>/extension/src/background.ts import type { Rule } from './rule' import { BlockAlarm, getInfo } from './alarm' import { BACKEND_URL } from './config' import { storageGet } from './storage' function listener(request: chrome.webRequest.ResourceRequest) { return { redirectUrl: `chrome-extension://${chrome.runtime.id}/public/redirect.html`, } } function setRules(rules: Rule[]) { chrome.webRequest.onBeforeRequest.removeListener(listener) if (rules.length) { chrome.webRequest.onBeforeRequest.addListener( listener, { urls: rules .filter(rule => !rule.disabled) .map(rule => `*://${rule.url}/*`), types: ['main_frame'], }, ['blocking'] ) } } async function startBlocking(newValue: string) { const info = JSON.parse(newValue) as BlockAlarm const username = await storageGet('username') const angel = await storageGet('angel') if (!username || !angel) return const url = new URL(`${BACKEND_URL}/lock`) url.search = new URLSearchParams({ angel, username, ttl: info.duration.toString(), }).toString() try { const resp = await fetch(url.toString(), { method: 'POST' }) if (resp.status !== 200) throw `Invalid status code: ${resp.status}` } catch (e) { console.error(e) return } if (info.duration > 0) { chrome.alarms.create('BlockAlarm', { when: Date.parse(info.startTime) + info.duration * 60 * 1000, }) } } chrome.storage.onChanged.addListener(async changes => { let blockActive: boolean if (changes['alarmInfo']) { const { newValue } = changes['alarmInfo'] if (newValue === undefined) { blockActive = false await chrome.alarms.clear('BlockAlarm') } else { blockActive = true await startBlocking(newValue) } } else { blockActive = (await getInfo()) !== null } if (changes['rules'] && blockActive) { const { newValue } = changes['rules'] const rules = JSON.parse(newValue) as Rule[] setRules(rules) } else if (changes['alarmInfo']) { if (blockActive) { const entry = await storageGet('rules') const rules = JSON.parse(entry ?? '[]') as Rule[] setRules(rules) } else { setRules([]) } } }) chrome.alarms.onAlarm.addListener(async alarm => { if (alarm.name !== 'BlockAlarm') return await chrome.storage.sync.remove('alarmInfo') }) <file_sep>/extension/src/pages/main.ts import { Rule } from '../rule' import { storageGet, storageSet } from '../storage' import { BlockAlarm, getInfo as getAlarmInfo } from '../alarm' import { BACKEND_URL } from '../config' function t(text: string): Node { return document.createTextNode(text) } function createWrapper(childs: Node[], className: string | null = null) { const wrapper = document.createElement('div') wrapper.className = className ?? '' childs.forEach(child => wrapper.appendChild(child)) return wrapper } function ruleView( rule: Rule, root: HTMLElement, rules: Rule[], blockActive: boolean ) { const url = document.createElement('span') url.innerText = rule.url const checkbox = document.createElement('input') checkbox.setAttribute('type', 'checkbox') checkbox.checked = !rule.disabled const button = document.createElement('button') button.innerText = 'Delete' if (!blockActive) { button.addEventListener('click', () => storageSet( 'rules', JSON.stringify(rules.filter(it => it.url !== rule.url)) ) ) checkbox.addEventListener('change', () => { storageSet( 'rules', JSON.stringify( rules.map(it => { if (it.url === rule.url) { return { url: rule.url, disabled: !checkbox.checked, } } return it }) ) ) }) } else { button.setAttribute('disabled', 'disabled') checkbox.setAttribute('disabled', 'disabled') } root.appendChild( createWrapper([createWrapper([checkbox, url]), button], 'rule') ) } function listRules(root: HTMLElement, blockActive: boolean) { const wrapper = createWrapper([], 'rules') async function redraw(rules: Rule[]) { wrapper.innerHTML = '<hr />' rules.forEach(rule => ruleView(rule, wrapper, rules, blockActive)) wrapper.appendChild(document.createElement('hr')) } storageGet('rules').then(value => redraw(value ? JSON.parse(value) : [])) chrome.storage.onChanged.addListener(changes => { if (!changes['rules']) return redraw(JSON.parse(changes['rules'].newValue)) }) root.appendChild(wrapper) } function newItemElement(root: HTMLElement) { const input = document.createElement('input') const button = document.createElement('button') button.innerText = 'Add' input.setAttribute('placeholder', 'youtube.com') input.addEventListener('keyup', e => { if (e.code === 'Enter') { e.preventDefault() button.click() } }) button.addEventListener('click', async () => { const value = input.value.trim() if (!value) { return } input.value = '' const rules = JSON.parse((await storageGet('rules')) ?? '[]') as Rule[] if (rules.some(rule => rule.url === value)) { return } rules.push({ url: value, disabled: false, }) storageSet('rules', JSON.stringify(rules)) }) root.appendChild(createWrapper([input, button], 'new-item-wrapper')) } async function stopBlocking() { const username = await storageGet('username') const angel = await storageGet('angel') if (!username || !angel) return const url = new URL(`${BACKEND_URL}/islocked`) url.search = new URLSearchParams({ username, angel }).toString() try { const resp = await fetch(url.toString()) if (resp.status !== 200) return const result = await resp.json() if (result['result']) return } catch (e) { console.error(e) return } await chrome.storage.sync.remove('alarmInfo') } function header(root: HTMLElement, username: string, alarm: BlockAlarm | null) { // username element const usernameElem = document.createElement('h4') usernameElem.innerText = username // angel input const angelInputRegex = /^[a-zA-Z0-9_]+$/ let lastValidangelInput = '' const angelInput = document.createElement('input') angelInput.setAttribute('placeholder', "angel's tgname") function validate() { if (angelInput.value === '' || angelInputRegex.test(angelInput.value)) { lastValidangelInput = angelInput.value storageSet('angel', lastValidangelInput) } else { angelInput.value = lastValidangelInput } } if (alarm === null) { angelInput.addEventListener('input', validate) } else { angelInput.setAttribute('disabled', 'disabled') } storageGet('angel').then(value => (angelInput.value = value ?? '')) // range input const rangeInput = document.createElement('input') rangeInput.setAttribute('type', 'range') rangeInput.setAttribute('min', '0') rangeInput.setAttribute('max', '720') rangeInput.setAttribute('step', '5') const span = document.createElement('span') function updateSpan() { const value = parseInt(rangeInput.value) if (value > 0) { span.innerText = `${value} min.` } else { span.innerText = 'Infinity' } } if (alarm === null) { rangeInput.addEventListener('input', updateSpan) } else { rangeInput.setAttribute('disabled', 'disabled') rangeInput.value = alarm.duration.toString() } updateSpan() // start button const button = document.createElement('button') if (alarm) { const diff = Date.now() - Date.parse(alarm.startTime) button.innerText = `Stop (left ${ alarm.duration - Math.round(diff / 1000 / 60) } min)` button.addEventListener('click', stopBlocking) } else { button.innerText = 'Start' button.addEventListener('click', async () => { const info = { startTime: new Date().toISOString(), duration: parseInt(rangeInput.value), } await storageSet('alarmInfo', JSON.stringify(info)) }) } // mount root.appendChild( createWrapper( [ createWrapper([t('@'), angelInput, t('|'), usernameElem], 'header-row'), createWrapper([rangeInput, span], 'header-row'), createWrapper([button], 'header-row'), ], 'header' ) ) } export default async function mainPage( root: HTMLElement, reload: () => Promise<void> ) { const username = await storageGet('username') if (!username) { return reload() } const alarm = await getAlarmInfo() header(root, username, alarm) listRules(root, alarm !== null) newItemElement(root) } <file_sep>/extension/src/popup.ts import { storageGet } from './storage' import setUsernamePage from './pages/setUsername' import mainPage from './pages/main' const body = document.body async function init() { const username = await storageGet('username') body.innerHTML = '' if (!username) { return setUsernamePage(body, init) } await mainPage(body, init) } chrome.storage.onChanged.addListener(changes => { if (changes['alarmInfo']) init() }) init() <file_sep>/extension/src/pages/setUsername.ts import { storageSet } from '../storage' export default function setUsername( root: HTMLElement, reload: () => Promise<void> ) { const input = document.createElement('input') const inputRegex = /^[a-zA-Z0-9_]+$/ let lastValidInput = '' function validate() { if (input.value === '' || inputRegex.test(input.value)) { lastValidInput = input.value } else { input.value = lastValidInput } } input.className = 'username' input.setAttribute('placeholder', 'Enter username') input.addEventListener('input', validate) input.addEventListener('keyup', e => { if (e.code === 'Enter') { if (input.value.trim()) { storageSet('username', input.value.trim()) .then(reload) .catch(console.error) } e.preventDefault() } }) root.appendChild(input) } <file_sep>/bot/src/db.ts import { config } from 'dotenv' import { Tedis } from 'tedis' config() const tedis = new Tedis({ host: process.env.REDIS_HOST, port: parseInt(process.env.REDIS_PORT), password: process.env.REDIS_PASSWORD, }) function toKey(angel: string, username: string): string { return `${angel}/${username}` } export async function isLocked( angel: string, username: string ): Promise<boolean> { const key = toKey(angel, username) return (await tedis.exists(key)) === 1 } export async function lock(angel: string, username: string, ttl: number = 0) { const key = toKey(angel, username) await tedis.set(key, '1') if (ttl > 0) { await tedis.expire(key, ttl) } } export async function unlock( angel: string, username: string ): Promise<boolean> { const key = toKey(angel, username) return (await tedis.del(key)) > 0 } export async function unlockAll(angel: string): Promise<string[]> { const keys = await tedis.keys(`${angel}/*`) if (!keys.length) return [] // @ts-ignore await tedis.del(...keys) return keys.map(key => key.split('/')[1]) } export async function getLocks(angel: string): Promise<string[]> { const keys = await tedis.keys(`${angel}/*`) return keys.map(key => key.split('/')[1]).sort() } export async function getUserId(username: string): Promise<number | null> { const value = await tedis.hget('uids', username) return value ? parseInt(value) : null } export async function setUserId(username: string, userId: number) { await tedis.hset('uids', username, userId.toString()) } <file_sep>/bot/src/index.ts import { config } from 'dotenv' import express, { Request, Response } from 'express' import { Markup } from 'telegraf' import { bot } from './bot' import { getUserId, isLocked, lock, unlock } from './db' config() const app = express() const PORT = parseInt(process.env.PORT) const WEBHOOK_PATH = process.env.WEBHOOK_PATH as string if (WEBHOOK_PATH === undefined) { console.error('WEBHOOK_PATH must be provided') process.exit(1) } app.get('/islocked', async (req: Request, res: Response) => { const angel = req.query['angel'] const username = req.query['username'] if (!angel || !username) { return res.status(400).end() } const result = await isLocked( typeof angel === 'string' ? angel : angel[0], typeof username === 'string' ? username : username[0] ) res.json({ result: result }).end() }) app.post('/lock', async (req: Request, res: Response) => { const angels = req.query['angel'] const usernames = req.query['username'] if (!angels || !usernames) { return res.status(400).end() } const angel = typeof angels === 'string' ? angels : angels[0] const username = typeof usernames === 'string' ? usernames : usernames[0] let ttl = 0 if (req.query['ttl']) { const ttlQuery = req.query['ttl'] if (typeof ttlQuery === 'string') ttl = parseInt(ttlQuery) else ttl = parseInt(ttlQuery[0]) } await lock(angel, username, ttl * 60) const userId = await getUserId(angel) if (userId) { bot.telegram.sendMessage( userId, `New lock for ${username}`, Markup.inlineKeyboard([ [ { text: 'Unlock', callback_data: username, }, ], ]) ) } res.status(200).end() }) bot.telegram.setWebhook(`${WEBHOOK_PATH}/tg`) app.use(bot.webhookCallback('/tg')) app.listen(PORT, () => console.log(`Listening on port ${PORT}`)) <file_sep>/bot/src/bot.ts import { config } from 'dotenv' import { Telegraf, Markup } from 'telegraf' import { getLocks, unlock, unlockAll, setUserId } from './db' config() export const bot = new Telegraf(process.env.BOT_TOKEN) bot.use(async (ctx, next) => { if (ctx.message) { await setUserId(ctx.message.from.username, ctx.message.from.id) } await next() }) bot.command('unlockall', async ctx => { const username = ctx.message.from.username const keys = await unlockAll(username) if (keys.length) { ctx.reply(`Unlocked ${keys.join(', ')}`) } else ctx.reply('No locks') }) bot.command('locks', async ctx => { const locks = await getLocks(ctx.message.from.username) if (locks.length) { const items = locks.map(lock => ({ text: lock, callback_data: lock })) const rows = [] for (let i = 0; i < items.length; i += 3) { const row = items.slice(i, i + 3) rows.push(row) } ctx.reply('Current locks:', Markup.inlineKeyboard(rows)) } else ctx.reply('No current active locks', Markup.removeKeyboard()) }) bot.action(/.+/, async ctx => { const username = ctx.callbackQuery.from.username // @ts-ignore const target = ctx.callbackQuery.data const result = await unlock(username, target) if (result) { ctx.answerCbQuery(`${target} unlocked`) } else ctx.answerCbQuery(`No lock for ${target}`) const locks = await getLocks(username) const message = ctx.callbackQuery.message if (locks.length) { const items = locks.map(lock => ({ text: lock, callback_data: lock })) const rows = [] for (let i = 0; i < items.length; i += 3) { const row = items.slice(i, i + 3) rows.push(row) } ctx.tg.editMessageReplyMarkup( message.chat.id, message.message_id, undefined, { inline_keyboard: rows } ) } else { ctx.tg.editMessageText( message.chat.id, message.message_id, undefined, 'No current active locks' ) } }) <file_sep>/extension/src/alarm.ts import { storageGet } from './storage' export interface BlockAlarm { startTime: string duration: number } export async function getInfo(): Promise<BlockAlarm | null> { const entry = await storageGet('alarmInfo') if (!entry) return null else return JSON.parse(entry) as BlockAlarm } <file_sep>/extension/src/storage.ts export function storageGet(key: string): Promise<string | undefined> { return new Promise((resolve, reject) => chrome.storage.sync.get([key], items => { if (chrome.runtime.lastError) { return reject(chrome.runtime.lastError) } return resolve(items[key]) }) ) } export function storageSet(key: string, value: string): Promise<void> { return new Promise((resolve, reject) => { chrome.storage.sync.set({ [key]: value }, () => { if (chrome.runtime.lastError) { return reject(chrome.runtime.lastError) } return resolve() }) }) }
7156a1901a4973832a27e9ca789bde1eb9f5a76a
[ "TypeScript" ]
10
TypeScript
GUDN/anblock
25a9dcf7c52512beeff044355f5784f68dd447bd
c04fa14ce6490728115f6d0d1fc584d3329318b4
refs/heads/master
<repo_name>chufnagel/testtaker<file_sep>/packages/server/server.js const bodyParser = require("body-parser"); const cors = require("cors"); const express = require("express"); const next = require("next"); const logger = require("morgan"); const dev = process.env.NODE_ENV !== "production"; const app = next({ dev }); const handle = app.getRequestHandler(); const port = parseInt(process.env.PORT, 10) || 3000; app .prepare() .then(() => { const server = express(); server.use(bodyParser.json()); server.use(bodyParser.urlencoded({ extended: false })); server.use(logger("dev")); server.use(cors()); server.get("/quiz", (req, res) => { console.log("/quiz requested"); console.log(req.query); return app.render(req, res, "/quiz", req.query); }); server.get("/results", (req, res) => { console.log("/results requested"); console.log(req.query); return app.render(req, res, "/quiz", req.query); }); server.get("/", (req, res) => { console.log("/ requested"); console.log(req.query); return app.render(req, res, "/", req.query); }); server.get("*", (req, res) => handle(req, res)); server.listen(port, err => { if (err) throw err; console.log(`> Ready on http://localhost:${port}`); }); }) .catch(ex => { console.error(ex.stack); process.exit(1); }); module.exports = app; <file_sep>/packages/client/pages/testview.js import React, { Component } from "react"; import Layout from "../components/Layout"; // import passage from "../static/passage.json"; import "isomorphic-unfetch"; // import questions from "../static/questions.json"; // const Test = (props) = ( // <Layout> // <h1>`({this.props.passage.passageId})`</h1> // </Layout> // ) // export default class Test extends Component { // static async getInitialProps () { // const res = await fetch("") // const json = await res.json(); // return { passage: json.passage }; // } // render() { // const { passage } = this.props; // return ( // <Layout> // <p>{passage}</p> // </Layout> // ); // } // } const Test = props => { const data = import("../static/passage.json"); return ( <Layout> {Object.keys(data).map(key => ( <Line key={key} text={data.key} /> ))} </Layout> ); }; // Test.getInitialProps = async ({ req }) => { // const baseUrl = req ? `${req.protocol}://${req.get("Host")}` : ""; // const res = await fetch(baseUrl + "/static/passage.json"); // const json = await res.json(); // const passage = json.passage; // console.log(passage); // return { passage: passage }; // }; export default Test; <file_sep>/packages/client/components/Question.spec.js /* global beforeEach describe, expect, test */ import { shallow } from "enzyme"; import Question from "./Question"; // Question.defaultProps = { // id: 1, // text: "Lorem ipsum", // }; describe("Question", () => { let wrapper; beforeEach(() => { wrapper = shallow(<Question />); }); test("It should render without crashing", () => { expect(wrapper.exists()).toEqual(true); }); test("Question matches snapshot", () => { expect(wrapper).toMatchSnapshot(); }); }); <file_sep>/packages/client/components/SubmitButton.spec.js /* global beforeEach describe, expect, test */ import { shallow } from "enzyme"; import SubmitButton from "./SubmitButton"; // SubmitButton.propTypes = { // action: PropTypes.func.isRequired, // path: PropTypes.string.isRequired, // query: PropTypes.string.isRequired, // }; const mockFn = jest.fn(); describe("SubmitButton", () => { let wrapper; beforeEach(() => { wrapper = shallow(<SubmitButton action={mockFn} text="Submit" path="/" query={{}} />); }); test("It should render without crashing", () => { expect(wrapper.exists()).toEqual(true); }); test("SubmitButton matches snapshot", () => { expect(wrapper).toMatchSnapshot(); }); }); <file_sep>/packages/client/components/results/QuestionAnswerCard.spec.js /* global beforeEach describe, expect, test */ import { shallow } from "enzyme"; import QuestionAnswerCard from "./QuestionAnswerCard"; // QuestionAnswerCard.propTypes = { // id: PropTypes.number, // text: PropTypes.string, // correct: PropTypes.string, // userAnswer: PropTypes.string, // answers: PropTypes.arrayOf(PropTypes.object), // }; describe("QuestionAnswerCard", () => { let wrapper; beforeEach(() => { wrapper = shallow(<QuestionAnswerCard />); }); test("It should render without crashing", () => { expect(wrapper.exists()).toEqual(true); }); test("QuestionAnswerCard matches snapshot", () => { expect(wrapper).toMatchSnapshot(); }); }); <file_sep>/packages/client/components/quiz/Answer.spec.js /* global beforeEach describe, expect, test */ import { shallow } from "enzyme"; import Answer from "./Answer"; // Answer.propTypes = { // questionId: PropTypes.string, // choice: PropTypes.string, // text: PropTypes.string, // onSelect: PropTypes.func.isRequired, // checked: PropTypes.bool, // }; // Answer.defaultProps = { // questionId: 1, // choice: "A", // text: "Lorem ipsum", // checked: false, // }; const mockFn = jest.fn(); describe("Answer", () => { let wrapper; beforeEach(() => { wrapper = shallow(<Answer onSelect={mockFn} />); }); test("It should render without crashing", () => { expect(wrapper.exists()).toEqual(true); }); test("Answer matches snapshot", () => { expect(wrapper).toMatchSnapshot(); }); }); <file_sep>/packages/client/components/QuizNavButton.js import PropTypes from "prop-types"; const QuizNavButton = ({ disabled, direction }) => ( <button disabled={disabled} className={`quizNavButton ${direction}`} direction={direction} type="button" > {direction} </button> ); QuizNavButton.propTypes = { disabled: PropTypes.bool, direction: PropTypes.string, }; QuizNavButton.defaultProps = { disabled: true, direction: "Next", }; export default QuizNavButton; <file_sep>/packages/client/pages/quiz.js // import fetch from "isomorphic-unfetch"; import PropTypes from "prop-types"; import Layout from "../components/Layout"; import QuizContainer from "../components/quiz/QuizContainer"; import passage1 from "../static/passage.json"; import questions1 from "../static/questions.json"; const Quiz = ({ passage, questions, subject }) => ( <Layout> <h1>{subject}</h1> <QuizContainer passage={passage} questions={questions} subject={subject} /> </Layout> ); Quiz.getInitialProps = async () => { const passage = passage1; const questions = questions1; const subject = "Latin"; return { passage, questions, subject, }; }; Quiz.propTypes = { passage: PropTypes.arrayOf(PropTypes.object).isRequired, questions: PropTypes.arrayOf(PropTypes.object).isRequired, subject: PropTypes.string.isRequired, }; export default Quiz; <file_sep>/packages/client/components/results/QuestionAnswerCard.js import PropTypes from "prop-types"; import Question from "../Question"; // iterate through answers // highlight correct answer with green text // if correct !== userAnswer // highlight incorrect answer with red text const getClassName = (correct, choice, userAnswer) => { let className = "radio-row"; if (correct === choice) { className = "radio-row correct"; } else if (correct !== userAnswer && userAnswer === choice) { className = "radio-row incorrect"; } return className; }; const QuestionAnswerCard = ({ id, text, correct, userAnswer, answers }) => { return ( <div className="answer-card card"> <Question id={id} text={text} /> {userAnswer === correct ? ( <p className="correct">Great!</p> ) : ( <p className="incorrect"> You answered {userAnswer}, but the right answer was {correct} </p> )} {answers.map(answer => ( <Answer questionId={answer.questionId} choice={answer.choice} key={answer.choice} text={answer.content} checked={correct === answer.choice} className={getClassName(correct, answer.choice, userAnswer)} /> ))} </div> ); }; QuestionAnswerCard.propTypes = { id: PropTypes.number, text: PropTypes.string, correct: PropTypes.string, userAnswer: PropTypes.string, answers: PropTypes.arrayOf(PropTypes.object), }; QuestionAnswerCard.defaultProps = { id: 1, text: "Navita (line 2) refers to", correct: "A", userAnswer: "B", answers: [ { choice: "A", content: "Evander", }, { choice: "B", content: "Latinus", }, { choice: "C", content: "Priam", }, { choice: "D", content: "Juturna", }, ], }; const Answer = ({ questionId, choice, text, checked, correct, className }) => ( <div className={className} key={`${questionId}${choice}`} aria-checked={checked} checked={checked} role="radio" tabIndex="0" > <input key={`${questionId}:${choice}`} name="answer" value={text} type="radio" /> {`${choice} - `} {`${text}`} <br /> </div> ); export default QuestionAnswerCard; <file_sep>/.travis.yml language: node_js node_js: - '11.4.0' install: - npm install <file_sep>/packages/client/components/quiz/QuestionContainer.js import PropTypes from "prop-types"; import Answer from "./Answer"; import Question from "../Question"; const QuestionContainer = ({ question, handleSelect }) => ( <div className="card"> <Question id={question.id} text={question.text} /> <form> {question.answers.map(answer => ( <Answer questionId={question.id} choice={answer.choice} key={answer.choice} text={answer.content} onSelect={handleSelect} checked={answer.choice === question.userAnswer} /> ))} </form> </div> ); QuestionContainer.propTypes = { question: PropTypes.shape({ id: PropTypes.number, text: PropTypes.string, answers: PropTypes.arrayOf(PropTypes.object), }), handleSelect: PropTypes.func.isRequired, }; QuestionContainer.defaultProps = { question: { id: 1, text: "Lorem ipsum", answers: [{ a: "Lorem ipsum" }], }, }; export default QuestionContainer; <file_sep>/packages/client/components/results/Result.js import PropTypes from "prop-types"; import Passage from "../Passage"; import ProgressBar from "../ProgressBar"; import QuestionAnswerCard from "./QuestionAnswerCard"; const Result = ({ passage, questions, totalCorrect, totalQuestions, elapsedTime, totalTime }) => { const correct = (totalCorrect / totalQuestions) * 100; const elapsed = (elapsedTime / totalTime) * 100; let renderPassage; if (passage) { renderPassage = <Passage passage={passage} />; } else { renderPassage = <div />; } return ( <div> <h1>Results</h1> <ProgressBar percentage={correct} /> <p> {totalCorrect} out of {totalQuestions} correct </p> <ProgressBar percentage={elapsed} /> <p> {elapsedTime} out of {totalTime} used </p> {renderPassage} {questions.map(question => ( <QuestionAnswerCard key={question.id} {...question} /> ))} </div> ); }; Result.propTypes = { // questions: PropTypes.arrayOf(PropTypes.object).isRequired, questions: PropTypes.arrayOf(PropTypes.object), // answers: PropTypes.arrayOf(PropTypes.object).isRequired, // correctAnswers: PropTypes.arrayOf(PropTypes.object).isRequired, passage: PropTypes.arrayOf(PropTypes.object), totalCorrect: PropTypes.number, totalQuestions: PropTypes.number, elapsedTime: PropTypes.number, totalTime: PropTypes.number, }; Result.defaultProps = { questions: [ { id: 1, text: "Navita (line 2) refers to", correct: "A", userAnswer: "B", answers: [ { choice: "A", content: "Evander", }, { choice: "B", content: "Latinus", }, { choice: "C", content: "Priam", }, { choice: "D", content: "Juturna", }, ], }, ], passage: [ { line: "1", text: "Ergo iter inceptum peragunt fluvioque propinquant.", }, ], totalCorrect: 15, totalQuestions: 20, elapsedTime: 15, totalTime: 15, }; export default Result; <file_sep>/packages/client/components/quiz/QuizContainer.js import React, { Component } from "react"; import PropTypes from "prop-types"; import Passage from "../Passage"; import QuestionContainer from "./QuestionContainer"; import Timer from "../Timer"; import SubmitButton from "../SubmitButton"; class QuizContainer extends Component { state = { questions: [], answers: {}, originalTime: "", minutes: "20", seconds: "00", subject: "Latin", }; componentDidMount = () => { const { questions, passage, subject, minutes } = this.props; this.setState(() => ({ questions, passage, subject, minutes, originalTime: minutes, })); this.startTest(); }; tick = () => { const min = Math.floor(this.secondsRemaining / 60); const sec = this.secondsRemaining - min * 60; this.setState({ minutes: min, seconds: sec, }); if (sec < 10) { this.setState(prevState => ({ seconds: `0${prevState.seconds}`, })); } if (min < 10) { this.setState(prevState => ({ minutes: `0${prevState.minutes}`, })); } if (!min && !sec) { clearInterval(this.handleInterval); this.submitQuiz(); } this.secondsRemaining -= 1; }; startTest = () => { this.handleInterval = setInterval(this.tick, 1000); const time = this.state.minutes; this.secondsRemaining = time * 60; }; handleSelect = (questionId, choice) => { const { questions } = this.state; // console.log(questions); const answered = questions[questionId - 1]; // console.log(answered); answered.userAnswer = choice; console.log(answered); this.setState(() => ({ questions, })); // console.log(questions); // questions[questionId + 1] = choice; // console.log(questions[questionId + 1]); // const answer = {}; // answer[questionId].selected = choice; // this.setState(prevState => ({ // answers: Object.assign(prevState.answers, { answer }), // })); // this.setState(prevState => ({ // answers: Object.assign(prevState.answers, { answer }), // questions, // })); }; submitQuiz = () => { // add elapsed time to results later // const { questions, answers, originalTime } = this.state; console.log("Render results!"); // return <Results answers={answers} />; }; render() { const { minutes, seconds, passage, questions, answers, subject } = this.state; const { handleSelect, submitQuiz } = this; return ( <div> <Timer minutes={minutes} seconds={seconds} /> {passage ? <Passage passage={passage} /> : <div />} {/* <Passage passage={passage} /> */} <div className="cards"> {questions.map(question => ( <QuestionContainer key={question.id} handleSelect={handleSelect} question={question} /> ))} </div> <SubmitButton path="/results" query={{ subject, questions, answers }} action={submitQuiz} text="Submit" /> </div> ); } } export default QuizContainer; QuizContainer.propTypes = { passage: PropTypes.arrayOf(PropTypes.object), questions: PropTypes.arrayOf(PropTypes.object), subject: PropTypes.string, minutes: PropTypes.number, }; QuizContainer.defaultProps = { subject: "Latin", passage: [ { line: "1", text: "Ergo iter inceptum peragunt fluvioque propinquant.", }, ], questions: [ { id: 1, text: "Navita (line 2) refers to", answers: [ { choice: "A", content: "Evander", }, { choice: "B", content: "Latinus", }, { choice: "C", content: "Priam", }, { choice: "D", content: "Juturna", }, ], }, ], minutes: 20, }; <file_sep>/packages/client/pages/index.js import fetch from "isomorphic-unfetch"; import Link from "next/link"; import Layout from "../components/Layout"; import Start from "../components/start/Start"; import passage1 from "../static/passage.json"; import questions1 from "../static/questions.json"; import subjects1 from "../static/subjects.json"; const Index = props => { // const { subjects } = props; return ( <Layout> <Start /> {/* <Start subjects={subjects} /> */} </Layout> ); }; export default Index; Index.getInitialProps = async () => { const subjects = subjects1; return { subjects, }; }; <file_sep>/packages/client/jest.config.js const jestBase = require("tools/jest.config.js"); module.exports = { ...jestBase, snapshotSerializers: ["enzyme-to-json/serializer"], setupFiles: ["<rootDir>/testSetup.js"], testPathIgnorePatterns: ["<rootDir>/.next/", "<rootDir>/node_modules/"], moduleNameMapper: { "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/fileMock.js", }, }; <file_sep>/packages/client/components/quiz/Answer.js import PropTypes from "prop-types"; const Answer = ({ questionId, choice, text, onSelect, key, checked }) => ( <div className="radio-row" key={key} onClick={() => onSelect(questionId, choice)} onKeyPress={() => onSelect(questionId, choice)} aria-checked={checked} checked={checked} role="radio" tabIndex="0" > <input key={`${questionId}:${choice}`} name="answer" value={text} type="radio" /> {`${choice} - `} {`${text}`} <br /> </div> ); Answer.propTypes = { questionId: PropTypes.number, choice: PropTypes.string, text: PropTypes.string, key: PropTypes.string, onSelect: PropTypes.func.isRequired, checked: PropTypes.bool, }; Answer.defaultProps = { questionId: 1, choice: "A", key: "A", text: "Lorem ipsum", checked: false, }; export default Answer; <file_sep>/packages/client/components/Timer.js const Timer = ({ minutes, seconds }) => ( <div className="timer" style={{ marginLeft: 1 }}> <span> {minutes}:{seconds} </span> </div> ); export default Timer; <file_sep>/packages/client/components/quiz/QuizContainer.spec.js /* global beforeEach describe, expect, test */ import { shallow } from "enzyme"; import QuizContainer from "./QuizContainer"; // QuizContainer.propTypes = { // action: PropTypes.func.isRequired, // path: PropTypes.string.isRequired, // query: PropTypes.string.isRequired, // }; const props = {}; props.passage = [ { line: "1", text: "Ergo iter inceptum peragunt fluvioque propinquant.", }, ]; props.questions = [ { id: 1, text: "Navita (line 2) refers to", answers: [ { choice: "A", content: "Evander", }, { choice: "B", content: "Latinus", }, { choice: "C", content: "Priam", }, { choice: "D", content: "Juturna", }, ], }, ]; props.subject = "Test"; // const mockFn = jest.fn(); // const mapSubject = "Test"; describe("QuizContainer", () => { let wrapper; beforeEach(() => { wrapper = shallow(<QuizContainer {...props} />); }); test("It should render without crashing", () => { expect(wrapper.exists()).toEqual(true); }); test("QuizContainer matches snapshot", () => { expect(wrapper).toMatchSnapshot(); }); }); <file_sep>/packages/client/.prettierrc.js module.exports = require('tools/.prettierrc.js'); <file_sep>/packages/client/.eslintrc.js const baseConfig = require('tools/.eslintrc'); module.exports = { ...baseConfig, rules: { ...baseConfig.rules, "react/forbid-prop-types": 1, } }; <file_sep>/packages/client/components/SubmitButton.js import Link from "next/link"; import PropTypes from "prop-types"; const SubmitButton = ({ path, query, action, text }) => ( <div style={{ marginLeft: 130 }}> <Link href={{ pathname: path, query }}> <button onClick={action} type="button"> {text} </button> </Link> </div> ); SubmitButton.propTypes = { action: PropTypes.func.isRequired, path: PropTypes.string.isRequired, query: PropTypes.object.isRequired, text: PropTypes.string.isRequired, }; export default SubmitButton; <file_sep>/packages/client/components/start/TimerInput.spec.js /* global beforeEach describe, expect, test */ import { shallow } from "enzyme"; import TimerInput from "./TimerInput"; // TimerInput.propTypes = { // action: PropTypes.func.isRequired, // path: PropTypes.string.isRequired, // query: PropTypes.string.isRequired, // }; const mockFn = jest.fn(); describe("TimerInput", () => { let wrapper; beforeEach(() => { wrapper = shallow(<TimerInput action={mockFn} />); }); test("It should render without crashing", () => { expect(wrapper.exists()).toEqual(true); }); test("TimerInput matches snapshot", () => { expect(wrapper).toMatchSnapshot(); }); }); <file_sep>/packages/client/components/start/Start.js import React, { Component } from "react"; import Timer from "../Timer"; import TimerInput from "./TimerInput"; import SubmitButton from "../SubmitButton"; import Dropdown from "../Dropdown"; class Start extends Component { state = { minutes: "20", seconds: "00", subjects: ["Latin"], subject: "Latin", }; // componentDidMount = () => { // const receivedSubjects = []; // for (let subject of this.props.subjects) { // receivedSubjects.push(subject); // } // this.setState(() => ({ // subjects: receivedSubjects, // })); // }; handleSettings = event => { const { name, value } = event.target; this.setState(() => ({ [name]: value, })); }; startTest = event => { const { subject, minutes } = this.state; console.log(`${subject}, ${minutes}`); }; render() { const { minutes, seconds, subjects, subject } = this.state; const { handleSettings, startTest } = this; return ( <div> <Timer minutes={minutes} seconds={seconds} /> <TimerInput action={handleSettings} minutes={minutes} /> <Dropdown action={handleSettings} choices={subjects} name="subject" /> <SubmitButton path="/quiz" query={{ subject, minutes }} action={startTest} text="Start" /> </div> ); } } export default Start; <file_sep>/packages/client/components/quiz/QuestionContainer.spec.js /* global beforeEach describe, expect, test */ import { shallow } from "enzyme"; import QuestionContainer from "./QuestionContainer"; // QuestionContainer.propTypes = { // question: PropTypes.shape({ // id: PropTypes.string, // text: PropTypes.string, // answers: PropTypes.arrayOf(PropTypes.obj), // }), // handleSelect: PropTypes.func.isRequired, // }; const mockFn = jest.fn(); describe("QuestionContainer", () => { let wrapper; beforeEach(() => { wrapper = shallow(<QuestionContainer handleSelect={mockFn} />); }); test("It should render without crashing", () => { expect(wrapper.exists()).toEqual(true); }); test("QuestionContainer matches snapshot", () => { expect(wrapper).toMatchSnapshot(); }); }); <file_sep>/packages/client/components/Layout.js import Meta from "./Meta"; import Header from "./Header"; const Layout = props => ( <div> <Meta /> <style jsx global>{` body { background: DarkBlue; color: white; text-align: center; align-items: center; justify-content: center; display: flex; } a { color: white; text-decoration: none; padding: 1em; } .passage-container { clear: both; top: 0; position: sticky; } .passage { text-align: left; display: flex; } .spacer { width: 100%; height: 95px; } .header { display: block; margin: 0em; padding: 1em; border-style: solid; border-color: black; font-size: 1.5em; border-width: 0.2em; } .timer { display: flex; flex-flow: row reverse; margin-left: auto; justify-content: flex-end; font-weight: bold; font-size: large; text-align: right; border: 2px solid black; border-style: double; } .nav { } .cards { position: relative; display: flex; flex-flow: row wrap; justify-content: center; align-items: center; } .card { background: grey; border: 2px solid black; box-sizing: border-box; border-radius: 6px; box-padding: 1.25rem; padding: 20px; display: flex; flex-direction: column; margin: 5px; height: 100%; } .radio-row { text-align: left; align-items: center; justify-content: center; } .question { } radio { } .progress-bar { position: relative; height: 20px; width: 350px; border-radius: 50px; border: 1px solid #333; } .progress { background: #1da598; height: 100%; border-radius: inherit; transition: width 0.2s ease-in; } .correct { color: green; } .incorrect { color: red; } `}</style> <Header /> {props.children} </div> ); export default Layout; // flex: 1 0 21%; // .cards { // position: relative; // display: flex; // flex-flow: row wrap; // justify-content: space-between; // } // .card { // box-sizing: border-box; // padding: 20px; // flex: 1; // margin: 5px; // height: 100px; // } <file_sep>/packages/client/pages/results.js // import fetch from "isomorphic-unfetch"; // import axios from "axios"; import Layout from "../components/Layout"; import Result from "../components/results/Result"; const questions = [ { id: 1, text: "Navita (line 2) refers to", correct: "A", userAnswer: "B", answers: [ { choice: "A", content: "Evander", }, { choice: "B", content: "Latinus", }, { choice: "C", content: "Priam", }, { choice: "D", content: "Juturna", }, ], }, ]; const Results = props => { return ( <Layout> <Result {...props} /> </Layout> ); }; Results.getInitialProps = async () => { const props = {}; props.totalCorrect = 15; props.totalQuestions = 20; props.elapsedTime = 15; props.totalTime = 20; props.questions = questions; props.passage = [ { line: "1", text: "Ergo iter inceptum peragunt fluvioque propinquant.", }, ]; return props; }; // Results.getInitialProps = async () => { // const response = await axios({ // method: "get", // url: url + // }) // } export default Results; <file_sep>/packages/tools/jest.config.js module.exports = { snapshotSerializers: ["enzyme-to-json/serializer"], setupFiles: ["<rootDir>/src/testSetup.js"], testPathIgnorePatterns: [["<rootDir>/.next/", "<rootDir>/node_modules/"]], moduleNameMapper: { "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/src/tests/fileMock.js", }, modulePathIgnorePatterns: ["./e2etests"], };
8e434e6f6c1419e823fc942183d5e3569f37cc71
[ "JavaScript", "YAML" ]
27
JavaScript
chufnagel/testtaker
70017056ea3c7272d7176c5f0d427776fa06218f
47aff132ec74a6e6fe34bbb11dca9fae1aca5a42
refs/heads/master
<file_sep>import pymysql import pymysql.cursor class DBconnector: def __init__(self): self.host = '192.168.56.101', self.user = 'admin', self.password = '<PASSWORD>', self.db = 'tarefas', charset = 'utf8' cursorclass=pymysql.cursors.DictCursor def add_tarefas(a,b,c,d,e): descricao = a prioridade = b dataConclusao = c foiConcluido = d nome = e with con: cur = con.cursor() cur.execute("INSERT INTO tarefas.tarefas_table(descrição,prioridade,data_conclusao,foi_concluido, nome) VALUES('"+descricao+"','"+prioridade+"','"+dataConclusao+"','"+foiConcluido+"','"+nome+")") cur.execute("SELECT * FROM tarefas_table") rows = cur.fetchall() def listar(): for row in rows: print(row["id"], row["nome"], row["descricao"], row["prioridade"], row["data_conclusao"], row["foi_concluido"]) def deletar_tarefa(a): linha = a with con: cur = con.cursor() cur.execute("SELECT * FROM tarefas_table") cur.execute("DELETE FROM tarefas_table WHERE id = '"+linha+"';") rows = cur.fetchall()
7dfc5353b1ee94034e45a9aba2b0b52cef0a2d7c
[ "Python" ]
1
Python
BrunoDemartini/ListaTarefasDB
6898757c3db834585da0bbd732d87ac0137a1849
3cb55c8ff945e9fb0295e90861dda2978ba797a6
refs/heads/master
<repo_name>marfurt/measurements<file_sep>/tests/Units/UnitDispersionTests.php <?php namespace Tests\Units; use PHPUnit\Framework\TestCase; use Measurements\Measurement; use Measurements\Units\UnitDispersion; class UnitDispersionTests extends TestCase { use InteractsWithUnits; /** @test */ public function it_defines_parts_per_million_as_base_unit() { $this->assertTrue(UnitDispersion::baseUnit() == UnitDispersion::partsPerMillion(), "Dispersion should define parts per million as its base unit."); } /** @test */ public function it_converts_dispersions() { $base = new Measurement(1, UnitDispersion::baseUnit()); $this->assertMeasurementEquals($base->convertTo(UnitDispersion::partsPerMillion()), 1.0, $base, "parts per million"); } }<file_sep>/tests/Units/UnitElectricCurrentTests.php <?php namespace Tests\Units; use PHPUnit\Framework\TestCase; use Measurements\Measurement; use Measurements\Units\UnitElectricCurrent; class UnitElectricCurrentTests extends TestCase { use InteractsWithUnits; /** @test */ public function it_defines_amperes_as_base_unit() { $this->assertTrue(UnitElectricCurrent::baseUnit() == UnitElectricCurrent::amperes(), "Electric current should define amperes as its base unit."); } /** @test */ public function it_converts_electric_currents() { $base = new Measurement(1, UnitElectricCurrent::baseUnit()); $this->assertMeasurementEquals($base->convertTo(UnitElectricCurrent::megaamperes()), 1E-6, $base, "megaamperes"); $this->assertMeasurementEquals($base->convertTo(UnitElectricCurrent::kiloamperes()), 0.001, $base, "kiloamperes"); $this->assertMeasurementEquals($base->convertTo(UnitElectricCurrent::amperes()), 1.0, $base, "amperes"); $this->assertMeasurementEquals($base->convertTo(UnitElectricCurrent::milliamperes()), 1000, $base, "milliamperes"); $this->assertMeasurementEquals($base->convertTo(UnitElectricCurrent::microamperes()), 1E+6, $base, "microamperes"); } }<file_sep>/tests/Units/UnitIlluminanceTests.php <?php namespace Tests\Units; use PHPUnit\Framework\TestCase; use Measurements\Measurement; use Measurements\Units\UnitIlluminance; class UnitIlluminanceTests extends TestCase { use InteractsWithUnits; /** @test */ public function it_defines_lux_as_base_unit() { $this->assertTrue(UnitIlluminance::baseUnit() == UnitIlluminance::lux(), "Illuminance should define lux as its base unit."); } /** @test */ public function it_converts_lengths() { $base = new Measurement(1, UnitIlluminance::baseUnit()); $this->assertMeasurementEquals($base->convertTo(UnitIlluminance::lux()), 1.0, $base, "lux"); } }<file_sep>/doc/ApiIndex.md API Index ========= * Measurements * [Comparable](Measurements-Comparable.md) * Measurements\Converters * [UnitConverterLinear](Measurements-Converters-UnitConverterLinear.md) * [UnitConverterReciprocal](Measurements-Converters-UnitConverterReciprocal.md) * [BaseUnitConvertible](Measurements-BaseUnitConvertible.md) * [Dimension](Measurements-Dimension.md) * [Equatable](Measurements-Equatable.md) * Measurements\Exceptions * [MeasurementValueException](Measurements-Exceptions-MeasurementValueException.md) * [UnitException](Measurements-Exceptions-UnitException.md) * Measurements\Quantities * [Acceleration](Measurements-Quantities-Acceleration.md) * [Angle](Measurements-Quantities-Angle.md) * [Area](Measurements-Quantities-Area.md) * [ConcentrationMass](Measurements-Quantities-ConcentrationMass.md) * [Dispersion](Measurements-Quantities-Dispersion.md) * [Duration](Measurements-Quantities-Duration.md) * [ElectricCharge](Measurements-Quantities-ElectricCharge.md) * [ElectricCurrent](Measurements-Quantities-ElectricCurrent.md) * [ElectricPotentialDifference](Measurements-Quantities-ElectricPotentialDifference.md) * [ElectricResistance](Measurements-Quantities-ElectricResistance.md) * [Energy](Measurements-Quantities-Energy.md) * [Frequency](Measurements-Quantities-Frequency.md) * [FuelEfficiency](Measurements-Quantities-FuelEfficiency.md) * [Illuminance](Measurements-Quantities-Illuminance.md) * [Length](Measurements-Quantities-Length.md) * [Mass](Measurements-Quantities-Mass.md) * [Power](Measurements-Quantities-Power.md) * [Pressure](Measurements-Quantities-Pressure.md) * [Radioactivity](Measurements-Quantities-Radioactivity.md) * [Speed](Measurements-Quantities-Speed.md) * [Temperature](Measurements-Quantities-Temperature.md) * [Volume](Measurements-Quantities-Volume.md) * [Unit](Measurements-Unit.md) * [UnitConverter](Measurements-UnitConverter.md) * Measurements\Units * [UnitAcceleration](Measurements-Units-UnitAcceleration.md) * [UnitAngle](Measurements-Units-UnitAngle.md) * [UnitArea](Measurements-Units-UnitArea.md) * [UnitConcentrationMass](Measurements-Units-UnitConcentrationMass.md) * [UnitDispersion](Measurements-Units-UnitDispersion.md) * [UnitDuration](Measurements-Units-UnitDuration.md) * [UnitElectricCharge](Measurements-Units-UnitElectricCharge.md) * [UnitElectricCurrent](Measurements-Units-UnitElectricCurrent.md) * [UnitElectricPotentialDifference](Measurements-Units-UnitElectricPotentialDifference.md) * [UnitElectricResistance](Measurements-Units-UnitElectricResistance.md) * [UnitEnergy](Measurements-Units-UnitEnergy.md) * [UnitFrequency](Measurements-Units-UnitFrequency.md) * [UnitFuelEfficiency](Measurements-Units-UnitFuelEfficiency.md) * [UnitIlluminance](Measurements-Units-UnitIlluminance.md) * [UnitLength](Measurements-Units-UnitLength.md) * [UnitMass](Measurements-Units-UnitMass.md) * [UnitPower](Measurements-Units-UnitPower.md) * [UnitPressure](Measurements-Units-UnitPressure.md) * [UnitRadioactivity](Measurements-Units-UnitRadioactivity.md) * [UnitSpeed](Measurements-Units-UnitSpeed.md) * [UnitTemperature](Measurements-Units-UnitTemperature.md) * [UnitVolume](Measurements-Units-UnitVolume.md) <file_sep>/src/Exceptions/UnitException.php <?php namespace Measurements\Exceptions; class UnitException extends \Exception {} <file_sep>/src/Units/UnitElectricCharge.php <?php namespace Measurements\Units; use Measurements\Dimension; use Measurements\Converters\UnitConverterLinear; /** * The `UnitElectricCharge` class encapsulates units of measure for electric charge. * You typically use instances of `UnitElectricCharge` to represent specific quantities of electric charge using the `Measurement` class. * Electric charge is a fundamental physical property of matter that causes it to experience a force within an electromagnetic field. * The SI unit for electric charge is the coulomb (C), which is defined as the amount of charge carried by a current of one ampere in one second (1C = 1A · 1s). * Charge is also commonly expressed in terms of ampere hours (Ah). * * The base unit of `UnitElectricCharge` is defined as coulombs. */ class UnitElectricCharge extends Dimension { const SYMBOL_COULOMBS = "C"; const SYMBOL_MEGAAMPERE_HOURS = "MAh"; const SYMBOL_KILOAMPERE_HOURS = "kAh"; const SYMBOL_AMPERE_HOURS = "Ah"; const SYMBOL_MILLIAMPERE_HOURS = "mAh"; const SYMBOL_MICROAMPERE_HOURS = "µAh"; const COEFFICIENT_COULOMBS = 1.0; const COEFFICIENT_MEGAAMPERE_HOURS = 3.6E+9; const COEFFICIENT_KILOAMPERE_HOURS = 3600000.0; const COEFFICIENT_AMPERE_HOURS = 3600.0; const COEFFICIENT_MILLIAMPERE_HOURS = 3.6; const COEFFICIENT_MICROAMPERE_HOURS = 0.0036; /** * Returns the base electric charge unit, equal to coulombs. * * @return UnitElectricCharge The base electric charge unit. */ public static function baseUnit() { return self::coulombs(); } /** * Returns the coulombs unit of electric charge. * * @return UnitElectricCharge The coulombs unit of electric charge. */ public static function coulombs(): UnitElectricCharge { return new static(static::SYMBOL_COULOMBS, new UnitConverterLinear(static::COEFFICIENT_COULOMBS)); } /** * Returns the megaampere hours unit of electric charge. * * @return UnitElectricCharge The megaampere hours unit of electric charge. */ public static function megaampereHours(): UnitElectricCharge { return new static(static::SYMBOL_MEGAAMPERE_HOURS, new UnitConverterLinear(static::COEFFICIENT_MEGAAMPERE_HOURS)); } /** * Returns the kiloampere hours unit of electric charge. * * @return UnitElectricCharge The kiloampere hours unit of electric charge. */ public static function kiloampereHours(): UnitElectricCharge { return new static(static::SYMBOL_KILOAMPERE_HOURS, new UnitConverterLinear(static::COEFFICIENT_KILOAMPERE_HOURS)); } /** * Returns the ampere hours unit of electric charge. * * @return UnitElectricCharge The ampere hours unit of electric charge. */ public static function ampereHours(): UnitElectricCharge { return new static(static::SYMBOL_AMPERE_HOURS, new UnitConverterLinear(static::COEFFICIENT_AMPERE_HOURS)); } /** * Returns the milliampere hours unit of electric charge. * * @return UnitElectricCharge The milliampere hours unit of electric charge. */ public static function milliampereHours(): UnitElectricCharge { return new static(static::SYMBOL_MILLIAMPERE_HOURS, new UnitConverterLinear(static::COEFFICIENT_MILLIAMPERE_HOURS)); } /** * Returns the microampere hours unit of electric charge. * * @return UnitElectricCharge The microampere hours unit of electric charge. */ public static function microampereHours(): UnitElectricCharge { return new static(static::SYMBOL_MICROAMPERE_HOURS, new UnitConverterLinear(static::COEFFICIENT_MICROAMPERE_HOURS)); } } <file_sep>/doc/Measurements-BaseUnitConvertible.md Measurements\BaseUnitConvertible =============== A unit type that can be converted to a base unit. * Interface name: BaseUnitConvertible * Namespace: Measurements * This is an **interface** Methods ------- ### baseUnit mixed Measurements\BaseUnitConvertible::baseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is **static**. <file_sep>/src/Quantities/Length.php <?php namespace Measurements\Quantities; use Measurements\Unit; use Measurements\Measurement; use Measurements\Units\UnitLength; use Measurements\Exceptions\UnitException; /** * The `Length` class represents specific quantities of length. * * @method static Length megameters(float $value) * @method static Length kilometers(float $value) * @method static Length hectometers(float $value) * @method static Length decameters(float $value) * @method static Length meters(float $value) * @method static Length decimeters(float $value) * @method static Length centimeters(float $value) * @method static Length millimeters(float $value) * @method static Length micrometers(float $value) * @method static Length nanometers(float $value) * @method static Length picometers(float $value) * @method static Length inches(float $value) * @method static Length feet(float $value) * @method static Length yards(float $value) * @method static Length miles(float $value) * @method static Length lightyears(float $value) * @method static Length nauticalMiles(float $value) * @method static Length fathoms(float $value) * @method static Length furlongs(float $value) * @method static Length astronomicalUnits(float $value) * @method static Length parsecs(float $value) */ class Length extends Measurement { /** * Initializes a new length measurement with a specified floating-point value and unit. * * @param double $value The measurement value. * @param Unit $unit The unit of measure. * * @throws \Measurements\Exceptions\UnitException */ public function __construct($value, Unit $unit) { if (!$unit instanceof UnitLength) { throw new UnitException("Attempt to create a length measurement from an invalid unit [$unit]!"); } parent::__construct($value, $unit); } } <file_sep>/src/Units/UnitElectricCurrent.php <?php namespace Measurements\Units; use Measurements\Dimension; use Measurements\Converters\UnitConverterLinear; /** * The `UnitElectricCurrent` class encapsulates units of measure for electric current. * You typically use instances of `UnitElectricCurrent` to represent specific quantities of electric current using the `Measurement` class. * * Electric current is the flow of electric current. The SI unit for electric current is the ampere (A), which is defined in terms the production of electromagnetic force between two parallel linear conductors. * It can also be expressed as the flow of one coulomb per second (1A = 1C / s). * * The base unit of `UnitElectricCurrent` is defined as amperes. */ class UnitElectricCurrent extends Dimension { const SYMBOL_MEGAAMPERES = "MA"; const SYMBOL_KILOAMPERES = "kA"; const SYMBOL_AMPERES = "A"; const SYMBOL_MILLIAMPERES = "mA"; const SYMBOL_MICROAMPERES = "µA"; const COEFFICIENT_MEGAAMPERES = 1E+6; const COEFFICIENT_KILOAMPERES = 1000.0; const COEFFICIENT_AMPERES = 1.0; const COEFFICIENT_MILLIAMPERES = 0.001; const COEFFICIENT_MICROAMPERES = 1E-6; /** * Returns the base electric current current, equal to amperes. * * @return UnitElectricCurrent The base electric current unit. */ public static function baseUnit() { return self::amperes(); } /** * Returns the megaamperes unit of electric current. * * @return UnitElectricCurrent The megaamperes unit of electric current. */ public static function megaamperes(): UnitElectricCurrent { return new static(static::SYMBOL_MEGAAMPERES, new UnitConverterLinear(static::COEFFICIENT_MEGAAMPERES)); } /** * Returns the kiloamperes unit of electric current. * * @return UnitElectricCurrent The kiloamperes unit of electric current. */ public static function kiloamperes(): UnitElectricCurrent { return new static(static::SYMBOL_KILOAMPERES, new UnitConverterLinear(static::COEFFICIENT_KILOAMPERES)); } /** * Returns the amperes unit of electric current. * * @return UnitElectricCurrent The amperes unit of electric current. */ public static function amperes(): UnitElectricCurrent { return new static(static::SYMBOL_AMPERES, new UnitConverterLinear(static::COEFFICIENT_AMPERES)); } /** * Returns the milliamperes unit of electric current. * * @return UnitElectricCurrent The milliamperes unit of electric current. */ public static function milliamperes(): UnitElectricCurrent { return new static(static::SYMBOL_MILLIAMPERES, new UnitConverterLinear(static::COEFFICIENT_MILLIAMPERES)); } /** * Returns the microamperes unit of electric current. * * @return UnitElectricCurrent The microamperes unit of electric current. */ public static function microamperes(): UnitElectricCurrent { return new static(static::SYMBOL_MICROAMPERES, new UnitConverterLinear(static::COEFFICIENT_MICROAMPERES)); } } <file_sep>/doc/Measurements-Units-UnitSpeed.md Measurements\Units\UnitSpeed =============== The `UnitSpeed` class encapsulates units of measure for speed. You typically use instances of `UnitSpeed` to represent specific quantities of speed using the `Measurement` class. Speed is the magnitude of velocity, or the rate of change of position. Speed can be expressed by SI derived units in terms of meters per second (m/s), and is also commonly expressed in terms of kilometers per hour (km/h) and miles per hour (mph). The base unit of `UnitSpeed` is defined as meters per second. * Class name: UnitSpeed * Namespace: Measurements\Units * Parent class: [Measurements\Dimension](Measurements-Dimension.md) Constants ---------- ### SYMBOL_METERS_PER_SECOND const SYMBOL_METERS_PER_SECOND = "m/s" ### SYMBOL_KILOMETERS_PER_HOUR const SYMBOL_KILOMETERS_PER_HOUR = "km/h" ### SYMBOL_MILES_PER_HOUR const SYMBOL_MILES_PER_HOUR = "mph" ### SYMBOL_KNOTS const SYMBOL_KNOTS = "kn" ### COEFFICIENT_METERS_PER_SECOND const COEFFICIENT_METERS_PER_SECOND = 1.0 ### COEFFICIENT_KILOMETERS_PER_HOUR const COEFFICIENT_KILOMETERS_PER_HOUR = 0.277778 ### COEFFICIENT_MILES_PER_HOUR const COEFFICIENT_MILES_PER_HOUR = 0.44704 ### COEFFICIENT_KNOTS const COEFFICIENT_KNOTS = 0.514444 Properties ---------- ### $converter protected \Measurements\UnitConverter $converter The converter used to represent the unit in terms of the dimension's base unit. * Visibility: **protected** ### $symbol protected string $symbol The symbolic representation of the unit. * Visibility: **protected** Methods ------- ### baseUnit mixed Measurements\BaseUnitConvertible::baseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is **static**. * This method is defined by [Measurements\BaseUnitConvertible](Measurements-BaseUnitConvertible.md) ### metersPerSecond \Measurements\Units\UnitSpeed Measurements\Units\UnitSpeed::metersPerSecond() Returns the meters per second unit of speed. * Visibility: **public** * This method is **static**. ### kilometersPerHour \Measurements\Units\UnitSpeed Measurements\Units\UnitSpeed::kilometersPerHour() Returns the kilometers per second unit of speed. * Visibility: **public** * This method is **static**. ### milesPerHour \Measurements\Units\UnitSpeed Measurements\Units\UnitSpeed::milesPerHour() Returns the miles per hours unit of speed. * Visibility: **public** * This method is **static**. ### knots \Measurements\Units\UnitSpeed Measurements\Units\UnitSpeed::knots() Returns the knots unit of speed. * Visibility: **public** * This method is **static**. ### __construct mixed Measurements\Unit::__construct(string $symbol) Initializes a new unit with the specified symbol. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) #### Arguments * $symbol **string** - &lt;p&gt;The symbolic representation of the unit.&lt;/p&gt; ### converter \Measurements\UnitConverter Measurements\Dimension::converter() Returns the unit converter used to represent the unit in terms of the dimension's base unit. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### getBaseUnit mixed Measurements\Dimension::getBaseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### symbol string Measurements\Unit::symbol() Return the symbolic representation of the unit. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) ### isEqualTo boolean Measurements\Equatable::isEqualTo(mixed $other) Returns a boolean value that indicates whether the receiver is equal to another given object. * Visibility: **public** * This method is defined by [Measurements\Equatable](Measurements-Equatable.md) #### Arguments * $other **mixed** - &lt;p&gt;The object with which to compare the receiver.&lt;/p&gt; ### __toString string Measurements\Unit::__toString() Converts the unit to its string representation. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) <file_sep>/src/Units/UnitElectricPotentialDifference.php <?php namespace Measurements\Units; use Measurements\Dimension; use Measurements\Converters\UnitConverterLinear; /** * The `UnitElectricPotentialDifference` class encapsulates units of measure for electric potential difference. * You typically use instances of `UnitElectricPotentialDifference` to represent specific quantities of electric potential difference using the `Measurement` class. * * Electric potential difference is the amount of electric potential energy of a point charge at a point in space. * The SI unit for electric potential difference is the volt (V), which is derived as the difference in electric potential energy between two points of a linear conductor when an electric current of one ampere dissipates one watt of power between those points (1V = 1W/1A). * * The base unit of `UnitElectricPotentialDifference` is defined as volts. */ class UnitElectricPotentialDifference extends Dimension { const SYMBOL_MEGAVOLTS = "MV"; const SYMBOL_KILOVOLTS = "kV"; const SYMBOL_VOLTS = "V"; const SYMBOL_MILLIVOLTS = "mV"; const SYMBOL_MICROVOLTS = "µV"; const COEFFICIENT_MEGAVOLTS = 1E+6; const COEFFICIENT_KILOVOLTS = 1000.0; const COEFFICIENT_VOLTS = 1.0; const COEFFICIENT_MILLIVOLTS = 0.001; const COEFFICIENT_MICROVOLTS = 1E-6; /** * Returns the base unit of electric potential difference, equal to volts. * * @return UnitElectricPotentialDifference The base unit of electric potential differnce. */ public static function baseUnit() { return self::volts(); } /** * Returns the megavolts unit of electric potential difference. * * @return UnitElectricPotentialDifference The megavolts unit of electric potential difference. */ public static function megavolts(): UnitElectricPotentialDifference { return new static(static::SYMBOL_MEGAVOLTS, new UnitConverterLinear(static::COEFFICIENT_MEGAVOLTS)); } /** * Returns the kilovolts unit of electric potential difference. * * @return UnitElectricPotentialDifference The kilovolts unit of electric potential difference. */ public static function kilovolts(): UnitElectricPotentialDifference { return new static(static::SYMBOL_KILOVOLTS, new UnitConverterLinear(static::COEFFICIENT_KILOVOLTS)); } /** * Returns the volts unit of electric potential difference. * * @return UnitElectricPotentialDifference The volts unit of electric potential difference. */ public static function volts(): UnitElectricPotentialDifference { return new static(static::SYMBOL_VOLTS, new UnitConverterLinear(static::COEFFICIENT_VOLTS)); } /** * Returns the millivolts unit of electric potential difference. * * @return UnitElectricPotentialDifference The millivolts unit of electric potential difference. */ public static function millivolts(): UnitElectricPotentialDifference { return new static(static::SYMBOL_MILLIVOLTS, new UnitConverterLinear(static::COEFFICIENT_MILLIVOLTS)); } /** * Returns the microvolts unit of electric potential difference. * * @return UnitElectricPotentialDifference The microvolts unit of electric potential difference. */ public static function microvolts(): UnitElectricPotentialDifference { return new static(static::SYMBOL_MICROVOLTS, new UnitConverterLinear(static::COEFFICIENT_MICROVOLTS)); } } <file_sep>/doc/Measurements-UnitConverter.md Measurements\UnitConverter =============== A `UnitConverter` describes how to convert a unit to and from the base unit of its dimension. Use the `UnitConverter` interface to implement new ways of converting a unit. * Interface name: UnitConverter * Namespace: Measurements * This is an **interface** Methods ------- ### baseUnitValueFromValue mixed Measurements\UnitConverter::baseUnitValueFromValue($value) * Visibility: **public** #### Arguments * $value **mixed** ### valueFromBaseUnitValue mixed Measurements\UnitConverter::valueFromBaseUnitValue($baseUnitValue) * Visibility: **public** #### Arguments * $baseUnitValue **mixed** <file_sep>/tests/Units/UnitConcentrationMassTests.php <?php namespace Tests\Units; use PHPUnit\Framework\TestCase; use Measurements\Measurement; use Measurements\Units\UnitConcentrationMass; class UnitConcentrationMassTests extends TestCase { use InteractsWithUnits; /** @test */ public function it_defines_grams_per_liter_as_base_unit() { $this->assertTrue(UnitConcentrationMass::baseUnit() == UnitConcentrationMass::gramsPerLiter(), "Concentration mass should define grams per liter as its base unit."); } /** @test */ public function it_converts_concentration_masses() { $base = new Measurement(1, UnitConcentrationMass::baseUnit()); $gramsPerMole = 1.0; $this->assertMeasurementEquals($base->convertTo(UnitConcentrationMass::gramsPerLiter()), 1.0, $base, "grams per liter "); $this->assertMeasurementEquals($base->convertTo(UnitConcentrationMass::milligramsPerDeciliter()), 100, $base, "milligrams per deciliter"); $this->assertMeasurementEquals($base->convertTo(UnitConcentrationMass::millimolesPerLiterWithGramsPerMole($gramsPerMole)), 1.0 / (18 * $gramsPerMole), $base, "millimoles per liter"); } }<file_sep>/src/Units/UnitFuelEfficiency.php <?php namespace Measurements\Units; use Measurements\Dimension; use Measurements\Converters\UnitConverterLinear; use Measurements\Converters\UnitConverterReciprocal; /** * The `UnitFuelEfficiency` class encapsulates units of measure for fuel efficiency. * You typically use instances of `UnitFuelEfficiency` to represent specific quantities of fuel efficiency using the `Measurement` class. * * Fuel efficiency corresponds to the thermal efficiency of a process that converts the chemical potential energy of a fuel into kinetic energy. * Fuel efficiency can be expressed by SI derived units in terms of cubic meters per meter (m3/m), but is more commonly expressed in terms of liters per kilometer (L/km) and miles per gallon (mpg). * * The base unit of `UnitFuelEfficiency` is defined as liters per 100 kilometers. */ class UnitFuelEfficiency extends Dimension { const SYMBOL_LITERS_PER_100_KILOMETERS = "L/100km"; const SYMBOL_MILES_PER_GALLON = "mpg"; const SYMBOL_MILES_PER_IMPERIAL_GALLON = "mpg"; const SYMBOL_KILOMETERS_PER_LITER = "km/L"; const COEFFICIENT_LITERS_PER_100_KILOMETERS = 1.0; const COEFFICIENT_MILES_PER_GALLON = 235.215; const COEFFICIENT_MILES_PER_IMPERIAL_GALLON = 282.481; const COEFFICIENT_KILOMETERS_PER_LITER = 0.01; /** * Returns the base unit of fuel efficiency, equal to liters per 100 kilometers. * * @return UnitFuelEfficiency The base unit of fuel efficiency. */ public static function baseUnit() { return self::litersPer100Kilometers(); } /** * Returns the liter per 100 kilometers unit of fuel efficiency. * * @return UnitFuelEfficiency The liter per 100 kilometers unit of fuel efficiency. */ public static function litersPer100Kilometers(): UnitFuelEfficiency { return new static(self::SYMBOL_LITERS_PER_100_KILOMETERS, new UnitConverterReciprocal(self::COEFFICIENT_LITERS_PER_100_KILOMETERS)); } /** * Returns the miles per gallon unit of fuel efficiency. * * @return UnitFuelEfficiency The miles per gallon unit of fuel efficiency. */ public static function milesPerGallon(): UnitFuelEfficiency { return new static(self::SYMBOL_MILES_PER_GALLON, new UnitConverterReciprocal(self::COEFFICIENT_MILES_PER_GALLON)); } /** * Returns the miles per imperial gallon unit of fuel efficiency. * * @return UnitFuelEfficiency The the miles per imperial gallon unit of fuel efficiency. */ public static function milesPerImperialGallon(): UnitFuelEfficiency { return new static(self::SYMBOL_MILES_PER_IMPERIAL_GALLON, new UnitConverterReciprocal(self::COEFFICIENT_MILES_PER_IMPERIAL_GALLON)); } /** * Returns the kilometers per liter unit of fuel efficiency. * * @return UnitFuelEfficiency The kilometers per liter unit of fuel efficiency. */ public static function kilometersPerLiter(): UnitFuelEfficiency { return new static(self::SYMBOL_KILOMETERS_PER_LITER, new UnitConverterLinear(self::COEFFICIENT_KILOMETERS_PER_LITER)); } } <file_sep>/src/Quantities/Power.php <?php namespace Measurements\Quantities; use Measurements\Unit; use Measurements\Measurement; use Measurements\Units\UnitPower; use Measurements\Exceptions\UnitException; /** * The `Power` class represents a specific quantities of power. * * @method static Power terawatts(float $value) * @method static Power gigawatts(float $value) * @method static Power megawatts(float $value) * @method static Power kilowatts(float $value) * @method static Power watts(float $value) * @method static Power milliwatts(float $value) * @method static Power microwatts(float $value) * @method static Power nanowatts(float $value) * @method static Power picowatts(float $value) * @method static Power femtowatts(float $value) * @method static Power horsepower(float $value) */ class Power extends Measurement { /** * Initializes a new power measurement with a specified floating-point value and unit. * * @param double $value The measurement value. * @param Unit $unit The unit of measure. * * @throws \Measurements\Exceptions\UnitException */ public function __construct($value, Unit $unit) { if (!$unit instanceof UnitPower) { throw new UnitException("Attempt to create a power measurement from an invalid unit [$unit]!"); } parent::__construct($value, $unit); } } <file_sep>/src/Dimension.php <?php namespace Measurements; /** * A unit type that can be converted to a base unit. */ interface BaseUnitConvertible { /** * Returns the base unit of the dimension. * * @return mixed */ public static function baseUnit(); } /** * `Dimension` is an abstract subclass of `Unit` that declares a programmatic interface for objects that represent a dimensional unit of measure. */ abstract class Dimension extends Unit implements BaseUnitConvertible { /** * The converter used to represent the unit in terms of the dimension's base unit. * * @var \Measurements\UnitConverter */ protected $converter; /** * Initializes a dimensional unit with the specified symbol and unit converter. * * @param string $symbol The symbolic representation of the unit. * @param UnitConverter $converter A converter used to represent the unit in terms of the dimension's base unit. */ public function __construct($symbol, UnitConverter $converter) { parent::__construct($symbol); $this->converter = $converter; } /** * Returns the unit converter used to represent the unit in terms of the dimension's base unit. * * @return \Measurements\UnitConverter The unit converter used to represent the unit in terms of the dimension's base unit. */ public function converter(): UnitConverter { return $this->converter; } /** * Returns the base unit of the dimension. * * @return mixed The base unit of the dimension. */ public function getBaseUnit() { return static::baseUnit(); } } <file_sep>/doc/Measurements-Units-UnitMass.md Measurements\Units\UnitMass =============== The `UnitMass` class encapsulates units of measure for mass. You typically use instances of `UnitMass` to represent specific quantities of mass using the `Measurement` class. Mass is a fundamental property of matter that causes it to resist being accelerated by a force. The SI unit for mass is the kilogram (kg), which defined in terms of the mass of the international prototype kilogram. The base unit of `UnitMass` is defined as kilograms. * Class name: UnitMass * Namespace: Measurements\Units * Parent class: [Measurements\Dimension](Measurements-Dimension.md) Constants ---------- ### SYMBOL_KILOGRAMS const SYMBOL_KILOGRAMS = "kg" ### SYMBOL_GRAMS const SYMBOL_GRAMS = "g" ### SYMBOL_DECIGRAMS const SYMBOL_DECIGRAMS = "dg" ### SYMBOL_CENTIGRAMS const SYMBOL_CENTIGRAMS = "cg" ### SYMBOL_MILLIGRAMS const SYMBOL_MILLIGRAMS = "mg" ### SYMBOL_MICROGRAMS const SYMBOL_MICROGRAMS = "µg" ### SYMBOL_NANOGRAMS const SYMBOL_NANOGRAMS = "ng" ### SYMBOL_PICOGRAMS const SYMBOL_PICOGRAMS = "pg" ### SYMBOL_OUNCES const SYMBOL_OUNCES = "oz" ### SYMBOL_OUNCES_TROY const SYMBOL_OUNCES_TROY = "oz t" ### SYMBOL_POUNDS const SYMBOL_POUNDS = "lb" ### SYMBOL_STONES const SYMBOL_STONES = "st" ### SYMBOL_METRIC_TONS const SYMBOL_METRIC_TONS = "t" ### SYMBOL_SHORT_TONS const SYMBOL_SHORT_TONS = "ton" ### SYMBOL_CARATS const SYMBOL_CARATS = "ct" ### SYMBOL_SLUGS const SYMBOL_SLUGS = "sg" ### COEFFICIENT_KILOGRAMS const COEFFICIENT_KILOGRAMS = 1.0 ### COEFFICIENT_GRAMS const COEFFICIENT_GRAMS = 0.001 ### COEFFICIENT_DECIGRAMS const COEFFICIENT_DECIGRAMS = 0.0001 ### COEFFICIENT_CENTIGRAMS const COEFFICIENT_CENTIGRAMS = 1.0E-5 ### COEFFICIENT_MILLIGRAMS const COEFFICIENT_MILLIGRAMS = 1.0E-6 ### COEFFICIENT_MICROGRAMS const COEFFICIENT_MICROGRAMS = 1.0E-9 ### COEFFICIENT_NANOGRAMS const COEFFICIENT_NANOGRAMS = 1.0E-12 ### COEFFICIENT_PICOGRAMS const COEFFICIENT_PICOGRAMS = 1.0E-15 ### COEFFICIENT_OUNCES const COEFFICIENT_OUNCES = 0.0283495 ### COEFFICIENT_OUNCES_TROY const COEFFICIENT_OUNCES_TROY = 0.03110348 ### COEFFICIENT_POUNDS const COEFFICIENT_POUNDS = 0.453592 ### COEFFICIENT_STONES const COEFFICIENT_STONES = 0.157473 ### COEFFICIENT_METRIC_TONS const COEFFICIENT_METRIC_TONS = 1000.0 ### COEFFICIENT_SHORT_TONS const COEFFICIENT_SHORT_TONS = 907.1849999999999 ### COEFFICIENT_CARATS const COEFFICIENT_CARATS = 0.0002 ### COEFFICIENT_SLUGS const COEFFICIENT_SLUGS = 14.5939 Properties ---------- ### $converter protected \Measurements\UnitConverter $converter The converter used to represent the unit in terms of the dimension's base unit. * Visibility: **protected** ### $symbol protected string $symbol The symbolic representation of the unit. * Visibility: **protected** Methods ------- ### baseUnit mixed Measurements\BaseUnitConvertible::baseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is **static**. * This method is defined by [Measurements\BaseUnitConvertible](Measurements-BaseUnitConvertible.md) ### kilograms \Measurements\Units\UnitMass Measurements\Units\UnitMass::kilograms() Returns the kilograms unit of mass. * Visibility: **public** * This method is **static**. ### grams \Measurements\Units\UnitMass Measurements\Units\UnitMass::grams() Returns the grams unit of mass. * Visibility: **public** * This method is **static**. ### decigrams \Measurements\Units\UnitMass Measurements\Units\UnitMass::decigrams() Returns the decigrams unit of mass. * Visibility: **public** * This method is **static**. ### centigrams \Measurements\Units\UnitMass Measurements\Units\UnitMass::centigrams() Returns the centigrams unit of mass. * Visibility: **public** * This method is **static**. ### milligrams \Measurements\Units\UnitMass Measurements\Units\UnitMass::milligrams() Returns the milligrams unit of mass. * Visibility: **public** * This method is **static**. ### micrograms \Measurements\Units\UnitMass Measurements\Units\UnitMass::micrograms() Returns the micrograms unit of mass. * Visibility: **public** * This method is **static**. ### nanograms \Measurements\Units\UnitMass Measurements\Units\UnitMass::nanograms() Returns the nanograms unit of mass. * Visibility: **public** * This method is **static**. ### picograms \Measurements\Units\UnitMass Measurements\Units\UnitMass::picograms() Returns the picograms unit of mass. * Visibility: **public** * This method is **static**. ### ounces \Measurements\Units\UnitMass Measurements\Units\UnitMass::ounces() Returns the ounces unit of mass. * Visibility: **public** * This method is **static**. ### ouncesTroy \Measurements\Units\UnitMass Measurements\Units\UnitMass::ouncesTroy() Returns the ounces Troy unit of mass. * Visibility: **public** * This method is **static**. ### pounds \Measurements\Units\UnitMass Measurements\Units\UnitMass::pounds() Returns the pounds unit of mass. * Visibility: **public** * This method is **static**. ### stones \Measurements\Units\UnitMass Measurements\Units\UnitMass::stones() Returns the stones unit of mass. * Visibility: **public** * This method is **static**. ### metricTons \Measurements\Units\UnitMass Measurements\Units\UnitMass::metricTons() Returns the metricTons unit of mass. * Visibility: **public** * This method is **static**. ### shortTons \Measurements\Units\UnitMass Measurements\Units\UnitMass::shortTons() Returns the short tons unit of mass. * Visibility: **public** * This method is **static**. ### carats \Measurements\Units\UnitMass Measurements\Units\UnitMass::carats() Returns the carats unit of mass. * Visibility: **public** * This method is **static**. ### slugs \Measurements\Units\UnitMass Measurements\Units\UnitMass::slugs() Returns the slugs unit of mass. * Visibility: **public** * This method is **static**. ### __construct mixed Measurements\Unit::__construct(string $symbol) Initializes a new unit with the specified symbol. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) #### Arguments * $symbol **string** - &lt;p&gt;The symbolic representation of the unit.&lt;/p&gt; ### converter \Measurements\UnitConverter Measurements\Dimension::converter() Returns the unit converter used to represent the unit in terms of the dimension's base unit. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### getBaseUnit mixed Measurements\Dimension::getBaseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### symbol string Measurements\Unit::symbol() Return the symbolic representation of the unit. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) ### isEqualTo boolean Measurements\Equatable::isEqualTo(mixed $other) Returns a boolean value that indicates whether the receiver is equal to another given object. * Visibility: **public** * This method is defined by [Measurements\Equatable](Measurements-Equatable.md) #### Arguments * $other **mixed** - &lt;p&gt;The object with which to compare the receiver.&lt;/p&gt; ### __toString string Measurements\Unit::__toString() Converts the unit to its string representation. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) <file_sep>/src/Units/UnitPower.php <?php namespace Measurements\Units; use Measurements\Dimension; use Measurements\Converters\UnitConverterLinear; /** * The `UnitPower` class encapsulates units of measure for power. * You typically use instances of `UnitPower` to represent specific quantities of power using the `Measurement` class. * * Power is the amount of energy used over time. The SI unit for power is the watt (W), which is derived as one joule per second (1W = 1J / 1s). * * The base unit of `UnitPower` is defined as watts. */ class UnitPower extends Dimension { const SYMBOL_TERAWATTS = "TW"; const SYMBOL_GIGAWATTS = "GW"; const SYMBOL_MEGAWATTS = "MW"; const SYMBOL_KILOWATTS = "kW"; const SYMBOL_WATTS = "W"; const SYMBOL_MILLIWATTS = "mW"; const SYMBOL_MICROWATTS = "µW"; const SYMBOL_NANOWATTS = "nW"; const SYMBOL_PICOWATTS = "pW"; const SYMBOL_FEMTOWATTS = "fW"; const SYMBOL_HORSE_POWER = "hp"; const COEFFICIENT_TERAWATTS = 1E+12; const COEFFICIENT_GIGAWATTS = 1E+9; const COEFFICIENT_MEGAWATTS = 1E+6; const COEFFICIENT_KILOWATTS = 1000.0; const COEFFICIENT_WATTS = 1.0; const COEFFICIENT_MILLIWATTS = 0.001; const COEFFICIENT_MICROWATTS = 1E-6; const COEFFICIENT_NANOWATTS = 1E-9; const COEFFICIENT_PICOWATTS = 1E-12; const COEFFICIENT_FEMTOWATTS = 1E-15; const COEFFICIENT_HORSE_POWER = 745.7; /** * Returns the base unit of power, equal to watts. * * @return UnitPower The base unit of power. */ public static function baseUnit() { return self::watts(); } /** * Returns the terawatts unit of power. * * @return UnitPower The terawatts unit of power. */ public static function terawatts(): UnitPower { return new static(static::SYMBOL_TERAWATTS, new UnitConverterLinear(static::COEFFICIENT_TERAWATTS)); } /** * Returns the gigawatts unit of power. * * @return UnitPower The gigawatts unit of power. */ public static function gigawatts(): UnitPower { return new static(static::SYMBOL_GIGAWATTS, new UnitConverterLinear(static::COEFFICIENT_GIGAWATTS)); } /** * Returns the megawatts unit of power. * * @return UnitPower The megawatts unit of power. */ public static function megawatts(): UnitPower { return new static(static::SYMBOL_MEGAWATTS, new UnitConverterLinear(static::COEFFICIENT_MEGAWATTS)); } /** * Returns the kilowatts unit of power. * * @return UnitPower The kilowatts unit of power. */ public static function kilowatts(): UnitPower { return new static(static::SYMBOL_KILOWATTS, new UnitConverterLinear(static::COEFFICIENT_KILOWATTS)); } /** * Returns the watts unit of power. * * @return UnitPower The watts unit of power. */ public static function watts(): UnitPower { return new static(static::SYMBOL_WATTS, new UnitConverterLinear(static::COEFFICIENT_WATTS)); } /** * Returns the milliwatts unit of power. * * @return UnitPower The milliwatts unit of power. */ public static function milliwatts(): UnitPower { return new static(static::SYMBOL_MILLIWATTS, new UnitConverterLinear(static::COEFFICIENT_MILLIWATTS)); } /** * Returns the microwatts unit of power. * * @return UnitPower The microwatts unit of power. */ public static function microwatts(): UnitPower { return new static(static::SYMBOL_MICROWATTS, new UnitConverterLinear(static::COEFFICIENT_MICROWATTS)); } /** * Returns the nanowatts unit of power. * * @return UnitPower The nanowatts unit of power. */ public static function nanowatts(): UnitPower { return new static(static::SYMBOL_NANOWATTS, new UnitConverterLinear(static::COEFFICIENT_NANOWATTS)); } /** * Returns the picowatts unit of power. * * @return UnitPower The picowatts unit of power. */ public static function picowatts(): UnitPower { return new static(static::SYMBOL_PICOWATTS, new UnitConverterLinear(static::COEFFICIENT_PICOWATTS)); } /** * Returns the femtowatts unit of power. * * @return UnitPower The femtowatts unit of power. */ public static function femtowatts(): UnitPower { return new static(static::SYMBOL_FEMTOWATTS, new UnitConverterLinear(static::COEFFICIENT_FEMTOWATTS)); } /** * Returns the horsepower unit of power. * * @return UnitPower The horsepower unit of power. */ public static function horsepower(): UnitPower { return new static(static::SYMBOL_HORSE_POWER, new UnitConverterLinear(static::COEFFICIENT_HORSE_POWER)); } } <file_sep>/doc/Measurements-Exceptions-UnitException.md Measurements\Exceptions\UnitException =============== * Class name: UnitException * Namespace: Measurements\Exceptions * Parent class: Exception <file_sep>/tests/ConversionTests.php <?php namespace Tests; use PHPUnit\Framework\TestCase; use Measurements\Measurement; use Measurements\Units\UnitLength; use Measurements\Units\UnitDuration; use Measurements\Quantities\Length; use Measurements\Converters\UnitConverterLinear; class ConversionTests extends TestCase { /** @test */ public function it_checks_converter_linearity() { $coefficient = 7.0; $baseUnitConverter = new UnitConverterLinear($coefficient); $this->assertEquals($baseUnitConverter->valueFromBaseUnitValue($coefficient), 1.0, "Linear conversion from base unit is not linear."); $this->assertEquals($baseUnitConverter->baseUnitValueFromValue(1), $coefficient, "Linear conversion to base unit is not linear."); } /** @test */ public function it_checks_whether_a_measurement_can_be_converted_to_a_different_unit() { $meters = new Measurement(42, UnitLength::meters()); $this->assertTrue($meters->canBeConvertedToUnit(UnitLength::centimeters()), "Meters should be convertible in centimeters."); $this->assertFalse($meters->canBeConvertedToUnit(UnitDuration::hours()), "Meters should not be convertible in hours (non length unit)."); } /** @test */ public function it_converts_a_measurement_to_a_different_unit() { $meters = new Measurement(42, UnitLength::meters()); $centimeters = $meters->convertTo(UnitLength::centimeters()); $this->assertEquals($centimeters->value(), 100 * $meters->value(), "{$meters} converted to centimeters should be equal to 4200 cm instead of {$centimeters}."); } /** @test */ public function it_converts_a_measurement_to_a_different_unit_using_short_syntax() { $meters = new Length(42, UnitLength::meters()); $centimeters = $meters->convertTo(UnitLength::centimeters()); $this->assertEquals($meters->toCentimeters(), $centimeters, "A measurement should be converted using the short syntax."); } /** @test */ public function short_syntax_conversion_is_available_on_measurement_subclasses_only() { $meters = new Measurement(42, UnitLength::meters()); $this->expectException(\BadMethodCallException::class); $invalid = $meters->toCentimeters(); } }<file_sep>/tests/Units/UnitAngleTests.php <?php namespace Tests\Units; use PHPUnit\Framework\TestCase; use Measurements\Measurement; use Measurements\Units\UnitAngle; class UnitAngleTests extends TestCase { use InteractsWithUnits; /** @test */ public function it_defines_degrees_as_base_unit() { $this->assertTrue(UnitAngle::baseUnit() == UnitAngle::degrees(), "Angle should define degrees as its base unit."); } /** @test */ public function it_converts_angles() { $base = new Measurement(1, UnitAngle::baseUnit()); $this->assertMeasurementEquals($base->convertTo(UnitAngle::degrees()), 1.0, $base, "degrees"); $this->assertMeasurementEquals($base->convertTo(UnitAngle::arcMinutes()), 1.0 / 0.016667, $base, "arc minutes"); $this->assertMeasurementEquals($base->convertTo(UnitAngle::arcSeconds()), 1.0 / 0.00027778, $base, "arc seconds"); $this->assertMeasurementEquals($base->convertTo(UnitAngle::radians()), 1.0 / 57.2958, $base, "radians"); $this->assertMeasurementEquals($base->convertTo(UnitAngle::gradians()), 1.0 / 0.9, $base, "gradians"); $this->assertMeasurementEquals($base->convertTo(UnitAngle::revolutions()), 1.0 / 6.28319, $base, "revolutions"); } }<file_sep>/src/Quantities/Acceleration.php <?php namespace Measurements\Quantities; use Measurements\Unit; use Measurements\Measurement; use Measurements\Units\UnitLength; use Measurements\Units\UnitDuration; use Measurements\Units\UnitAcceleration; use Measurements\Exceptions\UnitException; /** * The `Acceleration` class represents a specific quantities of acceleration. * * @method static Acceleration metersPerSecondSquared(float $value) * @method static Acceleration gravity(float $value) */ class Acceleration extends Measurement { /** * Initializes a new acceleration with a specified floating-point value and unit. * * @param double $value The measurement value. * @param Unit $unit The unit of measure. * * @throws \Measurements\Exceptions\UnitException */ public function __construct($value, Unit $unit) { if (!$unit instanceof UnitAcceleration) { throw new UnitException("Attempt to create an acceleration measurement from an invalid unit [$unit]!"); } parent::__construct($value, $unit); } /** * Returns an acceleration measurement computed from the specified length and duration. * * @param Length $length A length. * @param Duration $duration A duration. * * @return \Measurements\Quantities\Acceleration The acceleration that corresponds to the given length and duration. */ public static function fromLengthAndDuration(Length $length, Duration $duration) { $meters = $length->convertTo(UnitLength::meters()); $seconds = $duration->convertTo(UnitDuration::seconds()); $acceleration = $meters->value() / ($seconds->value() * $seconds->value()); return new static($acceleration, UnitAcceleration::metersPerSecondSquared()); } } <file_sep>/src/Units/UnitMass.php <?php namespace Measurements\Units; use Measurements\Dimension; use Measurements\Converters\UnitConverterLinear; /** * The `UnitMass` class encapsulates units of measure for mass. * You typically use instances of `UnitMass` to represent specific quantities of mass using the `Measurement` class. * * Mass is a fundamental property of matter that causes it to resist being accelerated by a force. * The SI unit for mass is the kilogram (kg), which defined in terms of the mass of the international prototype kilogram. * * The base unit of `UnitMass` is defined as kilograms. */ class UnitMass extends Dimension { const SYMBOL_KILOGRAMS = "kg"; const SYMBOL_GRAMS = "g"; const SYMBOL_DECIGRAMS = "dg"; const SYMBOL_CENTIGRAMS = "cg"; const SYMBOL_MILLIGRAMS = "mg"; const SYMBOL_MICROGRAMS = "µg"; const SYMBOL_NANOGRAMS = "ng"; const SYMBOL_PICOGRAMS = "pg"; const SYMBOL_OUNCES = "oz"; const SYMBOL_OUNCES_TROY = "oz t"; const SYMBOL_POUNDS = "lb"; const SYMBOL_STONES = "st"; const SYMBOL_METRIC_TONS = "t"; const SYMBOL_SHORT_TONS = "ton"; const SYMBOL_CARATS = "ct"; const SYMBOL_SLUGS = "sg"; const COEFFICIENT_KILOGRAMS = 1.0; const COEFFICIENT_GRAMS = 0.001; const COEFFICIENT_DECIGRAMS = 1E-4; const COEFFICIENT_CENTIGRAMS = 1E-5; const COEFFICIENT_MILLIGRAMS = 1E-6; const COEFFICIENT_MICROGRAMS = 1E-9; const COEFFICIENT_NANOGRAMS = 1E-12; const COEFFICIENT_PICOGRAMS = 1E-15; const COEFFICIENT_OUNCES = 0.0283495; const COEFFICIENT_OUNCES_TROY = 0.03110348; const COEFFICIENT_POUNDS = 0.453592; const COEFFICIENT_STONES = 0.157473; const COEFFICIENT_METRIC_TONS = 1000.0; const COEFFICIENT_SHORT_TONS = 907.185; const COEFFICIENT_CARATS = 0.0002; const COEFFICIENT_SLUGS = 14.5939; /** * Returns the base unit of mass, equal to kilograms. * * @return UnitMass The the base unit of mass. */ public static function baseUnit() { return self::kilograms(); } /** * Returns the kilograms unit of mass. * * @return UnitMass The kilograms unit of mass. */ public static function kilograms(): UnitMass { return new static(static::SYMBOL_KILOGRAMS, new UnitConverterLinear(static::COEFFICIENT_KILOGRAMS)); } /** * Returns the grams unit of mass. * * @return UnitMass The grams unit of mass. */ public static function grams(): UnitMass { return new static(static::SYMBOL_GRAMS, new UnitConverterLinear(static::COEFFICIENT_GRAMS)); } /** * Returns the decigrams unit of mass. * * @return UnitMass The decigrams unit of mass. */ public static function decigrams(): UnitMass { return new static(static::SYMBOL_DECIGRAMS, new UnitConverterLinear(static::COEFFICIENT_DECIGRAMS)); } /** * Returns the centigrams unit of mass. * * @return UnitMass The centigrams unit of mass. */ public static function centigrams(): UnitMass { return new static(static::SYMBOL_CENTIGRAMS, new UnitConverterLinear(static::COEFFICIENT_CENTIGRAMS)); } /** * Returns the milligrams unit of mass. * * @return UnitMass The milligrams unit of mass. */ public static function milligrams(): UnitMass { return new static(static::SYMBOL_MILLIGRAMS, new UnitConverterLinear(static::COEFFICIENT_MILLIGRAMS)); } /** * Returns the micrograms unit of mass. * * @return UnitMass The micrograms unit of mass. */ public static function micrograms(): UnitMass { return new static(static::SYMBOL_MICROGRAMS, new UnitConverterLinear(static::COEFFICIENT_MICROGRAMS)); } /** * Returns the nanograms unit of mass. * * @return UnitMass The nanograms unit of mass. */ public static function nanograms(): UnitMass { return new static(static::SYMBOL_NANOGRAMS, new UnitConverterLinear(static::COEFFICIENT_NANOGRAMS)); } /** * Returns the picograms unit of mass. * * @return UnitMass The picograms unit of mass. */ public static function picograms(): UnitMass { return new static(static::SYMBOL_PICOGRAMS, new UnitConverterLinear(static::COEFFICIENT_PICOGRAMS)); } /** * Returns the ounces unit of mass. * * @return UnitMass The ounces unit of mass. */ public static function ounces(): UnitMass { return new static(static::SYMBOL_OUNCES, new UnitConverterLinear(static::COEFFICIENT_OUNCES)); } /** * Returns the ounces Troy unit of mass. * * @return UnitMass The ounces Troy unit of mass. */ public static function ouncesTroy(): UnitMass { return new static(static::SYMBOL_OUNCES_TROY, new UnitConverterLinear(static::COEFFICIENT_OUNCES_TROY)); } /** * Returns the pounds unit of mass. * * @return UnitMass The pounds unit of mass. */ public static function pounds(): UnitMass { return new static(static::SYMBOL_POUNDS, new UnitConverterLinear(static::COEFFICIENT_POUNDS)); } /** * Returns the stones unit of mass. * * @return UnitMass The stones unit of mass. */ public static function stones(): UnitMass { return new static(static::SYMBOL_STONES, new UnitConverterLinear(static::COEFFICIENT_STONES)); } /** * Returns the metricTons unit of mass. * * @return UnitMass The metricTons unit of mass. */ public static function metricTons(): UnitMass { return new static(static::SYMBOL_METRIC_TONS, new UnitConverterLinear(static::COEFFICIENT_METRIC_TONS)); } /** * Returns the short tons unit of mass. * * @return UnitMass The short tons unit of mass. */ public static function shortTons(): UnitMass { return new static(static::SYMBOL_SHORT_TONS, new UnitConverterLinear(static::COEFFICIENT_SHORT_TONS)); } /** * Returns the carats unit of mass. * * @return UnitMass The carats unit of mass. */ public static function carats(): UnitMass { return new static(static::SYMBOL_CARATS, new UnitConverterLinear(static::COEFFICIENT_CARATS)); } /** * Returns the slugs unit of mass. * * @return UnitMass The slugs unit of mass. */ public static function slugs(): UnitMass { return new static(static::SYMBOL_SLUGS, new UnitConverterLinear(static::COEFFICIENT_SLUGS)); } } <file_sep>/doc/Measurements-Exceptions-MeasurementValueException.md Measurements\Exceptions\MeasurementValueException =============== * Class name: MeasurementValueException * Namespace: Measurements\Exceptions * Parent class: Exception <file_sep>/tests/Units/UnitRadioactivityTests.php <?php namespace Tests\Units; use PHPUnit\Framework\TestCase; use Measurements\Measurement; use Measurements\Units\UnitRadioactivity; class UnitRadioactivityTests extends TestCase { use InteractsWithUnits; /** @test */ public function it_defines_becquerel_as_base_unit() { $this->assertTrue(UnitRadioactivity::baseUnit() == UnitRadioactivity::becquerel(), "Radioactivity should define becquerel as its base unit."); } /** @test */ public function it_converts_radioactivities() { $base = new Measurement(1, UnitRadioactivity::baseUnit()); $this->assertMeasurementEquals($base->convertTo(UnitRadioactivity::becquerel()), 1.0, $base, "becquerel"); $this->assertMeasurementEquals($base->convertTo(UnitRadioactivity::curie()), 1.0 / 3.7E+10, $base, "curie"); } }<file_sep>/doc/Measurements-Units-UnitPressure.md Measurements\Units\UnitPressure =============== The `UnitPressure` class encapsulates units of measure for pressure. You typically use instances of `UnitPressure` to represent specific quantities of pressure using the `Measurement` class. Pressure is the normal force over a surface. The SI unit for pressure is the pascal (Pa), which is derived as one newton of force over one square meter (1Pa = 1N / 1m2). The base unit of `UnitPressure` is defined as newtons per meter squared (equivalent to Pascals). * Class name: UnitPressure * Namespace: Measurements\Units * Parent class: [Measurements\Dimension](Measurements-Dimension.md) Constants ---------- ### SYMBOL_NEWTONS_PER_METERS_SQUARED const SYMBOL_NEWTONS_PER_METERS_SQUARED = "N/m²" ### SYMBOL_GIGAPASCALS const SYMBOL_GIGAPASCALS = "GPa" ### SYMBOL_MEGAPASCALS const SYMBOL_MEGAPASCALS = "MPa" ### SYMBOL_KILOPASCALS const SYMBOL_KILOPASCALS = "kPa" ### SYMBOL_HECTOPASCALS const SYMBOL_HECTOPASCALS = "hPa" ### SYMBOL_PASCALS const SYMBOL_PASCALS = "Pa" ### SYMBOL_INCHES_OF_MERCURY const SYMBOL_INCHES_OF_MERCURY = "inHg" ### SYMBOL_BARS const SYMBOL_BARS = "bar" ### SYMBOL_MILLIBARS const SYMBOL_MILLIBARS = "mbar" ### SYMBOL_MILLIMETERS_OF_MERCURY const SYMBOL_MILLIMETERS_OF_MERCURY = "mmHg" ### SYMBOL_POUNDS_PER_SQUARE_INCH const SYMBOL_POUNDS_PER_SQUARE_INCH = "psi" ### COEFFICIENT_NEWTONS_PER_METERS_SQUARED const COEFFICIENT_NEWTONS_PER_METERS_SQUARED = 1.0 ### COEFFICIENT_GIGAPASCALS const COEFFICIENT_GIGAPASCALS = 1000000000.0 ### COEFFICIENT_MEGAPASCALS const COEFFICIENT_MEGAPASCALS = 1000000.0 ### COEFFICIENT_KILOPASCALS const COEFFICIENT_KILOPASCALS = 1000.0 ### COEFFICIENT_HECTOPASCALS const COEFFICIENT_HECTOPASCALS = 100.0 ### COEFFICIENT_PASCALS const COEFFICIENT_PASCALS = 1.0 ### COEFFICIENT_INCHES_OF_MERCURY const COEFFICIENT_INCHES_OF_MERCURY = 3386.39 ### COEFFICIENT_BARS const COEFFICIENT_BARS = 100000.0 ### COEFFICIENT_MILLIBARS const COEFFICIENT_MILLIBARS = 100.0 ### COEFFICIENT_MILLIMETERS_OF_MERCURY const COEFFICIENT_MILLIMETERS_OF_MERCURY = 133.322 ### COEFFICIENT_POUNDS_PER_SQUARE_INCH const COEFFICIENT_POUNDS_PER_SQUARE_INCH = 6894.76 Properties ---------- ### $converter protected \Measurements\UnitConverter $converter The converter used to represent the unit in terms of the dimension's base unit. * Visibility: **protected** ### $symbol protected string $symbol The symbolic representation of the unit. * Visibility: **protected** Methods ------- ### baseUnit mixed Measurements\BaseUnitConvertible::baseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is **static**. * This method is defined by [Measurements\BaseUnitConvertible](Measurements-BaseUnitConvertible.md) ### newtonsPerMeterSquared \Measurements\Units\UnitPressure Measurements\Units\UnitPressure::newtonsPerMeterSquared() Returns the newtons per meter square unit of pressure (equivalent to Pascals). * Visibility: **public** * This method is **static**. ### gigapascals \Measurements\Units\UnitPressure Measurements\Units\UnitPressure::gigapascals() Returns the pascals unit of pressure (equivalent to newtons per meter square). * Visibility: **public** * This method is **static**. ### megapascals \Measurements\Units\UnitPressure Measurements\Units\UnitPressure::megapascals() Returns the megapascals unit of pressure (equivalent to newtons per meter square). * Visibility: **public** * This method is **static**. ### kilopascals \Measurements\Units\UnitPressure Measurements\Units\UnitPressure::kilopascals() Returns the kilopascals unit of pressure. * Visibility: **public** * This method is **static**. ### hectopascals \Measurements\Units\UnitPressure Measurements\Units\UnitPressure::hectopascals() Returns the hectopascals unit of pressure. * Visibility: **public** * This method is **static**. ### pascals \Measurements\Units\UnitPressure Measurements\Units\UnitPressure::pascals() Returns the Pascals unit of pressure (equivalent to newtons per meter square). * Visibility: **public** * This method is **static**. ### inchesOfMercury \Measurements\Units\UnitPressure Measurements\Units\UnitPressure::inchesOfMercury() Returns the inches of mercury unit of pressure. * Visibility: **public** * This method is **static**. ### bars \Measurements\Units\UnitPressure Measurements\Units\UnitPressure::bars() Returns the bars unit of pressure. * Visibility: **public** * This method is **static**. ### millibars \Measurements\Units\UnitPressure Measurements\Units\UnitPressure::millibars() Returns the millibars unit of pressure. * Visibility: **public** * This method is **static**. ### millimetersOfMercury \Measurements\Units\UnitPressure Measurements\Units\UnitPressure::millimetersOfMercury() Returns the millimeters of mercury unit of pressure. * Visibility: **public** * This method is **static**. ### poundsPerSquareInch \Measurements\Units\UnitPressure Measurements\Units\UnitPressure::poundsPerSquareInch() Returns the pounds per square inch unit of pressure. * Visibility: **public** * This method is **static**. ### __construct mixed Measurements\Unit::__construct(string $symbol) Initializes a new unit with the specified symbol. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) #### Arguments * $symbol **string** - &lt;p&gt;The symbolic representation of the unit.&lt;/p&gt; ### converter \Measurements\UnitConverter Measurements\Dimension::converter() Returns the unit converter used to represent the unit in terms of the dimension's base unit. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### getBaseUnit mixed Measurements\Dimension::getBaseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### symbol string Measurements\Unit::symbol() Return the symbolic representation of the unit. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) ### isEqualTo boolean Measurements\Equatable::isEqualTo(mixed $other) Returns a boolean value that indicates whether the receiver is equal to another given object. * Visibility: **public** * This method is defined by [Measurements\Equatable](Measurements-Equatable.md) #### Arguments * $other **mixed** - &lt;p&gt;The object with which to compare the receiver.&lt;/p&gt; ### __toString string Measurements\Unit::__toString() Converts the unit to its string representation. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) <file_sep>/src/Measurement.php <?php namespace Measurements; use BadMethodCallException; use InvalidArgumentException; use Measurements\Exceptions\UnitException; use Measurements\Exceptions\MeasurementValueException; /** * A `Measurement` object represents a quantity and unit of measure. * The `Measurement` class provides a programmatic interface to converting measurements into different units, as well as calculating the sum or difference between two measurements. */ class Measurement implements Comparable { /** * The value component of the measurement. * * @var double */ protected $value; /** * The unit component of the measurement. * * @var \Measurements\Unit */ protected $unit; /** * Initializes a new measurement with a specified floating-point value and unit. * * @param double $value The measurement value. * @param Unit $unit The unit of measure. * * @throws \Measurements\Exceptions\MeasurementValueException */ public function __construct($value, Unit $unit) { if (!is_numeric($value)) { throw new MeasurementValueException("Measurement value <{$value}> must be numeric."); } $this->value = (double)$value; $this->unit = $unit; } /** * Returns the unit of measure. * * @return \Measurements\Unit The unit of measure. */ public function unit(): Unit { return $this->unit; } /** * Returns the measurement value, represented as a floating-point number. * * @return double The measurement value. */ public function value() { return $this->value; } /** * Returns a string that represents the contents of the measurement. * * @return string A string that represents the contents of the measurement. */ public function toString() { return "{$this->value()} {$this->unit()}"; } /** * Converts the measurement to its string representation. * * @return string A string that represents the measurement. */ public function __toString() { return $this->toString(); } /** * Returns a boolean value that indicates whether the measurement is equal to another given object. * * @param mixed $other The object with which to compare the measurement. * * @return bool `true` if both objects are equal, otherwise `false`. */ public function isEqualTo($other) { if (! $other instanceof Measurement) { return false; } if ($other->unit()->isEqualTo($this->unit)) { return $this->value() == $other->value(); } $rhsInLhs = $other->convertTo($this->unit()); return $this->value() == $rhsInLhs->value(); } /** * Returns a boolean value that indicates whether the measurement is greater than another given object. * * @param mixed $object The object with which to compare the measurement. * * @return bool `true` if the ` is greater than object, otherwise `false`. */ public function isGreaterThan($object) { return $this->compareTo($object, function($lhs, $rhs) { return $lhs > $rhs; }); } /** * Returns a boolean value that indicates whether the measurement is greater than or equal to another given object. * * @param mixed $object The object with which to compare the measurement. * * @return bool `true` if the measurement is greater than or equal to object, otherwise `false`. */ public function isGreaterThanOrEqualTo($object) { return $this->compareTo($object, function($lhs, $rhs) { return $lhs >= $rhs; }); } /** * RReturns a boolean value that indicates whether the measurement is less than another given object. * * @param mixed $object The object with which to compare the measurement. * * @return bool `true` if the measurement is less than object, otherwise `false`. */ public function isLessThan($object) { return $this->compareTo($object, function($lhs, $rhs) { return $lhs < $rhs; }); } /** * Returns a boolean value that indicates whether the measurement is less than or equal to another given object. * * @param mixed $object The object with which to compare the measurement. * * @return bool `true` if the measurement is less than or equal to object, otherwise `false`. */ public function isLessThanOrEqualTo($object) { return $this->compareTo($object, function($lhs,$rhs) { return $lhs >= $rhs; }); } /** * Compares the measurement to another given object. * * @param mixed $object The object with which to compare the measurement. * @param callable $comparison The closure used to compare objects. * * @return mixed The result of the comparison between the measurement and the given object. * * @throws \Measurements\Exceptions\UnitException */ public function compareTo($object, callable $comparison) { if (! $object instanceof Measurement) { return $comparison($this, $object); } if ($this->unit()->isEqualTo($object->unit())) { return $comparison($this->value(), $object->value()); } if (! $this->canBeConvertedToUnit($object->unit())) { throw new UnitException("Attempt to compare measurements with non-equal units!"); } $rhsInLhs = $object->convertTo($this->unit()); return $comparison($this->value(), $rhsInLhs->value()); } /** * Returns a measurement created by converting the measurement to the specified unit. * * @param Dimension $otherUnit The unit to convert the measurement. * * @return Measurement A new measurement object with a value calculated by converting into the new unit. * * @throws \Measurements\Exceptions\UnitException */ public function convertTo(Dimension $otherUnit): Measurement { if (!($this->unit instanceof Dimension)) { throw new UnitException("Measurement unit must be of Dimension type to be converted!"); } if ($otherUnit->isEqualTo($this->unit)) { return new static($this->value, $otherUnit); } $baseUnit = get_class($this->unit)::baseUnit(); $valueInTermsOfBase = $this->unit->converter()->baseUnitValueFromValue($this->value); if ($otherUnit->isEqualTo($baseUnit)) { return new Measurement($valueInTermsOfBase, $otherUnit); } $otherValueFromTermsOfBase = $otherUnit->converter()->valueFromBaseUnitValue($valueInTermsOfBase); return new Measurement($otherValueFromTermsOfBase, $otherUnit); } /** * Returns a boolean that indicates whether the measurement can be converted to the specified unit. * * @param Dimension $unit The unit to convert the measurement. * * @return bool `true` if the measurement can be converted to the specified unit, otherwise `false`. */ public function canBeConvertedToUnit(Dimension $unit) { if (!($this->unit instanceof Dimension)) { return false; } return $this->unit->getBaseUnit()->isEqualTo($unit->getBaseUnit()); } /** * Returns a new measurement by adding the receiver to the specified measurement. * * @param Measurement $measurement The measurement to be added. * * @return Measurement A new measurement with a value equal to the receiver's value plus the value of the specified measurement converted into the unit of the receiver. * * @throws \Measurements\Exceptions\UnitException */ public function add(Measurement $measurement): Measurement { if ($measurement->unit()->isEqualTo($this->unit)) { return $this->addValue($measurement->value()); } if ($measurement->unit() instanceOf Dimension) { $lhsValueInTermsOfBase = $this->unit()->converter()->baseUnitValueFromValue($this->value()); $rhsValueInTermsOfBase = $measurement->unit()->converter()->baseUnitValueFromValue($measurement->value()); return new Measurement($lhsValueInTermsOfBase + $rhsValueInTermsOfBase, $this->unit->getBaseUnit()); } throw new UnitException("Attempt to add measurements with non-equal units!"); } /** * Returns a new measurement by adding the given value to the measurement. * * @param double $value The value to be added. * * @return Measurement A new measurement with a value equal to the receiver's value plus the specified value. */ public function addValue($value): Measurement { return new Measurement($this->value() + $value, $this->unit()); } /** * Returns a new measurement by subtracting the specified measurement from the receiver. * * @param Measurement $measurement The measurement to be subtracted. * * @return Measurement A new measurement with a value equal to the receiver's value minus the value of the specified measurement converted into the unit of the receiver. * * @throws \Measurements\Exceptions\UnitException */ public function subtract(Measurement $measurement): Measurement { if ($measurement->unit()->isEqualTo($this->unit)) { return $this->subtractValue($measurement->value()); } if ($measurement->unit() instanceOf Dimension) { $lhsValueInTermsOfBase = $this->unit()->converter()->baseUnitValueFromValue($this->value()); $rhsValueInTermsOfBase = $measurement->unit()->converter()->baseUnitValueFromValue($measurement->value()); return new Measurement($lhsValueInTermsOfBase - $rhsValueInTermsOfBase, $this->unit->getBaseUnit()); } throw new UnitException("Attempt to subtract measurements with non-equal units!"); } /** * Returns a new measurement by subtracting the given value from the measurement. * * @param double $value The value to be subtracted. * * @return Measurement A new measurement with a value equal to the receiver's value minus the specified value. */ public function subtractValue($value): Measurement { return new Measurement($this->value() - $value, $this->unit()); } /** * Returns a new measurement by multiplying the receiver by the specified measurement. * * @param Measurement $measurement The measurement to be multiplied by. * * @return Measurement A new measurement with a value equal to the receiver's value multiplied by the value of the specified measurement converted into the unit of the receiver. * * @throws \Measurements\Exceptions\UnitException */ public function multiplyBy(Measurement $measurement): Measurement { if ($measurement->unit()->isEqualTo($this->unit)) { return $this->multiplyByValue($measurement->value()); } if ($measurement->unit() instanceOf Dimension) { $lhsValueInTermsOfBase = $this->unit()->converter()->baseUnitValueFromValue($this->value()); $rhsValueInTermsOfBase = $measurement->unit()->converter()->baseUnitValueFromValue($measurement->value()); return new Measurement($lhsValueInTermsOfBase * $rhsValueInTermsOfBase, $this->unit->getBaseUnit()); } throw new UnitException("Attempt to multiply measurements with non-equal units!"); } /** * Returns a new measurement by multiplying the measurement by the given value. * * @param double $value The value to be multiplied by. * * @return Measurement A new measurement with a value equal to the receiver's value multiplied by the specified value. */ public function multiplyByValue($value): Measurement { return new Measurement($this->value() * $value, $this->unit()); } /** * Returns a new measurement by dividing the receiver by the specified measurement. * * @param Measurement $measurement The measurement to divide by. * * @return Measurement A new measurement with a value equal to the receiver's value divided by the value of the specified measurement converted into the unit of the receiver. * * @throws \Measurements\Exceptions\UnitException */ public function divideBy(Measurement $measurement): Measurement { if ($measurement->unit()->isEqualTo($this->unit)) { return $this->divideByValue($measurement->value()); } if ($measurement->unit() instanceOf Dimension) { $lhsValueInTermsOfBase = $this->unit()->converter()->baseUnitValueFromValue($this->value()); $rhsValueInTermsOfBase = $measurement->unit()->converter()->baseUnitValueFromValue($measurement->value()); return new Measurement($lhsValueInTermsOfBase / $rhsValueInTermsOfBase, $this->unit->getBaseUnit()); } throw new UnitException("Attempt to divide measurements with non-equal units!"); } /** * Returns a new measurement by dividing the measurement by the given value. * * @param $value double The value to divide by. * * @return Measurement A new measurement with a value equal to the receiver's value divided by the specified value. */ public function divideByValue($value): Measurement { return new Measurement($this->value() / $value, $this->unit()); } /** * Handle dynamic calls to the object. * * @param string $method * @param array $parameters * * @return mixed * * @throws \BadMethodCallException */ public function __call($method, $parameters) { // Provide a shortcut to convert a measurement to a specific unit: // $meters = Length::meters($x); // $centimeters = $meters->toCentimeters(); // instead of // $meters = new Length($x, UnitLength::meters()); // $centimeters = $meters->convertTo(UnitLength::centimeters()); if (substr($method, 0, 2) == 'to') { $class = static::resolveUnitClass(); $method = lcfirst(substr($method, 2)); if (method_exists($class, $method) && is_callable([ $class, $method ])) { return $this->convertTo(call_user_func([ $class, $method ])); } if (!is_subclass_of($this, Measurement::class)) { throw new BadMethodCallException("The caller must be a subclass of ".Measurement::class." to allow the short syntax conversion to {$method}."); } throw new BadMethodCallException("Cannot convert ".static::class." to {$method}."); } } /** * Handle dynamic, static calls to the object. * * @param string $method * @param array $parameters * * @return mixed * * @throws \InvalidArgumentException * @throws \BadMethodCallException */ public static function __callStatic($method, $parameters) { // Provide a shortcut to create a measurement with a specific unit: // $length = Length::meters($x); // instead of // $length = new Length($x, UnitLength::meters()); $class = static::resolveUnitClass(); if (method_exists($class, $method) && is_callable([ $class, $method ])) { if (count($parameters) == 0) { throw new InvalidArgumentException("Missing value argument for creating a measurement."); } return new static($parameters[0], call_user_func([ $class, $method ])); } throw new BadMethodCallException("Invalid method {$method}() called on {$class} class."); } /** * Resolve the specific Unit class that corresponds to the current Measurement type. * * @return string The Unit class that corresponds to the current quantity. */ protected static function resolveUnitClass() { return '\Measurements\Units\Unit'.basename(str_replace('\\', '/', static::class)); } } <file_sep>/doc/Measurements-Units-UnitConcentrationMass.md Measurements\Units\UnitConcentrationMass =============== The `UnitConcentrationMass` class encapsulates units of measure for concentration of mass. You typically use instances of `UnitConcentrationMass` to represent specific quantities of concentration using the `Measurement` class. Concentration is the abundance of a constituent within a volume. Concentration can be expressed by SI derived units in terms of kilograms per cubic meter (kg/m3). The base unit of `UnitConcentrationMass` is defined as grams per liter. * Class name: UnitConcentrationMass * Namespace: Measurements\Units * Parent class: [Measurements\Dimension](Measurements-Dimension.md) Constants ---------- ### SYMBOL_GRAMS_PER_LITER const SYMBOL_GRAMS_PER_LITER = "g/L" ### SYMBOL_MILLIGRAMS_PER_DECILITER const SYMBOL_MILLIGRAMS_PER_DECILITER = "mg/dL" ### SYMBOL_MILLIMOLES_PER_LITER const SYMBOL_MILLIMOLES_PER_LITER = "mmol/L" ### COEFFICIENT_GRAMS_PER_LITER const COEFFICIENT_GRAMS_PER_LITER = 1.0 ### COEFFICIENT_MILLIGRAMS_PER_DECILITER const COEFFICIENT_MILLIGRAMS_PER_DECILITER = 0.01 ### COEFFICIENT_MILLIMOLES_PER_LITER const COEFFICIENT_MILLIMOLES_PER_LITER = 18.0 Properties ---------- ### $converter protected \Measurements\UnitConverter $converter The converter used to represent the unit in terms of the dimension's base unit. * Visibility: **protected** ### $symbol protected string $symbol The symbolic representation of the unit. * Visibility: **protected** Methods ------- ### baseUnit mixed Measurements\BaseUnitConvertible::baseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is **static**. * This method is defined by [Measurements\BaseUnitConvertible](Measurements-BaseUnitConvertible.md) ### gramsPerLiter \Measurements\Units\UnitConcentrationMass Measurements\Units\UnitConcentrationMass::gramsPerLiter() Returns grams per liter unit of concentration. * Visibility: **public** * This method is **static**. ### milligramsPerDeciliter \Measurements\Units\UnitConcentrationMass Measurements\Units\UnitConcentrationMass::milligramsPerDeciliter() Returns milligrams per deciliter unit of concentration. * Visibility: **public** * This method is **static**. ### millimolesPerLiterWithGramsPerMole \Measurements\Units\UnitConcentrationMass Measurements\Units\UnitConcentrationMass::millimolesPerLiterWithGramsPerMole(double $gramsPerMole) Returns the millimoles per liter unit with the specified number of grams per mole. * Visibility: **public** * This method is **static**. #### Arguments * $gramsPerMole **double** - &lt;p&gt;The mass, in grams, for a mole of a given constituent.&lt;/p&gt; ### __construct mixed Measurements\Unit::__construct(string $symbol) Initializes a new unit with the specified symbol. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) #### Arguments * $symbol **string** - &lt;p&gt;The symbolic representation of the unit.&lt;/p&gt; ### converter \Measurements\UnitConverter Measurements\Dimension::converter() Returns the unit converter used to represent the unit in terms of the dimension's base unit. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### getBaseUnit mixed Measurements\Dimension::getBaseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### symbol string Measurements\Unit::symbol() Return the symbolic representation of the unit. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) ### isEqualTo boolean Measurements\Equatable::isEqualTo(mixed $other) Returns a boolean value that indicates whether the receiver is equal to another given object. * Visibility: **public** * This method is defined by [Measurements\Equatable](Measurements-Equatable.md) #### Arguments * $other **mixed** - &lt;p&gt;The object with which to compare the receiver.&lt;/p&gt; ### __toString string Measurements\Unit::__toString() Converts the unit to its string representation. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) <file_sep>/doc/Measurements-Quantities-Volume.md Measurements\Quantities\Volume =============== The `Volume` class represents a specific quantities of volume. * Class name: Volume * Namespace: Measurements\Quantities * Parent class: Measurements\Measurement Methods ------- ### __construct mixed Measurements\Quantities\Volume::__construct(double $value, \Measurements\Unit $unit) Initializes a new volume measurement with a specified floating-point value and unit. * Visibility: **public** #### Arguments * $value **double** - &lt;p&gt;The measurement value.&lt;/p&gt; * $unit **[Measurements\Unit](Measurements-Unit.md)** - &lt;p&gt;The unit of measure.&lt;/p&gt; ### fromEquivalentLengths \Measurements\Quantities\Volume Measurements\Quantities\Volume::fromEquivalentLengths(\Measurements\Quantities\Length $length) Returns a volume measurement computed from a specified length. * Visibility: **public** * This method is **static**. #### Arguments * $length **[Measurements\Quantities\Length](Measurements-Quantities-Length.md)** - &lt;p&gt;A length.&lt;/p&gt; ### fromLengths \Measurements\Quantities\Volume Measurements\Quantities\Volume::fromLengths(\Measurements\Quantities\Length $length, \Measurements\Quantities\Length $width, \Measurements\Quantities\Length $height) Returns a volume measurement computed from the specified length, width and height. * Visibility: **public** * This method is **static**. #### Arguments * $length **[Measurements\Quantities\Length](Measurements-Quantities-Length.md)** - &lt;p&gt;A length.&lt;/p&gt; * $width **[Measurements\Quantities\Length](Measurements-Quantities-Length.md)** - &lt;p&gt;A width.&lt;/p&gt; * $height **[Measurements\Quantities\Length](Measurements-Quantities-Length.md)** - &lt;p&gt;A height.&lt;/p&gt; <file_sep>/doc/Measurements-Converters-UnitConverterReciprocal.md Measurements\Converters\UnitConverterReciprocal =============== `UnitConverterReciprocal` is a `UnitConverter` subclass for converting between units using a reciprocal function. * Class name: UnitConverterReciprocal * Namespace: Measurements\Converters * This class implements: [Measurements\UnitConverter](Measurements-UnitConverter.md) Properties ---------- ### $reciprocal protected double $reciprocal The reciprocal value used in the unit conversion calculation. * Visibility: **protected** Methods ------- ### __construct mixed Measurements\Converters\UnitConverterReciprocal::__construct(double $reciprocal) Initializes the unit converter with the specified reciprocal value. * Visibility: **public** #### Arguments * $reciprocal **double** - &lt;p&gt;The reciprocal value used in the unit conversion calculation.&lt;/p&gt; ### baseUnitValueFromValue mixed Measurements\UnitConverter::baseUnitValueFromValue($value) * Visibility: **public** * This method is defined by [Measurements\UnitConverter](Measurements-UnitConverter.md) #### Arguments * $value **mixed** ### valueFromBaseUnitValue mixed Measurements\UnitConverter::valueFromBaseUnitValue($baseUnitValue) * Visibility: **public** * This method is defined by [Measurements\UnitConverter](Measurements-UnitConverter.md) #### Arguments * $baseUnitValue **mixed** <file_sep>/src/Units/UnitConcentrationMass.php <?php namespace Measurements\Units; use Measurements\Dimension; use Measurements\Converters\UnitConverterLinear; /** * The `UnitConcentrationMass` class encapsulates units of measure for concentration of mass. * You typically use instances of `UnitConcentrationMass` to represent specific quantities of concentration using the `Measurement` class. * * Concentration is the abundance of a constituent within a volume. * Concentration can be expressed by SI derived units in terms of kilograms per cubic meter (kg/m3). * * The base unit of `UnitConcentrationMass` is defined as grams per liter. */ class UnitConcentrationMass extends Dimension { const SYMBOL_GRAMS_PER_LITER = "g/L"; const SYMBOL_MILLIGRAMS_PER_DECILITER = "mg/dL"; const SYMBOL_MILLIMOLES_PER_LITER = "mmol/L"; const COEFFICIENT_GRAMS_PER_LITER = 1.0; const COEFFICIENT_MILLIGRAMS_PER_DECILITER = 0.01; const COEFFICIENT_MILLIMOLES_PER_LITER = 18.0; /** * Returns the base unit of concentration of mass, equal to grams per liter. * * @return UnitConcentrationMass The base unit of concentration of mass. */ public static function baseUnit() { return self::gramsPerLiter(); } /** * Returns grams per liter unit of concentration. * * @return UnitConcentrationMass The grams per liter unit of concentration. */ public static function gramsPerLiter(): UnitConcentrationMass { return new static(static::SYMBOL_GRAMS_PER_LITER, new UnitConverterLinear(static::COEFFICIENT_GRAMS_PER_LITER)); } /** * Returns milligrams per deciliter unit of concentration. * * @return UnitConcentrationMass The milligrams per deciliter unit of concentration. */ public static function milligramsPerDeciliter(): UnitConcentrationMass { return new static(static::SYMBOL_MILLIGRAMS_PER_DECILITER, new UnitConverterLinear(static::COEFFICIENT_MILLIGRAMS_PER_DECILITER)); } /** * Returns the millimoles per liter unit with the specified number of grams per mole. * * @param double $gramsPerMole The mass, in grams, for a mole of a given constituent. * * @return UnitConcentrationMass A unit expressing millimoles per liter with the specified molar mass. */ public static function millimolesPerLiterWithGramsPerMole($gramsPerMole): UnitConcentrationMass { return new static(static::SYMBOL_MILLIMOLES_PER_LITER, new UnitConverterLinear(static::COEFFICIENT_MILLIMOLES_PER_LITER * $gramsPerMole)); } } <file_sep>/doc/Measurements-Units-UnitElectricPotentialDifference.md Measurements\Units\UnitElectricPotentialDifference =============== The `UnitElectricPotentialDifference` class encapsulates units of measure for electric potential difference. You typically use instances of `UnitElectricPotentialDifference` to represent specific quantities of electric potential difference using the `Measurement` class. Electric potential difference is the amount of electric potential energy of a point charge at a point in space. The SI unit for electric potential difference is the volt (V), which is derived as the difference in electric potential energy between two points of a linear conductor when an electric current of one ampere dissipates one watt of power between those points (1V = 1W/1A). The base unit of `UnitElectricPotentialDifference` is defined as volts. * Class name: UnitElectricPotentialDifference * Namespace: Measurements\Units * Parent class: [Measurements\Dimension](Measurements-Dimension.md) Constants ---------- ### SYMBOL_MEGAVOLTS const SYMBOL_MEGAVOLTS = "MV" ### SYMBOL_KILOVOLTS const SYMBOL_KILOVOLTS = "kV" ### SYMBOL_VOLTS const SYMBOL_VOLTS = "V" ### SYMBOL_MILLIVOLTS const SYMBOL_MILLIVOLTS = "mV" ### SYMBOL_MICROVOLTS const SYMBOL_MICROVOLTS = "µV" ### COEFFICIENT_MEGAVOLTS const COEFFICIENT_MEGAVOLTS = 1000000.0 ### COEFFICIENT_KILOVOLTS const COEFFICIENT_KILOVOLTS = 1000.0 ### COEFFICIENT_VOLTS const COEFFICIENT_VOLTS = 1.0 ### COEFFICIENT_MILLIVOLTS const COEFFICIENT_MILLIVOLTS = 0.001 ### COEFFICIENT_MICROVOLTS const COEFFICIENT_MICROVOLTS = 1.0E-6 Properties ---------- ### $converter protected \Measurements\UnitConverter $converter The converter used to represent the unit in terms of the dimension's base unit. * Visibility: **protected** ### $symbol protected string $symbol The symbolic representation of the unit. * Visibility: **protected** Methods ------- ### baseUnit mixed Measurements\BaseUnitConvertible::baseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is **static**. * This method is defined by [Measurements\BaseUnitConvertible](Measurements-BaseUnitConvertible.md) ### megavolts \Measurements\Units\UnitElectricPotentialDifference Measurements\Units\UnitElectricPotentialDifference::megavolts() Returns the megavolts unit of electric potential difference. * Visibility: **public** * This method is **static**. ### kilovolts \Measurements\Units\UnitElectricPotentialDifference Measurements\Units\UnitElectricPotentialDifference::kilovolts() Returns the kilovolts unit of electric potential difference. * Visibility: **public** * This method is **static**. ### volts \Measurements\Units\UnitElectricPotentialDifference Measurements\Units\UnitElectricPotentialDifference::volts() Returns the volts unit of electric potential difference. * Visibility: **public** * This method is **static**. ### millivolts \Measurements\Units\UnitElectricPotentialDifference Measurements\Units\UnitElectricPotentialDifference::millivolts() Returns the millivolts unit of electric potential difference. * Visibility: **public** * This method is **static**. ### microvolts \Measurements\Units\UnitElectricPotentialDifference Measurements\Units\UnitElectricPotentialDifference::microvolts() Returns the microvolts unit of electric potential difference. * Visibility: **public** * This method is **static**. ### __construct mixed Measurements\Unit::__construct(string $symbol) Initializes a new unit with the specified symbol. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) #### Arguments * $symbol **string** - &lt;p&gt;The symbolic representation of the unit.&lt;/p&gt; ### converter \Measurements\UnitConverter Measurements\Dimension::converter() Returns the unit converter used to represent the unit in terms of the dimension's base unit. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### getBaseUnit mixed Measurements\Dimension::getBaseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### symbol string Measurements\Unit::symbol() Return the symbolic representation of the unit. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) ### isEqualTo boolean Measurements\Equatable::isEqualTo(mixed $other) Returns a boolean value that indicates whether the receiver is equal to another given object. * Visibility: **public** * This method is defined by [Measurements\Equatable](Measurements-Equatable.md) #### Arguments * $other **mixed** - &lt;p&gt;The object with which to compare the receiver.&lt;/p&gt; ### __toString string Measurements\Unit::__toString() Converts the unit to its string representation. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) <file_sep>/src/Units/UnitFrequency.php <?php namespace Measurements\Units; use Measurements\Dimension; use Measurements\Converters\UnitConverterLinear; /** * The `UnitFrequency` class encapsulates units of measure for frequency. * You typically use instances of `UnitFrequency` to represent specific quantities of frequency using the `Measurement` class. * * Frequency is a quantity of occurrences for a repeating event over time. * The SI unit for frequency is the hertz (Hz), which is a derived as one occurrence per second (1Hz = 1 / 1s). * * The base unit of `UnitFrequency` is defined as hertz. */ class UnitFrequency extends Dimension { const SYMBOL_TERAHERTZ = "THz"; const SYMBOL_GIGAHERTZ = "GHz"; const SYMBOL_MEGAHERTZ = "MHz"; const SYMBOL_KILOHERTZ = "kHz"; const SYMBOL_HERTZ = "Hz"; const SYMBOL_MILLIHERTZ = "mHz"; const SYMBOL_MICROHERTZ = "µHz"; const SYMBOL_NANOHERTZ = "nHz"; const COEFFICIENT_TERAHERTZ = 1E+12; const COEFFICIENT_GIGAHERTZ = 1E+9; const COEFFICIENT_MEGAHERTZ = 1E+6; const COEFFICIENT_KILOHERTZ = 1000.0; const COEFFICIENT_HERTZ = 1.0; const COEFFICIENT_MILLIHERTZ = 0.001; const COEFFICIENT_MICROHERTZ = 1E-6; const COEFFICIENT_NANOHERTZ = 1E-9; /** * Returns the base unit of frequency, equal to hertz. * * @return UnitFrequency The base unit of frequency. */ public static function baseUnit() { return self::hertz(); } /** * Returns the terahertz unit of frequency. * * @return UnitFrequency The terahertz unit of frequency. */ public static function terahertz(): UnitFrequency { return new static(static::SYMBOL_TERAHERTZ, new UnitConverterLinear(static::COEFFICIENT_TERAHERTZ)); } /** * Returns the gigahertz unit of frequency. * * @return UnitFrequency The gigahertz unit of frequency. */ public static function gigahertz(): UnitFrequency { return new static(static::SYMBOL_GIGAHERTZ, new UnitConverterLinear(static::COEFFICIENT_GIGAHERTZ)); } /** * Returns the megahertz unit of frequency. * * @return UnitFrequency The megahertz unit of frequency. */ public static function megahertz(): UnitFrequency { return new static(static::SYMBOL_MEGAHERTZ, new UnitConverterLinear(static::COEFFICIENT_MEGAHERTZ)); } /** * Returns the kilohertz unit of frequency. * * @return UnitFrequency The kilohertz unit of frequency. */ public static function kilohertz(): UnitFrequency { return new static(static::SYMBOL_KILOHERTZ, new UnitConverterLinear(static::COEFFICIENT_KILOHERTZ)); } /** * Returns the hertz unit of frequency. * * @return UnitFrequency The hertz unit of frequency. */ public static function hertz(): UnitFrequency { return new static(static::SYMBOL_HERTZ, new UnitConverterLinear(static::COEFFICIENT_HERTZ)); } /** * Returns the millihertz unit of frequency. * * @return UnitFrequency The millihertz unit of frequency. */ public static function millihertz(): UnitFrequency { return new static(static::SYMBOL_MILLIHERTZ, new UnitConverterLinear(static::COEFFICIENT_MILLIHERTZ)); } /** * Returns the microhertz unit of frequency. * * @return UnitFrequency The microhertz unit of frequency. */ public static function microhertz(): UnitFrequency { return new static(static::SYMBOL_MICROHERTZ, new UnitConverterLinear(static::COEFFICIENT_MICROHERTZ)); } /** * Returns the nanohertz unit of frequency. * * @return UnitFrequency The hertz unit of frequency. */ public static function nanohertz(): UnitFrequency { return new static(static::SYMBOL_NANOHERTZ, new UnitConverterLinear(static::COEFFICIENT_NANOHERTZ)); } } <file_sep>/tests/Units/UnitElectricResistanceTests.php <?php namespace Tests\Units; use PHPUnit\Framework\TestCase; use Measurements\Measurement; use Measurements\Units\UnitElectricResistance; class UnitElectricResistanceTests extends TestCase { use InteractsWithUnits; /** @test */ public function it_defines_ohms_as_base_unit() { $this->assertTrue(UnitElectricResistance::baseUnit() == UnitElectricResistance::ohms(), "Electric resistance should define ohms as its base unit."); } /** @test */ public function it_converts_electric_resistances() { $base = new Measurement(1, UnitElectricResistance::baseUnit()); $this->assertMeasurementEquals($base->convertTo(UnitElectricResistance::megaohms()), 1.0 / 1E+6, $base, "megaohms"); $this->assertMeasurementEquals($base->convertTo(UnitElectricResistance::kiloohms()), 0.001, $base, "kiloohms"); $this->assertMeasurementEquals($base->convertTo(UnitElectricResistance::ohms()), 1.0, $base, "ohms"); $this->assertMeasurementEquals($base->convertTo(UnitElectricResistance::milliohms()), 1000, $base, "milliamperes"); $this->assertMeasurementEquals($base->convertTo(UnitElectricResistance::microohms()), 1E+6, $base, "microohms"); } }<file_sep>/doc/Measurements-Quantities-Acceleration.md Measurements\Quantities\Acceleration =============== The `Acceleration` class represents a specific quantities of acceleration. * Class name: Acceleration * Namespace: Measurements\Quantities * Parent class: Measurements\Measurement Methods ------- ### __construct mixed Measurements\Quantities\Acceleration::__construct(double $value, \Measurements\Unit $unit) Initializes a new acceleration with a specified floating-point value and unit. * Visibility: **public** #### Arguments * $value **double** - &lt;p&gt;The measurement value.&lt;/p&gt; * $unit **[Measurements\Unit](Measurements-Unit.md)** - &lt;p&gt;The unit of measure.&lt;/p&gt; ### fromLengthAndDuration \Measurements\Quantities\Acceleration Measurements\Quantities\Acceleration::fromLengthAndDuration(\Measurements\Quantities\Length $length, \Measurements\Quantities\Duration $duration) Returns an acceleration measurement computed from the specified length and duration. * Visibility: **public** * This method is **static**. #### Arguments * $length **[Measurements\Quantities\Length](Measurements-Quantities-Length.md)** - &lt;p&gt;A length.&lt;/p&gt; * $duration **[Measurements\Quantities\Duration](Measurements-Quantities-Duration.md)** - &lt;p&gt;A duration.&lt;/p&gt; <file_sep>/doc/Measurements-Unit.md Measurements\Unit =============== `Unit` is an abstract class that declares a programmatic interface for objects that represent a unit of measure. * Class name: Unit * Namespace: Measurements * This is an **abstract** class * This class implements: [Measurements\Equatable](Measurements-Equatable.md) Properties ---------- ### $symbol protected string $symbol The symbolic representation of the unit. * Visibility: **protected** Methods ------- ### __construct mixed Measurements\Unit::__construct(string $symbol) Initializes a new unit with the specified symbol. * Visibility: **public** #### Arguments * $symbol **string** - &lt;p&gt;The symbolic representation of the unit.&lt;/p&gt; ### symbol string Measurements\Unit::symbol() Return the symbolic representation of the unit. * Visibility: **public** ### isEqualTo boolean Measurements\Equatable::isEqualTo(mixed $other) Returns a boolean value that indicates whether the receiver is equal to another given object. * Visibility: **public** * This method is defined by [Measurements\Equatable](Measurements-Equatable.md) #### Arguments * $other **mixed** - &lt;p&gt;The object with which to compare the receiver.&lt;/p&gt; ### __toString string Measurements\Unit::__toString() Converts the unit to its string representation. * Visibility: **public** <file_sep>/src/Quantities/Mass.php <?php namespace Measurements\Quantities; use Measurements\Unit; use Measurements\Measurement; use Measurements\Units\UnitMass; use Measurements\Exceptions\UnitException; /** * The `Mass` class represents a specific quantities of mass. * * @method static Mass kilograms(float $value) * @method static Mass grams(float $value) * @method static Mass decigrams(float $value) * @method static Mass centigrams(float $value) * @method static Mass milligrams(float $value) * @method static Mass micrograms(float $value) * @method static Mass nanograms(float $value) * @method static Mass picograms(float $value) * @method static Mass ounces(float $value) * @method static Mass ouncesTroy(float $value) * @method static Mass pounds(float $value) * @method static Mass stones(float $value) * @method static Mass metricTons(float $value) * @method static Mass shortTons(float $value) * @method static Mass carats(float $value) * @method static Mass slugs(float $value) */ class Mass extends Measurement { /** * Initializes a new mass measurement with a specified floating-point value and unit. * * @param double $value The measurement value. * @param Unit $unit The unit of measure. * * @throws \Measurements\Exceptions\UnitException */ public function __construct($value, Unit $unit) { if (!$unit instanceof UnitMass) { throw new UnitException("Attempt to create a mass measurement from an invalid unit [$unit]!"); } parent::__construct($value, $unit); } } <file_sep>/doc/Measurements-Units-UnitFrequency.md Measurements\Units\UnitFrequency =============== The `UnitFrequency` class encapsulates units of measure for frequency. You typically use instances of `UnitFrequency` to represent specific quantities of frequency using the `Measurement` class. Frequency is a quantity of occurrences for a repeating event over time. The SI unit for frequency is the hertz (Hz), which is a derived as one occurrence per second (1Hz = 1 / 1s). The base unit of `UnitFrequency` is defined as hertz. * Class name: UnitFrequency * Namespace: Measurements\Units * Parent class: [Measurements\Dimension](Measurements-Dimension.md) Constants ---------- ### SYMBOL_TERAHERTZ const SYMBOL_TERAHERTZ = "THz" ### SYMBOL_GIGAHERTZ const SYMBOL_GIGAHERTZ = "GHz" ### SYMBOL_MEGAHERTZ const SYMBOL_MEGAHERTZ = "MHz" ### SYMBOL_KILOHERTZ const SYMBOL_KILOHERTZ = "kHz" ### SYMBOL_HERTZ const SYMBOL_HERTZ = "Hz" ### SYMBOL_MILLIHERTZ const SYMBOL_MILLIHERTZ = "mHz" ### SYMBOL_MICROHERTZ const SYMBOL_MICROHERTZ = "µHz" ### SYMBOL_NANOHERTZ const SYMBOL_NANOHERTZ = "nHz" ### COEFFICIENT_TERAHERTZ const COEFFICIENT_TERAHERTZ = 1000000000000.0 ### COEFFICIENT_GIGAHERTZ const COEFFICIENT_GIGAHERTZ = 1000000000.0 ### COEFFICIENT_MEGAHERTZ const COEFFICIENT_MEGAHERTZ = 1000000.0 ### COEFFICIENT_KILOHERTZ const COEFFICIENT_KILOHERTZ = 1000.0 ### COEFFICIENT_HERTZ const COEFFICIENT_HERTZ = 1.0 ### COEFFICIENT_MILLIHERTZ const COEFFICIENT_MILLIHERTZ = 0.001 ### COEFFICIENT_MICROHERTZ const COEFFICIENT_MICROHERTZ = 1.0E-6 ### COEFFICIENT_NANOHERTZ const COEFFICIENT_NANOHERTZ = 1.0E-9 Properties ---------- ### $converter protected \Measurements\UnitConverter $converter The converter used to represent the unit in terms of the dimension's base unit. * Visibility: **protected** ### $symbol protected string $symbol The symbolic representation of the unit. * Visibility: **protected** Methods ------- ### baseUnit mixed Measurements\BaseUnitConvertible::baseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is **static**. * This method is defined by [Measurements\BaseUnitConvertible](Measurements-BaseUnitConvertible.md) ### terahertz \Measurements\Units\UnitFrequency Measurements\Units\UnitFrequency::terahertz() Returns the terahertz unit of frequency. * Visibility: **public** * This method is **static**. ### gigahertz \Measurements\Units\UnitFrequency Measurements\Units\UnitFrequency::gigahertz() Returns the gigahertz unit of frequency. * Visibility: **public** * This method is **static**. ### megahertz \Measurements\Units\UnitFrequency Measurements\Units\UnitFrequency::megahertz() Returns the megahertz unit of frequency. * Visibility: **public** * This method is **static**. ### kilohertz \Measurements\Units\UnitFrequency Measurements\Units\UnitFrequency::kilohertz() Returns the kilohertz unit of frequency. * Visibility: **public** * This method is **static**. ### hertz \Measurements\Units\UnitFrequency Measurements\Units\UnitFrequency::hertz() Returns the hertz unit of frequency. * Visibility: **public** * This method is **static**. ### millihertz \Measurements\Units\UnitFrequency Measurements\Units\UnitFrequency::millihertz() Returns the millihertz unit of frequency. * Visibility: **public** * This method is **static**. ### microhertz \Measurements\Units\UnitFrequency Measurements\Units\UnitFrequency::microhertz() Returns the microhertz unit of frequency. * Visibility: **public** * This method is **static**. ### nanohertz \Measurements\Units\UnitFrequency Measurements\Units\UnitFrequency::nanohertz() Returns the nanohertz unit of frequency. * Visibility: **public** * This method is **static**. ### __construct mixed Measurements\Unit::__construct(string $symbol) Initializes a new unit with the specified symbol. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) #### Arguments * $symbol **string** - &lt;p&gt;The symbolic representation of the unit.&lt;/p&gt; ### converter \Measurements\UnitConverter Measurements\Dimension::converter() Returns the unit converter used to represent the unit in terms of the dimension's base unit. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### getBaseUnit mixed Measurements\Dimension::getBaseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### symbol string Measurements\Unit::symbol() Return the symbolic representation of the unit. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) ### isEqualTo boolean Measurements\Equatable::isEqualTo(mixed $other) Returns a boolean value that indicates whether the receiver is equal to another given object. * Visibility: **public** * This method is defined by [Measurements\Equatable](Measurements-Equatable.md) #### Arguments * $other **mixed** - &lt;p&gt;The object with which to compare the receiver.&lt;/p&gt; ### __toString string Measurements\Unit::__toString() Converts the unit to its string representation. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) <file_sep>/doc/Measurements-Units-UnitEnergy.md Measurements\Units\UnitEnergy =============== The `UnitEnergy` class encapsulates units of measure for energy. You typically use instances of `UnitEnergy` to represent specific quantities of energy using the `Measurement` class. Energy is a fundamental property of matter than can be transferred and converted into different forms, such as kinetic, electric, and thermal. The SI unit for energy is the joule (J), which is derived as the work of one meter of displacement in the direction of a force of one newton (1J = 1N ∙ 1m). It can also be derived as the work required to displace an electric charge of one coulomb through an electrical potential difference of one volt (1J = 1C ∙ 1V), or the work required to produce one watt of power for one second (1J = 1W ∙ 1s). Energy is also commonly expressed in terms of the calorie (cal), or the energy needed to raise the temperature of one gram of water by one degree Celsius at a pressure of one atmosphere (1cal ≡ 4.184J). The base unit of `UnitEnergy` is defined as joules. * Class name: UnitEnergy * Namespace: Measurements\Units * Parent class: [Measurements\Dimension](Measurements-Dimension.md) Constants ---------- ### SYMBOL_KILOJOULES const SYMBOL_KILOJOULES = "KJ" ### SYMBOL_JOULES const SYMBOL_JOULES = "J" ### SYMBOL_KILOCALORIES const SYMBOL_KILOCALORIES = "kCal" ### SYMBOL_CALORIES const SYMBOL_CALORIES = "cal" ### SYMBOL_KILOWATT_HOURS const SYMBOL_KILOWATT_HOURS = "kWh" ### COEFFICIENT_KILOJOULES const COEFFICIENT_KILOJOULES = 1000.0 ### COEFFICIENT_JOULES const COEFFICIENT_JOULES = 1.0 ### COEFFICIENT_KILOCALORIES const COEFFICIENT_KILOCALORIES = 4184.0 ### COEFFICIENT_CALORIES const COEFFICIENT_CALORIES = 4.184 ### COEFFICIENT_KILOWATT_HOURS const COEFFICIENT_KILOWATT_HOURS = 3600000.0 Properties ---------- ### $converter protected \Measurements\UnitConverter $converter The converter used to represent the unit in terms of the dimension's base unit. * Visibility: **protected** ### $symbol protected string $symbol The symbolic representation of the unit. * Visibility: **protected** Methods ------- ### baseUnit mixed Measurements\BaseUnitConvertible::baseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is **static**. * This method is defined by [Measurements\BaseUnitConvertible](Measurements-BaseUnitConvertible.md) ### kilojoules \Measurements\Units\UnitEnergy Measurements\Units\UnitEnergy::kilojoules() Returns the kilojoules unit of energy. * Visibility: **public** * This method is **static**. ### joules \Measurements\Units\UnitEnergy Measurements\Units\UnitEnergy::joules() Returns the joules unit of energy. * Visibility: **public** * This method is **static**. ### kilocalories \Measurements\Units\UnitEnergy Measurements\Units\UnitEnergy::kilocalories() Returns the kilocalories unit of energy. * Visibility: **public** * This method is **static**. ### calories \Measurements\Units\UnitEnergy Measurements\Units\UnitEnergy::calories() Returns the calories unit of energy. * Visibility: **public** * This method is **static**. ### kilowattHours \Measurements\Units\UnitEnergy Measurements\Units\UnitEnergy::kilowattHours() Returns the kilowatt hours unit of energy. * Visibility: **public** * This method is **static**. ### __construct mixed Measurements\Unit::__construct(string $symbol) Initializes a new unit with the specified symbol. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) #### Arguments * $symbol **string** - &lt;p&gt;The symbolic representation of the unit.&lt;/p&gt; ### converter \Measurements\UnitConverter Measurements\Dimension::converter() Returns the unit converter used to represent the unit in terms of the dimension's base unit. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### getBaseUnit mixed Measurements\Dimension::getBaseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### symbol string Measurements\Unit::symbol() Return the symbolic representation of the unit. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) ### isEqualTo boolean Measurements\Equatable::isEqualTo(mixed $other) Returns a boolean value that indicates whether the receiver is equal to another given object. * Visibility: **public** * This method is defined by [Measurements\Equatable](Measurements-Equatable.md) #### Arguments * $other **mixed** - &lt;p&gt;The object with which to compare the receiver.&lt;/p&gt; ### __toString string Measurements\Unit::__toString() Converts the unit to its string representation. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) <file_sep>/doc/Measurements-Quantities-ConcentrationMass.md Measurements\Quantities\ConcentrationMass =============== The `ConcentrationMass` class represents a specific quantities of concentration. * Class name: ConcentrationMass * Namespace: Measurements\Quantities * Parent class: Measurements\Measurement Methods ------- ### __construct mixed Measurements\Quantities\ConcentrationMass::__construct(double $value, \Measurements\Unit $unit) Initializes a new concentration of mass measurement with a specified floating-point value and unit. * Visibility: **public** #### Arguments * $value **double** - &lt;p&gt;The measurement value.&lt;/p&gt; * $unit **[Measurements\Unit](Measurements-Unit.md)** - &lt;p&gt;The unit of measure.&lt;/p&gt; ### fromMassAndVolume \Measurements\Quantities\ConcentrationMass Measurements\Quantities\ConcentrationMass::fromMassAndVolume(\Measurements\Quantities\Mass $mass, \Measurements\Quantities\Volume $volume) Returns a concentration of mass measurement computed from the specified mass and volume. * Visibility: **public** * This method is **static**. #### Arguments * $mass **[Measurements\Quantities\Mass](Measurements-Quantities-Mass.md)** - &lt;p&gt;A mass.&lt;/p&gt; * $volume **[Measurements\Quantities\Volume](Measurements-Quantities-Volume.md)** - &lt;p&gt;A volume.&lt;/p&gt; <file_sep>/src/Units/UnitVolume.php <?php namespace Measurements\Units; use Measurements\Dimension; use Measurements\Converters\UnitConverterLinear; /** * The `UnitVolume` class encapsulates units of measure for volume. * You typically use instances of `UnitVolume` to represent specific quantities of volume using the `Measurement` class. * Volume is a quantity of the extend of matter in three dimensions. * The SI accepted unit of volume is the liter (L), which is derived as one cubic decimeter (1 dm3). * Volume is also commonly expressed in terms of cubic meters (m3), gallons (gal), and cups (cup). * The base unit of `UnitVolume` is defined as liters. */ class UnitVolume extends Dimension { const SYMBOL_MEGALITERS = "ML"; const SYMBOL_KILOLITERS = "kL"; const SYMBOL_LITERS = "L"; const SYMBOL_DECILITERS = "dL"; const SYMBOL_CENTILITERS = "cL"; const SYMBOL_MILLILITERS = "mL"; const SYMBOL_CUBIC_KILOMETERS = "km³"; const SYMBOL_CUBIC_METERS = "m³"; const SYMBOL_CUBIC_DECIMETERS = "dm³"; const SYMBOL_CUBIC_CENTIMETERS = "cm³"; const SYMBOL_CUBIC_MILLIMETERS = "mm³"; const SYMBOL_CUBIC_INCHES = "in³"; const SYMBOL_CUBIC_FEET = "ft³"; const SYMBOL_CUBIC_YARDS = "yd³"; const SYMBOL_CUBIC_MILES = "mi³"; const SYMBOL_ACRE_FEET = "af"; const SYMBOL_BUSHELS = "bsh"; const SYMBOL_TEASPOONS = "tsp"; const SYMBOL_TABLESPOONS = "tbsp"; const SYMBOL_FLUID_OUNCES = "fl oz"; const SYMBOL_CUPS = "cup"; const SYMBOL_PINTS = "pt"; const SYMBOL_QUARTS = "qt"; const SYMBOL_GALLONS = "gal"; const SYMBOL_IMPERIAL_TEASPOONS = "tsp Imperial"; const SYMBOL_IMPERIAL_TABLESPOONS = "tbsp Imperial"; const SYMBOL_IMPERIAL_FLUID_OUNCES = "fl oz Imperial"; const SYMBOL_IMPERIAL_PINTS = "pt Imperial"; const SYMBOL_IMPERIAL_QUARTS = "qt Imperial"; const SYMBOL_IMPERIAL_GALLONS = "gal Imperial"; const SYMBOL_METRIC_CUPS = "metric cup Imperial"; const COEFFICIENT_MEGALITERS = 1E+6; const COEFFICIENT_KILOLITERS = 1000.0; const COEFFICIENT_LITERS = 1.0; const COEFFICIENT_DECILITERS = 0.1; const COEFFICIENT_CENTILITERS = 0.01; const COEFFICIENT_MILLILITERS = 0.001; const COEFFICIENT_CUBIC_KILOMETERS = 1E+12; const COEFFICIENT_CUBIC_METERS = 1000.0; const COEFFICIENT_CUBIC_DECIMETERS = 1.0; const COEFFICIENT_CUBIC_CENTIMETERS = 0.01; const COEFFICIENT_CUBIC_MILLIMETERS = 0.001; const COEFFICIENT_CUBIC_INCHES = 0.0163871; const COEFFICIENT_CUBIC_FEET = 28.3168; const COEFFICIENT_CUBIC_YARDS = 764.555; const COEFFICIENT_CUBIC_MILES = 4.168E+12; const COEFFICIENT_ACRE_FEET = 1.233E+6; const COEFFICIENT_BUSHELS = 35.2391; const COEFFICIENT_TEASPOONS = 0.00492892; const COEFFICIENT_TABLESPOONS = 0.0147868; const COEFFICIENT_FLUID_OUNCES = 0.0295735; const COEFFICIENT_CUPS = 0.24; const COEFFICIENT_PINTS = 0.473176; const COEFFICIENT_QUARTS = 0.946353; const COEFFICIENT_GALLONS = 3.78541; const COEFFICIENT_IMPERIAL_TEASPOONS = 0.00591939; const COEFFICIENT_IMPERIAL_TABLESPOONS = 0.0177582; const COEFFICIENT_IMPERIAL_FLUID_OUNCES = 0.0284131; const COEFFICIENT_IMPERIAL_PINTS = 0.568261; const COEFFICIENT_IMPERIAL_QUARTS = 1.13652; const COEFFICIENT_IMPERIAL_GALLONS = 4.54609; const COEFFICIENT_METRIC_CUPS = 0.25; /** * Returns the base unit of volume, equal to liters. * * @return UnitVolume The base unit of volume. */ public static function baseUnit() { return self::liters(); } /** * Returns the megaliters unit of volume. * * @return UnitVolume The megaliters unit of volume. */ public static function megaliters(): UnitVolume { return new static(static::SYMBOL_MEGALITERS, new UnitConverterLinear(static::COEFFICIENT_MEGALITERS)); } /** * Returns the kiloliters unit of volume. * * @return UnitVolume The kiloliters unit of volume. */ public static function kiloliters(): UnitVolume { return new static(static::SYMBOL_KILOLITERS, new UnitConverterLinear(static::COEFFICIENT_KILOLITERS)); } /** * Returns the liters unit of volume. * * @return UnitVolume The liters unit of volume. */ public static function liters(): UnitVolume { return new static(static::SYMBOL_LITERS, new UnitConverterLinear(static::COEFFICIENT_LITERS)); } /** * Returns the deciliters unit of volume. * * @return UnitVolume The deciliters unit of volume. */ public static function deciliters(): UnitVolume { return new static(static::SYMBOL_DECILITERS, new UnitConverterLinear(static::COEFFICIENT_DECILITERS)); } /** * Returns the centiliters unit of volume. * * @return UnitVolume The centiliters unit of volume. */ public static function centiliters(): UnitVolume { return new static(static::SYMBOL_CENTILITERS, new UnitConverterLinear(static::COEFFICIENT_CENTILITERS)); } /** * Returns the milliliters unit of volume. * * @return UnitVolume The milliliters unit of volume. */ public static function milliliters(): UnitVolume { return new static(static::SYMBOL_MILLILITERS, new UnitConverterLinear(static::COEFFICIENT_MILLILITERS)); } /** * Returns the cubic kilometers unit of volume. * * @return UnitVolume The cubic kilometers unit of volume. */ public static function cubicKilometers(): UnitVolume { return new static(static::SYMBOL_CUBIC_KILOMETERS, new UnitConverterLinear(static::COEFFICIENT_CUBIC_KILOMETERS)); } /** * Returns the cubic meters unit of volume. * * @return UnitVolume The cubic meters unit of volume. */ public static function cubicMeters(): UnitVolume { return new static(static::SYMBOL_CUBIC_METERS, new UnitConverterLinear(static::COEFFICIENT_CUBIC_METERS)); } /** * Returns the cubic decimeters unit of volume. * * @return UnitVolume The cubic decimeters unit of volume. */ public static function cubicDecimeters(): UnitVolume { return new static(static::SYMBOL_CUBIC_DECIMETERS, new UnitConverterLinear(static::COEFFICIENT_CUBIC_DECIMETERS)); } /** * Returns the cubic millimeters unit of volume. * * @return UnitVolume The cubic millimeters unit of volume. */ public static function cubicMillimeters(): UnitVolume { return new static(static::SYMBOL_CUBIC_MILLIMETERS, new UnitConverterLinear(static::COEFFICIENT_CUBIC_MILLIMETERS)); } /** * Returns the cubic inches unit of volume. * * @return UnitVolume The cubic inches unit of volume. */ public static function cubicInches(): UnitVolume { return new static(static::SYMBOL_CUBIC_INCHES, new UnitConverterLinear(static::COEFFICIENT_CUBIC_INCHES)); } /** * Returns the cubic feet unit of volume. * * @return UnitVolume The cubic feet unit of volume. */ public static function cubicFeet(): UnitVolume { return new static(static::SYMBOL_CUBIC_FEET, new UnitConverterLinear(static::COEFFICIENT_CUBIC_FEET)); } /** * Returns the cubic yards unit of volume. * * @return UnitVolume The cubic yards unit of volume. */ public static function cubicYards(): UnitVolume { return new static(static::SYMBOL_CUBIC_YARDS, new UnitConverterLinear(static::COEFFICIENT_CUBIC_YARDS)); } /** * Returns the cubic miles unit of volume. * * @return UnitVolume The cubic miles unit of volume. */ public static function cubicMiles(): UnitVolume { return new static(static::SYMBOL_CUBIC_MILES, new UnitConverterLinear(static::COEFFICIENT_CUBIC_MILES)); } /** * Returns the acre feet unit of volume. * * @return UnitVolume The acre feet unit of volume. */ public static function acreFeet(): UnitVolume { return new static(static::SYMBOL_ACRE_FEET, new UnitConverterLinear(static::COEFFICIENT_ACRE_FEET)); } /** * Returns the bushels unit of volume. * * @return UnitVolume The bushels unit of volume. */ public static function bushels(): UnitVolume { return new static(static::SYMBOL_BUSHELS, new UnitConverterLinear(static::COEFFICIENT_BUSHELS)); } /** * Returns the tea spoons unit of volume. * * @return UnitVolume The tea spoons unit of volume. */ public static function teaspoons(): UnitVolume { return new static(static::SYMBOL_TEASPOONS, new UnitConverterLinear(static::COEFFICIENT_TEASPOONS)); } /** * Returns the table spoons unit of volume. * * @return UnitVolume The table spoons unit of volume. */ public static function tablespoons(): UnitVolume { return new static(static::SYMBOL_TABLESPOONS, new UnitConverterLinear(static::COEFFICIENT_TABLESPOONS)); } /** * Returns the fluid ounces unit of volume. * * @return UnitVolume The fluid ounces unit of volume. */ public static function fluidOunces(): UnitVolume { return new static(static::SYMBOL_FLUID_OUNCES, new UnitConverterLinear(static::COEFFICIENT_FLUID_OUNCES)); } /** * Returns the cups of volume. * * @return UnitVolume The cups unit of volume. */ public static function cups(): UnitVolume { return new static(static::SYMBOL_CUPS, new UnitConverterLinear(static::COEFFICIENT_CUPS)); } /** * Returns the pints unit of volume. * * @return UnitVolume The pints unit of volume. */ public static function pints(): UnitVolume { return new static(static::SYMBOL_PINTS, new UnitConverterLinear(static::COEFFICIENT_PINTS)); } /** * Returns the quarts unit of volume. * * @return UnitVolume The quarts unit of volume. */ public static function quarts(): UnitVolume { return new static(static::SYMBOL_QUARTS, new UnitConverterLinear(static::COEFFICIENT_QUARTS)); } /** * Returns the gallons unit of volume. * * @return UnitVolume The gallons unit of volume. */ public static function gallons(): UnitVolume { return new static(static::SYMBOL_GALLONS, new UnitConverterLinear(static::COEFFICIENT_GALLONS)); } /** * Returns the imperial tea spoons unit of volume. * * @return UnitVolume The imperial tea spoons unit of volume. */ public static function imperialTeaspoons(): UnitVolume { return new static(static::SYMBOL_IMPERIAL_TEASPOONS, new UnitConverterLinear(static::COEFFICIENT_IMPERIAL_TEASPOONS)); } /** * Returns the imperial table spoons unit of volume. * * @return UnitVolume The imperial table spoons unit of volume. */ public static function imperialTablespoons(): UnitVolume { return new static(static::SYMBOL_IMPERIAL_TABLESPOONS, new UnitConverterLinear(static::COEFFICIENT_IMPERIAL_TABLESPOONS)); } /** * Returns the imperial fluid ounces unit of volume. * * @return UnitVolume The imperial fluid ounces unit of volume. */ public static function imperialFluidOunces(): UnitVolume { return new static(static::SYMBOL_IMPERIAL_FLUID_OUNCES, new UnitConverterLinear(static::COEFFICIENT_IMPERIAL_FLUID_OUNCES)); } /** * Returns the imperial pints unit of volume. * * @return UnitVolume The imperial pints unit of volume. */ public static function imperialPints(): UnitVolume { return new static(static::SYMBOL_IMPERIAL_PINTS, new UnitConverterLinear(static::COEFFICIENT_IMPERIAL_PINTS)); } /** * Returns the imperial quarts unit of volume. * * @return UnitVolume The imperial quarts unit of volume. */ public static function imperialQuarts(): UnitVolume { return new static(static::SYMBOL_IMPERIAL_QUARTS, new UnitConverterLinear(static::COEFFICIENT_IMPERIAL_QUARTS)); } /** * Returns the imperial gallons unit of volume. * * @return UnitVolume The imperial gallons unit of volume. */ public static function imperialGallons(): UnitVolume { return new static(static::SYMBOL_IMPERIAL_GALLONS, new UnitConverterLinear(static::COEFFICIENT_IMPERIAL_GALLONS)); } /** * Returns the metric cups unit of volume. * * @return UnitVolume The metric cups unit of volume. */ public static function metricCups(): UnitVolume { return new static(static::SYMBOL_METRIC_CUPS, new UnitConverterLinear(static::COEFFICIENT_METRIC_CUPS)); } } <file_sep>/tests/Units/UnitPressureTests.php <?php namespace Tests\Units; use PHPUnit\Framework\TestCase; use Measurements\Measurement; use Measurements\Units\UnitPressure; class UnitPressureTests extends TestCase { use InteractsWithUnits; /** @test */ public function it_defines_newtons_per_meter_squared_as_base_unit() { $this->assertTrue(UnitPressure::baseUnit() == UnitPressure::newtonsPerMeterSquared(), "Pressure should define newtons per meter squared as its base unit."); } /** @test */ public function it_converts_pressures() { $base = new Measurement(1, UnitPressure::baseUnit()); $this->assertMeasurementEquals($base->convertTo(UnitPressure::newtonsPerMeterSquared()), 1.0, $base, "newtons per meter squared"); $this->assertMeasurementEquals($base->convertTo(UnitPressure::gigapascals()), 1.0 / 1E+9, $base, "gigapascals"); $this->assertMeasurementEquals($base->convertTo(UnitPressure::megapascals()), 1E-6, $base, "megapascals"); $this->assertMeasurementEquals($base->convertTo(UnitPressure::kilopascals()), 0.001, $base, "kilopascals"); $this->assertMeasurementEquals($base->convertTo(UnitPressure::hectopascals()), 0.01, $base, "hectopascals"); $this->assertMeasurementEquals($base->convertTo(UnitPressure::pascals()), 1.0, $base, "pascals"); $this->assertMeasurementEquals($base->convertTo(UnitPressure::inchesOfMercury()), 1.0 / 3386.39, $base, "inches of mercury"); $this->assertMeasurementEquals($base->convertTo(UnitPressure::bars()), 1E-5, $base, "bars"); $this->assertMeasurementEquals($base->convertTo(UnitPressure::millibars()), 0.01, $base, "millibars"); $this->assertMeasurementEquals($base->convertTo(UnitPressure::millimetersOfMercury()), 1.0 / 133.322, $base, "millimeters of mercury"); $this->assertMeasurementEquals($base->convertTo(UnitPressure::poundsPerSquareInch()), 1.0 / 6894.76, $base, "pounds per square inch"); } }<file_sep>/tests/Units/UnitPowerTests.php <?php namespace Tests\Units; use PHPUnit\Framework\TestCase; use Measurements\Measurement; use Measurements\Units\UnitPower; class UnitPowerTests extends TestCase { use InteractsWithUnits; /** @test */ public function it_defines_watts_as_base_unit() { $this->assertTrue(UnitPower::baseUnit() == UnitPower::watts(), "Power should define watts as its base unit."); } /** @test */ public function it_converts_powers() { $base = new Measurement(1, UnitPower::baseUnit()); $this->assertMeasurementEquals($base->convertTo(UnitPower::terawatts()), 1.0 / 1E+12, $base, "terawatts"); $this->assertMeasurementEquals($base->convertTo(UnitPower::gigawatts()), 1.0 / 1E+9, $base, "gigawatts"); $this->assertMeasurementEquals($base->convertTo(UnitPower::megawatts()), 1.0 / 1E+6, $base, "megawatts"); $this->assertMeasurementEquals($base->convertTo(UnitPower::kilowatts()), 0.001, $base, "kilowatts"); $this->assertMeasurementEquals($base->convertTo(UnitPower::watts()), 1.0, $base, "watts"); $this->assertMeasurementEquals($base->convertTo(UnitPower::milliwatts()), 1000, $base, "milliwatts"); $this->assertMeasurementEquals($base->convertTo(UnitPower::microwatts()), 1.0 / 1E-6, $base, "microwatts"); $this->assertMeasurementEquals($base->convertTo(UnitPower::nanowatts()), 1.0 / 1E-9, $base, "nanowatts"); $this->assertMeasurementEquals($base->convertTo(UnitPower::picowatts()), 1.0 / 1E-12, $base, "picowatts"); $this->assertMeasurementEquals($base->convertTo(UnitPower::femtowatts()), 1.0 / 1E-15, $base, "femtowatts"); $this->assertMeasurementEquals($base->convertTo(UnitPower::horsepower()), 1.0 / 745.7, $base, "horsepower"); } }<file_sep>/doc/Measurements-Units-UnitTemperature.md Measurements\Units\UnitTemperature =============== The `UnitTemperature` class encapsulates units of measure for temperature. You typically use instances of `UnitTemperature` to represent specific quantities of temperature using the `Measurement` class. Temperature is a comparative measure of thermal energy. The SI unit for temperature is the kelvin (K), which is defined in terms of the triple point of water. Temperature is also commonly measured by degrees of various scales, including Celsius (°C) and Fahrenheit (°F). The base unit of `UnitTemperature` is defined as kelvin. * Class name: UnitTemperature * Namespace: Measurements\Units * Parent class: [Measurements\Dimension](Measurements-Dimension.md) Constants ---------- ### SYMBOL_KELVIN const SYMBOL_KELVIN = "K" ### SYMBOL_DEGREES_CELSIUS const SYMBOL_DEGREES_CELSIUS = "°C" ### SYMBOL_DEGREES_FAHRENHEIT const SYMBOL_DEGREES_FAHRENHEIT = "°F" ### COEFFICIENT_KELVIN const COEFFICIENT_KELVIN = 1.0 ### COEFFICIENT_DEGREES_CELSIUS const COEFFICIENT_DEGREES_CELSIUS = 1.0 ### COEFFICIENT_DEGREES_FAHRENHEIT const COEFFICIENT_DEGREES_FAHRENHEIT = 5.0 / 9.0 ### CONSTANT_DEGREES_CELSIUS const CONSTANT_DEGREES_CELSIUS = 273.15 ### CONSTANT_DEGREES_FAHRENHEIT const CONSTANT_DEGREES_FAHRENHEIT = 255.37222222222428 Properties ---------- ### $converter protected \Measurements\UnitConverter $converter The converter used to represent the unit in terms of the dimension's base unit. * Visibility: **protected** ### $symbol protected string $symbol The symbolic representation of the unit. * Visibility: **protected** Methods ------- ### baseUnit mixed Measurements\BaseUnitConvertible::baseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is **static**. * This method is defined by [Measurements\BaseUnitConvertible](Measurements-BaseUnitConvertible.md) ### kelvin \Measurements\Units\UnitTemperature Measurements\Units\UnitTemperature::kelvin() Returns the kelvin unit of temperature. * Visibility: **public** * This method is **static**. ### celsius \Measurements\Units\UnitTemperature Measurements\Units\UnitTemperature::celsius() Returns the degree Celsius unit of temperature. * Visibility: **public** * This method is **static**. ### fahrenheit \Measurements\Units\UnitTemperature Measurements\Units\UnitTemperature::fahrenheit() Returns the degree Fahrenheit unit of temperature. * Visibility: **public** * This method is **static**. ### __construct mixed Measurements\Unit::__construct(string $symbol) Initializes a new unit with the specified symbol. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) #### Arguments * $symbol **string** - &lt;p&gt;The symbolic representation of the unit.&lt;/p&gt; ### converter \Measurements\UnitConverter Measurements\Dimension::converter() Returns the unit converter used to represent the unit in terms of the dimension's base unit. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### getBaseUnit mixed Measurements\Dimension::getBaseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### symbol string Measurements\Unit::symbol() Return the symbolic representation of the unit. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) ### isEqualTo boolean Measurements\Equatable::isEqualTo(mixed $other) Returns a boolean value that indicates whether the receiver is equal to another given object. * Visibility: **public** * This method is defined by [Measurements\Equatable](Measurements-Equatable.md) #### Arguments * $other **mixed** - &lt;p&gt;The object with which to compare the receiver.&lt;/p&gt; ### __toString string Measurements\Unit::__toString() Converts the unit to its string representation. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) <file_sep>/src/Units/UnitArea.php <?php namespace Measurements\Units; use Measurements\Dimension; use Measurements\Converters\UnitConverterLinear; /** * The `UnitArea` class encapsulates units of measure for area. * You typically use instances of `UnitArea` to represent specific quantities of area using the `Measurement` class. * * Area is a quantity of extent in two dimensions. Area can be expressed by SI derived units in terms of square meters (m2). * Area is also commonly measured in square feet (ft2) and acres (ac). * * The base unit of `UnitArea` is defined as square meters. */ class UnitArea extends Dimension { const SYMBOL_SQUARE_MEGAMETERS = "Mm²"; const SYMBOL_SQUARE_KILOMETERS = "km²"; const SYMBOL_SQUARE_METERS = "m²"; const SYMBOL_SQUARE_CENTIMETERS = "cm²"; const SYMBOL_SQUARE_MILLIMETERS = "mm²"; const SYMBOL_SQUARE_MICROMETERS = "µm²"; const SYMBOL_SQUARE_NANOMETERS = "nm²"; const SYMBOL_SQUARE_INCHES = "in²"; const SYMBOL_SQUARE_FEET = "ft²"; const SYMBOL_SQUARE_YARDS = "yd²"; const SYMBOL_SQUARE_MILES = "mi²"; const SYMBOL_SQUARE_ACRES = "ac"; const SYMBOL_SQUARE_ARES = "a"; const SYMBOL_SQUARE_HECTARES = "ha"; const COEFFICIENT_SQUARE_MEGAMETERS = 1E+12; const COEFFICIENT_SQUARE_KILOMETERS = 1E+6; const COEFFICIENT_SQUARE_METERS = 1.0; const COEFFICIENT_SQUARE_CENTIMETERS = 1E-4; const COEFFICIENT_SQUARE_MILLIMETERS = 1E-6; const COEFFICIENT_SQUARE_MICROMETERS = 1E-12; const COEFFICIENT_SQUARE_NANOMETERS = 1E-18; const COEFFICIENT_SQUARE_INCHES = 0.00064516; const COEFFICIENT_SQUARE_FEET = 0.092903; const COEFFICIENT_SQUARE_YARDS = 0.836127; const COEFFICIENT_SQUARE_MILES = 2.59E+6; const COEFFICIENT_SQUARE_ACRES = 4046.86; const COEFFICIENT_SQUARE_ARES = 100.0; const COEFFICIENT_SQUARE_HECTARES = 10000.0; /** * Returns the base unit of area, equal to square meters. * * @return UnitArea The base unit of area. */ public static function baseUnit() { return self::squareMeters(); } /** * Returns the square megameters unit of area. * * @return UnitArea The square megameters unit of area. */ public static function squareMegameters(): UnitArea { return new static(static::SYMBOL_SQUARE_MEGAMETERS, new UnitConverterLinear(static::COEFFICIENT_SQUARE_MEGAMETERS)); } /** * Returns the square kilometers unit of area. * * @return UnitArea The square kilometers unit of area. */ public static function squareKilometers(): UnitArea { return new static(static::SYMBOL_SQUARE_KILOMETERS, new UnitConverterLinear(static::COEFFICIENT_SQUARE_KILOMETERS)); } /** * Returns the square meters unit of area. * * @return UnitArea The square meters unit of area. */ public static function squareMeters(): UnitArea { return new static(static::SYMBOL_SQUARE_METERS, new UnitConverterLinear(static::COEFFICIENT_SQUARE_METERS)); } /** * Returns the square centimeters unit of area. * * @return UnitArea The square centimeters unit of area. */ public static function squareCentimeters(): UnitArea { return new static(static::SYMBOL_SQUARE_CENTIMETERS, new UnitConverterLinear(static::COEFFICIENT_SQUARE_CENTIMETERS)); } /** * Returns the square millimeters unit of area. * * @return UnitArea The square millimeters unit of area. */ public static function squareMillimeters(): UnitArea { return new static(static::SYMBOL_SQUARE_MILLIMETERS, new UnitConverterLinear(static::COEFFICIENT_SQUARE_MILLIMETERS)); } /** * Returns the square micrometers unit of area. * * @return UnitArea The square micrometers unit of area. */ public static function squareMicrometers(): UnitArea { return new static(static::SYMBOL_SQUARE_MICROMETERS, new UnitConverterLinear(static::COEFFICIENT_SQUARE_MICROMETERS)); } /** * Returns the square nanometers unit of area. * * @return UnitArea The square nanometers unit of area. */ public static function squareNanometers(): UnitArea { return new static(static::SYMBOL_SQUARE_NANOMETERS, new UnitConverterLinear(static::COEFFICIENT_SQUARE_NANOMETERS)); } /** * Returns the square inches unit of area. * * @return UnitArea The square inches unit of area. */ public static function squareInches(): UnitArea { return new static(static::SYMBOL_SQUARE_INCHES, new UnitConverterLinear(static::COEFFICIENT_SQUARE_INCHES)); } /** * Returns the square feet unit of area. * * @return UnitArea The square feet unit of area. */ public static function squareFeet(): UnitArea { return new static(static::SYMBOL_SQUARE_FEET, new UnitConverterLinear(static::COEFFICIENT_SQUARE_FEET)); } /** * Returns the square yards unit of area. * * @return UnitArea The square yards unit of area. */ public static function squareYards(): UnitArea { return new static(static::SYMBOL_SQUARE_YARDS, new UnitConverterLinear(static::COEFFICIENT_SQUARE_YARDS)); } /** * Returns the square miles unit of area. * * @return UnitArea The square miles unit of area. */ public static function squareMiles(): UnitArea { return new static(static::SYMBOL_SQUARE_MILES, new UnitConverterLinear(static::COEFFICIENT_SQUARE_MILES)); } /** * Returns the acres unit of area. * * @return UnitArea The acres unit of area. */ public static function acres(): UnitArea { return new static(static::SYMBOL_SQUARE_ACRES, new UnitConverterLinear(static::COEFFICIENT_SQUARE_ACRES)); } /** * Returns the ares unit of area. * * @return UnitArea The ares unit of area. */ public static function ares(): UnitArea { return new static(static::SYMBOL_SQUARE_ARES, new UnitConverterLinear(static::COEFFICIENT_SQUARE_ARES)); } /** * Returns the hectares unit of area. * * @return UnitArea The hectares unit of area. */ public static function hectares(): UnitArea { return new static(static::SYMBOL_SQUARE_HECTARES, new UnitConverterLinear(static::COEFFICIENT_SQUARE_HECTARES)); } } <file_sep>/doc/Measurements-Units-UnitElectricResistance.md Measurements\Units\UnitElectricResistance =============== The `UnitElectricResistance` class encapsulates units of measure for electric resistance. You typically use instances of `UnitElectricResistance` to represent specific quantities of electric resistance using the `Measurement` class. Electric resistance is the difficulty of passing an electric current through a conductor. The SI unit for electric resistance is the ohm (Ω), which is derived as the electric resistance that produces one ampere of current between two points in conductor with one volt of electric resistance (1Ω = 1V/1A). The base unit of `UnitElectricResistance` is defined as coulombs. * Class name: UnitElectricResistance * Namespace: Measurements\Units * Parent class: [Measurements\Dimension](Measurements-Dimension.md) Constants ---------- ### SYMBOL_MEGAOHMS const SYMBOL_MEGAOHMS = "MΩ" ### SYMBOL_KILOOHMS const SYMBOL_KILOOHMS = "kΩ" ### SYMBOL_OHMS const SYMBOL_OHMS = "Ω" ### SYMBOL_MILLIOHMS const SYMBOL_MILLIOHMS = "mΩ" ### SYMBOL_MICROOHMS const SYMBOL_MICROOHMS = "µΩ" ### COEFFICIENT_MEGAOHMS const COEFFICIENT_MEGAOHMS = 1000000.0 ### COEFFICIENT_KILOOHMS const COEFFICIENT_KILOOHMS = 1000.0 ### COEFFICIENT_OHMS const COEFFICIENT_OHMS = 1.0 ### COEFFICIENT_MILLIOHMS const COEFFICIENT_MILLIOHMS = 0.001 ### COEFFICIENT_MICROOHMS const COEFFICIENT_MICROOHMS = 1.0E-6 Properties ---------- ### $converter protected \Measurements\UnitConverter $converter The converter used to represent the unit in terms of the dimension's base unit. * Visibility: **protected** ### $symbol protected string $symbol The symbolic representation of the unit. * Visibility: **protected** Methods ------- ### baseUnit mixed Measurements\BaseUnitConvertible::baseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is **static**. * This method is defined by [Measurements\BaseUnitConvertible](Measurements-BaseUnitConvertible.md) ### megaohms \Measurements\Units\UnitElectricResistance Measurements\Units\UnitElectricResistance::megaohms() Returns the megaohms unit of electric resistance. * Visibility: **public** * This method is **static**. ### kiloohms \Measurements\Units\UnitElectricResistance Measurements\Units\UnitElectricResistance::kiloohms() Returns the kiloohms unit of electric resistance. * Visibility: **public** * This method is **static**. ### ohms \Measurements\Units\UnitElectricResistance Measurements\Units\UnitElectricResistance::ohms() Returns the ohms unit of electric resistance. * Visibility: **public** * This method is **static**. ### milliohms \Measurements\Units\UnitElectricResistance Measurements\Units\UnitElectricResistance::milliohms() Returns the milliohms unit of electric resistance. * Visibility: **public** * This method is **static**. ### microohms \Measurements\Units\UnitElectricResistance Measurements\Units\UnitElectricResistance::microohms() Returns the microohms unit of electric resistance. * Visibility: **public** * This method is **static**. ### __construct mixed Measurements\Unit::__construct(string $symbol) Initializes a new unit with the specified symbol. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) #### Arguments * $symbol **string** - &lt;p&gt;The symbolic representation of the unit.&lt;/p&gt; ### converter \Measurements\UnitConverter Measurements\Dimension::converter() Returns the unit converter used to represent the unit in terms of the dimension's base unit. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### getBaseUnit mixed Measurements\Dimension::getBaseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### symbol string Measurements\Unit::symbol() Return the symbolic representation of the unit. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) ### isEqualTo boolean Measurements\Equatable::isEqualTo(mixed $other) Returns a boolean value that indicates whether the receiver is equal to another given object. * Visibility: **public** * This method is defined by [Measurements\Equatable](Measurements-Equatable.md) #### Arguments * $other **mixed** - &lt;p&gt;The object with which to compare the receiver.&lt;/p&gt; ### __toString string Measurements\Unit::__toString() Converts the unit to its string representation. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) <file_sep>/doc/Measurements-Units-UnitElectricCharge.md Measurements\Units\UnitElectricCharge =============== The `UnitElectricCharge` class encapsulates units of measure for electric charge. You typically use instances of `UnitElectricCharge` to represent specific quantities of electric charge using the `Measurement` class. Electric charge is a fundamental physical property of matter that causes it to experience a force within an electromagnetic field. The SI unit for electric charge is the coulomb (C), which is defined as the amount of charge carried by a current of one ampere in one second (1C = 1A · 1s). Charge is also commonly expressed in terms of ampere hours (Ah). The base unit of `UnitElectricCharge` is defined as coulombs. * Class name: UnitElectricCharge * Namespace: Measurements\Units * Parent class: [Measurements\Dimension](Measurements-Dimension.md) Constants ---------- ### SYMBOL_COULOMBS const SYMBOL_COULOMBS = "C" ### SYMBOL_MEGAAMPERE_HOURS const SYMBOL_MEGAAMPERE_HOURS = "MAh" ### SYMBOL_KILOAMPERE_HOURS const SYMBOL_KILOAMPERE_HOURS = "kAh" ### SYMBOL_AMPERE_HOURS const SYMBOL_AMPERE_HOURS = "Ah" ### SYMBOL_MILLIAMPERE_HOURS const SYMBOL_MILLIAMPERE_HOURS = "mAh" ### SYMBOL_MICROAMPERE_HOURS const SYMBOL_MICROAMPERE_HOURS = "µAh" ### COEFFICIENT_COULOMBS const COEFFICIENT_COULOMBS = 1.0 ### COEFFICIENT_MEGAAMPERE_HOURS const COEFFICIENT_MEGAAMPERE_HOURS = 3600000000.0 ### COEFFICIENT_KILOAMPERE_HOURS const COEFFICIENT_KILOAMPERE_HOURS = 3600000.0 ### COEFFICIENT_AMPERE_HOURS const COEFFICIENT_AMPERE_HOURS = 3600.0 ### COEFFICIENT_MILLIAMPERE_HOURS const COEFFICIENT_MILLIAMPERE_HOURS = 3.6 ### COEFFICIENT_MICROAMPERE_HOURS const COEFFICIENT_MICROAMPERE_HOURS = 0.0036 Properties ---------- ### $converter protected \Measurements\UnitConverter $converter The converter used to represent the unit in terms of the dimension's base unit. * Visibility: **protected** ### $symbol protected string $symbol The symbolic representation of the unit. * Visibility: **protected** Methods ------- ### baseUnit mixed Measurements\BaseUnitConvertible::baseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is **static**. * This method is defined by [Measurements\BaseUnitConvertible](Measurements-BaseUnitConvertible.md) ### coulombs \Measurements\Units\UnitElectricCharge Measurements\Units\UnitElectricCharge::coulombs() Returns the coulombs unit of electric charge. * Visibility: **public** * This method is **static**. ### megaampereHours \Measurements\Units\UnitElectricCharge Measurements\Units\UnitElectricCharge::megaampereHours() Returns the megaampere hours unit of electric charge. * Visibility: **public** * This method is **static**. ### kiloampereHours \Measurements\Units\UnitElectricCharge Measurements\Units\UnitElectricCharge::kiloampereHours() Returns the kiloampere hours unit of electric charge. * Visibility: **public** * This method is **static**. ### ampereHours \Measurements\Units\UnitElectricCharge Measurements\Units\UnitElectricCharge::ampereHours() Returns the ampere hours unit of electric charge. * Visibility: **public** * This method is **static**. ### milliampereHours \Measurements\Units\UnitElectricCharge Measurements\Units\UnitElectricCharge::milliampereHours() Returns the milliampere hours unit of electric charge. * Visibility: **public** * This method is **static**. ### microampereHours \Measurements\Units\UnitElectricCharge Measurements\Units\UnitElectricCharge::microampereHours() Returns the microampere hours unit of electric charge. * Visibility: **public** * This method is **static**. ### __construct mixed Measurements\Unit::__construct(string $symbol) Initializes a new unit with the specified symbol. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) #### Arguments * $symbol **string** - &lt;p&gt;The symbolic representation of the unit.&lt;/p&gt; ### converter \Measurements\UnitConverter Measurements\Dimension::converter() Returns the unit converter used to represent the unit in terms of the dimension's base unit. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### getBaseUnit mixed Measurements\Dimension::getBaseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### symbol string Measurements\Unit::symbol() Return the symbolic representation of the unit. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) ### isEqualTo boolean Measurements\Equatable::isEqualTo(mixed $other) Returns a boolean value that indicates whether the receiver is equal to another given object. * Visibility: **public** * This method is defined by [Measurements\Equatable](Measurements-Equatable.md) #### Arguments * $other **mixed** - &lt;p&gt;The object with which to compare the receiver.&lt;/p&gt; ### __toString string Measurements\Unit::__toString() Converts the unit to its string representation. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) <file_sep>/tests/Units/UnitMassTests.php <?php namespace Tests\Units; use PHPUnit\Framework\TestCase; use Measurements\Measurement; use Measurements\Units\UnitMass; class UnitMassTests extends TestCase { use InteractsWithUnits; /** @test */ public function it_defines_kilograms_as_base_unit() { $this->assertTrue(UnitMass::baseUnit() == UnitMass::kilograms(), "Mass should define kilograms as its base unit."); } /** @test */ public function it_converts_masses() { $base = new Measurement(1, UnitMass::baseUnit()); $this->assertMeasurementEquals($base->convertTo(UnitMass::kilograms()), 1.0, $base, "kilograms"); $this->assertMeasurementEquals($base->convertTo(UnitMass::grams()), 1000, $base, "grams"); $this->assertMeasurementEquals($base->convertTo(UnitMass::decigrams()), 10000, $base, "decigrams"); $this->assertMeasurementEquals($base->convertTo(UnitMass::centigrams()), 1.0 / 1E-5, $base, "centigrams"); $this->assertMeasurementEquals($base->convertTo(UnitMass::milligrams()), 1.0 / 1E-6, $base, "milligrams"); $this->assertMeasurementEquals($base->convertTo(UnitMass::micrograms()), 1.0 / 1E-9, $base, "micrograms"); $this->assertMeasurementEquals($base->convertTo(UnitMass::nanograms()), 1.0 / 1E-12, $base, "nanograms"); $this->assertMeasurementEquals($base->convertTo(UnitMass::picograms()), 1.0 / 1E-15, $base, "picograms"); $this->assertMeasurementEquals($base->convertTo(UnitMass::ounces()), 1.0 / 0.0283495, $base, "ounces"); $this->assertMeasurementEquals($base->convertTo(UnitMass::ouncesTroy()), 1.0 / 0.03110348, $base, "ounces Troy"); $this->assertMeasurementEquals($base->convertTo(UnitMass::pounds()), 1.0 / 0.453592, $base, "pounds"); $this->assertMeasurementEquals($base->convertTo(UnitMass::stones()), 1.0 / 0.157473, $base, "stones"); $this->assertMeasurementEquals($base->convertTo(UnitMass::metricTons()), 1.0 / 1000, $base, "metric tons"); $this->assertMeasurementEquals($base->convertTo(UnitMass::shortTons()), 1.0 / 907.185, $base, "short tons"); $this->assertMeasurementEquals($base->convertTo(UnitMass::carats()), 1.0 / 0.0002, $base, "carats"); $this->assertMeasurementEquals($base->convertTo(UnitMass::slugs()), 1.0 / 14.5939, $base, "slugs"); } }<file_sep>/src/Units/UnitDuration.php <?php namespace Measurements\Units; use Measurements\Dimension; use Measurements\Converters\UnitConverterLinear; /** * The `UnitDuration` class encapsulates units of measure for duration of time. * You typically use instances of `UnitDuration` to represent specific quantities of planar angle using the `Measurement` class. * * Duration is a quantity of time. The SI unit for time is the second (sec). Duration is also commonly expressed in terms of minutes (min) and hours (hr). * * The base unit of `UnitDuration` is defined as seconds. */ class UnitDuration extends Dimension { const SYMBOL_SECONDS = "sec"; const SYMBOL_MINUTES = "min"; const SYMBOL_HOURS = "hr"; const COEFFICIENT_SECONDS = 1.0; const COEFFICIENT_MINUTES = 60.0; const COEFFICIENT_HOURS = 3600.0; /** * Returns the base unit of duration, equal to seconds. * * @return UnitDuration The base unit of duration. */ public static function baseUnit() { return self::seconds(); } /** * Returns the second unit of duration. * * @return UnitDuration The second unit of duration. */ public static function seconds(): UnitDuration { return new static(static::SYMBOL_SECONDS, new UnitConverterLinear(static::COEFFICIENT_SECONDS)); } /** * Returns the minute unit of duration. * * @return UnitDuration The minute unit of duration. */ public static function minutes(): UnitDuration { return new static(static::SYMBOL_MINUTES, new UnitConverterLinear(static::COEFFICIENT_MINUTES)); } /** * Returns the hour unit of duration. * * @return UnitDuration The hour unit of duration. */ public static function hours(): UnitDuration { return new static(static::SYMBOL_HOURS, new UnitConverterLinear(static::COEFFICIENT_HOURS)); } } <file_sep>/doc/Measurements-Units-UnitRadioactivity.md Measurements\Units\UnitRadioactivity =============== The `UnitRadioactivity` class encapsulates units of measure for radioactivity. You typically use instances of `UnitRadioactivity` to represent specific quantities of radioactivity using the `Measurement` class. Radioactivity is the process by which the nucleus of an atom emits radiation. The SI unit of measure for radioactivity is the becquerel (Bq), which is defined as the quantity of radioactive material in which one nucleus decays per second (1 Bq = 1 s-1). Radioactivity is also commonly described in terms of curies (Ci), a unit defined relative to the decay of one gram of the radium-226 isotope (1 Ci = 3.7 × 1010 Bq). The base unit of `UnitRadioactivity` is defined as becquerel. * Class name: UnitRadioactivity * Namespace: Measurements\Units * Parent class: [Measurements\Dimension](Measurements-Dimension.md) Constants ---------- ### SYMBOL_BECQUEREL const SYMBOL_BECQUEREL = "Bq" ### SYMBOL_CURIE const SYMBOL_CURIE = "Ci" ### COEFFICIENT_BECQUEREL const COEFFICIENT_BECQUEREL = 1.0 ### COEFFICIENT_CURIE const COEFFICIENT_CURIE = 37000000000.0 Properties ---------- ### $converter protected \Measurements\UnitConverter $converter The converter used to represent the unit in terms of the dimension's base unit. * Visibility: **protected** ### $symbol protected string $symbol The symbolic representation of the unit. * Visibility: **protected** Methods ------- ### baseUnit mixed Measurements\BaseUnitConvertible::baseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is **static**. * This method is defined by [Measurements\BaseUnitConvertible](Measurements-BaseUnitConvertible.md) ### becquerel \Measurements\Units\UnitRadioactivity Measurements\Units\UnitRadioactivity::becquerel() Returns the becquerel unit of radioactivity. * Visibility: **public** * This method is **static**. ### curie \Measurements\Units\UnitRadioactivity Measurements\Units\UnitRadioactivity::curie() Returns the curie unit of radioactivity. * Visibility: **public** * This method is **static**. ### __construct mixed Measurements\Unit::__construct(string $symbol) Initializes a new unit with the specified symbol. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) #### Arguments * $symbol **string** - &lt;p&gt;The symbolic representation of the unit.&lt;/p&gt; ### converter \Measurements\UnitConverter Measurements\Dimension::converter() Returns the unit converter used to represent the unit in terms of the dimension's base unit. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### getBaseUnit mixed Measurements\Dimension::getBaseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### symbol string Measurements\Unit::symbol() Return the symbolic representation of the unit. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) ### isEqualTo boolean Measurements\Equatable::isEqualTo(mixed $other) Returns a boolean value that indicates whether the receiver is equal to another given object. * Visibility: **public** * This method is defined by [Measurements\Equatable](Measurements-Equatable.md) #### Arguments * $other **mixed** - &lt;p&gt;The object with which to compare the receiver.&lt;/p&gt; ### __toString string Measurements\Unit::__toString() Converts the unit to its string representation. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) <file_sep>/src/Units/UnitLength.php <?php namespace Measurements\Units; use Measurements\Dimension; use Measurements\Converters\UnitConverterLinear; /** * The `UnitLength` class encapsulates units of measure for length. * You typically use instances of `UnitLength` to represent specific quantities of length using the `Measurement` class. * * Length is the dimensional extent of matter. * The SI unit for length is the meter (m), which is defined in terms of the distance traveled by light in a vacuum. * * The base unit of `UnitLength` is defined as meters. */ class UnitLength extends Dimension { const SYMBOL_MEGAMETERS = "Mm"; const SYMBOL_KILOMETERS = "km"; const SYMBOL_HECTOMETERS = "hm"; const SYMBOL_DECAMETERS = "dam"; const SYMBOL_METERS = "m"; const SYMBOL_DECIMETERS = "dm"; const SYMBOL_CENTIMETERS = "cm"; const SYMBOL_MILLIMETERS = "mm"; const SYMBOL_MICROMETERS = "µm"; const SYMBOL_NANOMETERS = "nm"; const SYMBOL_PICOMETERS = "pm"; const SYMBOL_INCHES = "in"; const SYMBOL_FEET = "ft"; const SYMBOL_YARDS = "yd"; const SYMBOL_MILES = "mi"; const SYMBOL_LIGHTYEARS = "ly"; const SYMBOL_NAUTICAL_MILES = "NM"; const SYMBOL_FATHOMS = "ftm"; const SYMBOL_FURLONGS = "fur"; const SYMBOL_ASTRONOMIC_UNITS = "ua"; const SYMBOL_PARSECS = "pc"; const COEFFICIENT_MEGAMETERS = 1E+6; const COEFFICIENT_KILOMETERS = 1000.0; const COEFFICIENT_HECTOMETERS = 100.0; const COEFFICIENT_DECAMETERS = 10.0; const COEFFICIENT_METERS = 1.0; const COEFFICIENT_DECIMETERS = 0.1; const COEFFICIENT_CENTIMETERS = 0.01; const COEFFICIENT_MILLIMETERS = 0.001; const COEFFICIENT_MICROMETERS = 1E-6; const COEFFICIENT_NANOMETERS = 1E-9; const COEFFICIENT_PICOMETERS = 1E-12; const COEFFICIENT_INCHES = 0.0254; const COEFFICIENT_FEET = 0.3048; const COEFFICIENT_YARDS = 0.9144; const COEFFICIENT_MILES = 1609.34; const COEFFICIENT_LIGHTYEARS = 9.461E+15; const COEFFICIENT_NAUTICAL_MILES = 1852.0; const COEFFICIENT_FATHOMS = 1.8288; const COEFFICIENT_FURLONGS = 201.168; const COEFFICIENT_ASTRONOMIC_UNITS = 1.496E+11; const COEFFICIENT_PARSECS = 3.086E+16; /** * Returns the base unit of length, equal to seconds. * * @return UnitLength The base unit of length. */ public static function baseUnit() { return self::meters(); } /** * Returns the megameters unit of length. * * @return UnitLength The megameters unit of length. */ public static function megameters(): UnitLength { return new static(static::SYMBOL_MEGAMETERS, new UnitConverterLinear(static::COEFFICIENT_MEGAMETERS)); } /** * Returns the kilometers unit of length. * * @return UnitLength The kilometers unit of length. */ public static function kilometers(): UnitLength { return new static(static::SYMBOL_KILOMETERS, new UnitConverterLinear(static::COEFFICIENT_KILOMETERS)); } /** * Returns the hectometers unit of length. * * @return UnitLength The hectometers unit of length. */ public static function hectometers(): UnitLength { return new static(static::SYMBOL_HECTOMETERS, new UnitConverterLinear(static::COEFFICIENT_HECTOMETERS)); } /** * Returns the decameters unit of length. * * @return UnitLength The decameters unit of length. */ public static function decameters(): UnitLength { return new static(static::SYMBOL_DECAMETERS, new UnitConverterLinear(static::COEFFICIENT_DECAMETERS)); } /** * Returns the meters unit of length. * * @return UnitLength The meters unit of length. */ public static function meters(): UnitLength { return new static(static::SYMBOL_METERS, new UnitConverterLinear(static::COEFFICIENT_METERS)); } /** * Returns the decimeters unit of length. * * @return UnitLength The decimeters unit of length. */ public static function decimeters(): UnitLength { return new static(static::SYMBOL_DECIMETERS, new UnitConverterLinear(static::COEFFICIENT_DECIMETERS)); } /** * Returns the centimeters unit of length. * * @return UnitLength The centimeters unit of length. */ public static function centimeters(): UnitLength { return new static(static::SYMBOL_CENTIMETERS, new UnitConverterLinear(static::COEFFICIENT_CENTIMETERS)); } /** * Returns the millimeters unit of length. * * @return UnitLength The millimeters unit of length. */ public static function millimeters(): UnitLength { return new static(static::SYMBOL_MILLIMETERS, new UnitConverterLinear(static::COEFFICIENT_MILLIMETERS)); } /** * Returns the micrometers unit of length. * * @return UnitLength The micrometers unit of length. */ public static function micrometers(): UnitLength { return new static(static::SYMBOL_MICROMETERS, new UnitConverterLinear(static::COEFFICIENT_MICROMETERS)); } /** * Returns the nanometers unit of length. * * @return UnitLength The nanometers unit of length. */ public static function nanometers(): UnitLength { return new static(static::SYMBOL_NANOMETERS, new UnitConverterLinear(static::COEFFICIENT_NANOMETERS)); } /** * Returns the picometers unit of length. * * @return UnitLength The picometers unit of length. */ public static function picometers(): UnitLength { return new static(static::SYMBOL_PICOMETERS, new UnitConverterLinear(static::COEFFICIENT_PICOMETERS)); } /** * Returns the inches unit of length. * * @return UnitLength The inches unit of length. */ public static function inches(): UnitLength { return new static(static::SYMBOL_INCHES, new UnitConverterLinear(static::COEFFICIENT_INCHES)); } /** * Returns the feet unit of length. * * @return UnitLength The feet unit of length. */ public static function feet(): UnitLength { return new static(static::SYMBOL_FEET, new UnitConverterLinear(static::COEFFICIENT_FEET)); } /** * Returns the yards unit of length. * * @return UnitLength The yards unit of length. */ public static function yards(): UnitLength { return new static(static::SYMBOL_YARDS, new UnitConverterLinear(static::COEFFICIENT_YARDS)); } /** * Returns the miles unit of length. * * @return UnitLength The miles unit of length. */ public static function miles(): UnitLength { return new static(static::SYMBOL_MILES, new UnitConverterLinear(static::COEFFICIENT_MILES)); } /** * Returns the lightyears unit of length. * * @return UnitLength The lightyears unit of length. */ public static function lightyears(): UnitLength { return new static(static::SYMBOL_LIGHTYEARS, new UnitConverterLinear(static::COEFFICIENT_LIGHTYEARS)); } /** * Returns the nautical miles unit of length. * * @return UnitLength The nautical miles unit of length. */ public static function nauticalMiles(): UnitLength { return new static(static::SYMBOL_NAUTICAL_MILES, new UnitConverterLinear(static::COEFFICIENT_NAUTICAL_MILES)); } /** * Returns the fathoms unit of length. * * @return UnitLength The fathoms unit of length. */ public static function fathoms(): UnitLength { return new static(static::SYMBOL_FATHOMS, new UnitConverterLinear(static::COEFFICIENT_FATHOMS)); } /** * Returns the furlongs unit of length. * * @return UnitLength The furlongs unit of length. */ public static function furlongs(): UnitLength { return new static(static::SYMBOL_FURLONGS, new UnitConverterLinear(static::COEFFICIENT_FURLONGS)); } /** * Returns the astronomical units unit of length. * * @return UnitLength The astronomical units unit of length. */ public static function astronomicalUnits(): UnitLength { return new static(static::SYMBOL_ASTRONOMIC_UNITS, new UnitConverterLinear(static::COEFFICIENT_ASTRONOMIC_UNITS)); } /** * Returns the parsecs unit of length. * * @return UnitLength The parsecs unit of length. */ public static function parsecs(): UnitLength { return new static(static::SYMBOL_PARSECS, new UnitConverterLinear(static::COEFFICIENT_PARSECS)); } } <file_sep>/tests/Units/UnitAreaTests.php <?php namespace Tests\Units; use PHPUnit\Framework\TestCase; use Measurements\Measurement; use Measurements\Units\UnitArea; class UnitAreaTests extends TestCase { use InteractsWithUnits; /** @test */ public function it_defines_square_meters_as_base_unit() { $this->assertTrue(UnitArea::baseUnit() == UnitArea::squareMeters(), "Area should define square meters as its base unit."); } /** @test */ public function it_converts_areas() { $base = new Measurement(1, UnitArea::baseUnit()); $this->assertMeasurementEquals($base->convertTo(UnitArea::squareMegameters()), 1.0 / 1E+12, $base, "square megameters"); $this->assertMeasurementEquals($base->convertTo(UnitArea::squareKilometers()), 1.0 / 1E+6, $base, "square kilometers"); $this->assertMeasurementEquals($base->convertTo(UnitArea::squareMeters()), 1.0, $base, "square meters"); $this->assertMeasurementEquals($base->convertTo(UnitArea::squareCentimeters()), 10000, $base, "square centimeters"); $this->assertMeasurementEquals($base->convertTo(UnitArea::squareMillimeters()), 1.0 / 1E-6, $base, "square millimeters"); $this->assertMeasurementEquals($base->convertTo(UnitArea::squareMicrometers()), 1.0 / 1E-12, $base, "square micrometers"); $this->assertMeasurementEquals($base->convertTo(UnitArea::squareNanometers()), 1.0 / 1E-18, $base, "square nanometers"); $this->assertMeasurementEquals($base->convertTo(UnitArea::squareInches()), 1.0 / 0.00064516, $base, "square inches"); $this->assertMeasurementEquals($base->convertTo(UnitArea::squareFeet()), 1.0 / 0.092903, $base, "square feet"); $this->assertMeasurementEquals($base->convertTo(UnitArea::squareYards()), 1.0/ 0.836127, $base, "square yards"); $this->assertMeasurementEquals($base->convertTo(UnitArea::squareMiles()), 1.0 / 2.59E+6, $base, "square miles"); $this->assertMeasurementEquals($base->convertTo(UnitArea::acres()), 1.0 / 4046.86, $base, "acres"); $this->assertMeasurementEquals($base->convertTo(UnitArea::ares()), 0.01, $base, "ares"); $this->assertMeasurementEquals($base->convertTo(UnitArea::hectares()), 0.0001, $base, "hectares"); } }<file_sep>/src/Quantities/Illuminance.php <?php namespace Measurements\Quantities; use Measurements\Unit; use Measurements\Measurement; use Measurements\Units\UnitIlluminance; use Measurements\Exceptions\UnitException; /** * The `Illuminance` class represents a specific quantities of illuminance. * * @method static Illuminance lux(float $value) */ class Illuminance extends Measurement { /** * Initializes a new illuminance measurement with a specified floating-point value and unit. * * @param double $value The measurement value. * @param Unit $unit The unit of measure. * * @throws \Measurements\Exceptions\UnitException */ public function __construct($value, Unit $unit) { if (!$unit instanceof UnitIlluminance) { throw new UnitException("Attempt to create a illuminance measurement from an invalid unit [$unit]!"); } parent::__construct($value, $unit); } } <file_sep>/doc/Measurements-Comparable.md Measurements\Comparable =============== Instances of conforming types can be compared. * Interface name: Comparable * Namespace: Measurements * This is an **interface** * This interface extends: [Measurements\Equatable](Measurements-Equatable.md) Methods ------- ### isGreaterThan boolean Measurements\Comparable::isGreaterThan(mixed $object) Returns a Boolean value that indicates whether the receiver is greater than another given object. * Visibility: **public** #### Arguments * $object **mixed** - &lt;p&gt;The object with which to compare the receiver.&lt;/p&gt; ### isGreaterThanOrEqualTo boolean Measurements\Comparable::isGreaterThanOrEqualTo(mixed $object) Returns a Boolean value that indicates whether the receiver is greater than or equal to another given object. * Visibility: **public** #### Arguments * $object **mixed** - &lt;p&gt;The object with which to compare the receiver.&lt;/p&gt; ### isLessThan boolean Measurements\Comparable::isLessThan(mixed $object) Returns a Boolean value that indicates whether the receiver is less than another given object. * Visibility: **public** #### Arguments * $object **mixed** - &lt;p&gt;The object with which to compare the receiver.&lt;/p&gt; ### isLessThanOrEqualTo boolean Measurements\Comparable::isLessThanOrEqualTo(mixed $object) Returns a Boolean value that indicates whether the receiver is less than or equal to another given object. * Visibility: **public** #### Arguments * $object **mixed** - &lt;p&gt;The object with which to compare the receiver.&lt;/p&gt; ### compareTo mixed Measurements\Comparable::compareTo(mixed $object, callable $comparison) Compares the receiver to another given object. * Visibility: **public** #### Arguments * $object **mixed** - &lt;p&gt;The object with which to compare the receiver.&lt;/p&gt; * $comparison **callable** - &lt;p&gt;The closure used to compare objects.&lt;/p&gt; ### isEqualTo boolean Measurements\Equatable::isEqualTo(mixed $other) Returns a boolean value that indicates whether the receiver is equal to another given object. * Visibility: **public** * This method is defined by [Measurements\Equatable](Measurements-Equatable.md) #### Arguments * $other **mixed** - &lt;p&gt;The object with which to compare the receiver.&lt;/p&gt; <file_sep>/src/Unit.php <?php namespace Measurements; /** * `Unit` is an abstract class that declares a programmatic interface for objects that represent a unit of measure. */ abstract class Unit implements Equatable { /** * The symbolic representation of the unit. * * @var string */ protected $symbol; /** * Initializes a new unit with the specified symbol. * * @param string $symbol The symbolic representation of the unit. */ public function __construct(string $symbol) { $this->symbol = $symbol; } /** * Return the symbolic representation of the unit. * * @return string The symbolic representation of the unit. */ public function symbol() { return $this->symbol; } /** * Returns a boolean value that indicates whether the unit is equal to another given object. * * @param $other mixed The object with which to compare the unit. * * @return bool `true` if both objects are equal, otherwise `false`. */ public function isEqualTo($other) { if (! $other instanceof static) { return false; } return $this == $other; } /** * Converts the unit to its string representation. * * @return string A string that represents the unit. */ public function __toString() { return $this->symbol(); } } <file_sep>/src/Quantities/Duration.php <?php namespace Measurements\Quantities; use Measurements\Unit; use Measurements\Measurement; use Measurements\Units\UnitDuration; use Measurements\Exceptions\UnitException; /** * The `Duration` class represents specific quantities of duration. * * @method static Duration seconds(float $value) * @method static Duration minutes(float $value) * @method static Duration hours(float $value) */ class Duration extends Measurement { /** * Initializes a new duration measurement with a specified floating-point value and unit. * * @param double $value The measurement value. * @param Unit $unit The unit of measure. * * @throws \Measurements\Exceptions\UnitException */ public function __construct($value, Unit $unit) { if (!$unit instanceof UnitDuration) { throw new UnitException("Attempt to create a duration measurement from an invalid unit [$unit]!"); } parent::__construct($value, $unit); } } <file_sep>/tests/Units/UnitSpeedTests.php <?php namespace Tests\Units; use PHPUnit\Framework\TestCase; use Measurements\Measurement; use Measurements\Units\UnitSpeed; class UnitSpeedTests extends TestCase { use InteractsWithUnits; /** @test */ public function it_defines_meters_per_second_as_base_unit() { $this->assertTrue(UnitSpeed::baseUnit() == UnitSpeed::metersPerSecond(), "Speed should define meters per second as its base unit."); } /** @test */ public function it_converts_speeds() { $base = new Measurement(1, UnitSpeed::baseUnit()); $this->assertMeasurementEquals($base->convertTo(UnitSpeed::metersPerSecond()), 1.0, $base, "meters per second"); $this->assertMeasurementEquals($base->convertTo(UnitSpeed::kilometersPerHour()), 1.0 / 0.277778, $base, "kilometers per hour"); $this->assertMeasurementEquals($base->convertTo(UnitSpeed::milesPerHour()), 1.0 / 0.44704, $base, "miles per hour"); $this->assertMeasurementEquals($base->convertTo(UnitSpeed::knots()), 1.0 / 0.514444, $base, "knots"); } }<file_sep>/src/Quantities/ElectricCharge.php <?php namespace Measurements\Quantities; use Measurements\Unit; use Measurements\Measurement; use Measurements\Units\UnitElectricCharge; use Measurements\Exceptions\UnitException; /** * The `ElectricCharge` class represents a specific quantities of electric charge. * * @method static ElectricCharge coulombs(float $value) * @method static ElectricCharge megaampereHours(float $value) * @method static ElectricCharge kiloampereHours(float $value) * @method static ElectricCharge ampereHours(float $value) * @method static ElectricCharge milliampereHours(float $value) * @method static ElectricCharge microampereHours(float $value) */ class ElectricCharge extends Measurement { /** * Initializes a new electric charge measurement with a specified floating-point value and unit. * * @param double $value The measurement value. * @param Unit $unit The unit of measure. * * @throws \Measurements\Exceptions\UnitException */ public function __construct($value, Unit $unit) { if (! $unit instanceof UnitElectricCharge) { throw new UnitException("Attempt to create a electric charge measurement from an invalid unit [$unit]!"); } parent::__construct($value, $unit); } } <file_sep>/src/Units/UnitRadioactivity.php <?php namespace Measurements\Units; use Measurements\Dimension; use Measurements\Converters\UnitConverterLinear; /** * The `UnitRadioactivity` class encapsulates units of measure for radioactivity. * You typically use instances of `UnitRadioactivity` to represent specific quantities of radioactivity using the `Measurement` class. * * Radioactivity is the process by which the nucleus of an atom emits radiation. * The SI unit of measure for radioactivity is the becquerel (Bq), which is defined as the quantity of radioactive material in which one nucleus decays per second (1 Bq = 1 s-1). * Radioactivity is also commonly described in terms of curies (Ci), a unit defined relative to the decay of one gram of the radium-226 isotope (1 Ci = 3.7 × 1010 Bq). * * The base unit of `UnitRadioactivity` is defined as becquerel. */ class UnitRadioactivity extends Dimension { const SYMBOL_BECQUEREL = "Bq"; const SYMBOL_CURIE = "Ci"; const COEFFICIENT_BECQUEREL = 1.0; const COEFFICIENT_CURIE = 3.7E10; /** * Returns the base unit of radioactivity. * * @return UnitRadioactivity The base unit of radioactivity. */ public static function baseUnit() { return static::becquerel(); } /** * Returns the becquerel unit of radioactivity. * * @return UnitRadioactivity The becquerel unit of radioactivity. */ public static function becquerel(): UnitRadioactivity { return new static(static::SYMBOL_BECQUEREL, new UnitConverterLinear(static::COEFFICIENT_BECQUEREL)); } /** * Returns the curie unit of radioactivity. * * @return UnitRadioactivity The curie unit of radioactivity. */ public static function curie(): UnitRadioactivity { return new static(static::SYMBOL_CURIE, new UnitConverterLinear(static::COEFFICIENT_CURIE)); } }<file_sep>/src/Quantities/ConcentrationMass.php <?php namespace Measurements\Quantities; use Measurements\Unit; use Measurements\Measurement; use Measurements\Units\UnitMass; use Measurements\Units\UnitVolume; use Measurements\Exceptions\UnitException; use Measurements\Units\UnitConcentrationMass; /** * The `ConcentrationMass` class represents a specific quantities of concentration. * * @method static ConcentrationMass gramsPerLiter(float $value) * @method static ConcentrationMass milligramsPerDeciliter(float $value) * @method static ConcentrationMass millimolesPerLiterWithGramsPerMole(float $value) */ class ConcentrationMass extends Measurement { /** * Initializes a new concentration of mass measurement with a specified floating-point value and unit. * * @param double $value The measurement value. * @param Unit $unit The unit of measure. * * @throws \Measurements\Exceptions\UnitException */ public function __construct($value, Unit $unit) { if (!$unit instanceof UnitConcentrationMass) { throw new UnitException("Attempt to create a concentration of mass measurement from an invalid unit [$unit]!"); } parent::__construct($value, $unit); } /** * Returns a concentration of mass measurement computed from the specified mass and volume. * * @param Mass $mass A mass. * @param Volume $volume A volume. * * @return \Measurements\Quantities\ConcentrationMass The concentration of mass that corresponds to the given mass and volume. */ public static function fromMassAndVolume(Mass $mass, Volume $volume) { $grams = $mass->convertTo(UnitMass::grams()); $liters = $volume->convertTo(UnitVolume::liters()); $gramsPerLiter = $grams->value() / $liters->value(); return new static($gramsPerLiter, UnitConcentrationMass::gramsPerLiter()); } } <file_sep>/tests/Units/UnitElectricChargeTests.php <?php namespace Tests\Units; use PHPUnit\Framework\TestCase; use Measurements\Measurement; use Measurements\Units\UnitElectricCharge; class UnitElectricChargeTests extends TestCase { use InteractsWithUnits; /** @test */ public function it_defines_coulombs_as_base_unit() { $this->assertTrue(UnitElectricCharge::baseUnit() == UnitElectricCharge::coulombs(), "Electric charge should define coulombs as its base unit."); } /** @test */ public function it_converts_electric_charges() { $base = new Measurement(1, UnitElectricCharge::baseUnit()); $this->assertMeasurementEquals($base->convertTo(UnitElectricCharge::coulombs()), 1.0, $base, "coulombs"); $this->assertMeasurementEquals($base->convertTo(UnitElectricCharge::megaampereHours()), 1.0 / 3.6E+9, $base, "megaampere hours"); $this->assertMeasurementEquals($base->convertTo(UnitElectricCharge::kiloampereHours()), 1.0 / 3.6E+6, $base, "kiloampere hours"); $this->assertMeasurementEquals($base->convertTo(UnitElectricCharge::ampereHours()), 1.0 / 3600.0, $base, "ampere hours"); $this->assertMeasurementEquals($base->convertTo(UnitElectricCharge::milliampereHours()), 1.0 / 3.6, $base, "milliampere hours"); $this->assertMeasurementEquals($base->convertTo(UnitElectricCharge::microampereHours()), 1.0 / 0.0036, $base, "microampere hours"); } }<file_sep>/doc/Measurements-Units-UnitAngle.md Measurements\Units\UnitAngle =============== The `UnitAngle` class encapsulates units of measure for rotation. You typically use instances of `UnitAngle` to represent specific quantities of planar angle using the `Measurement` class. Angle is a quantity of rotation. The SI unit for angle is the radian (rad), which is dimensionless and defined to be the the angle subtended by an arc that is equal in length to the radius of a circle. Angle is also commonly expressed in terms of degrees (°) and revolutions (rev). The base unit of `UnitAngle` is defined as degrees. * Class name: UnitAngle * Namespace: Measurements\Units * Parent class: [Measurements\Dimension](Measurements-Dimension.md) Constants ---------- ### SYMBOL_DEGREES const SYMBOL_DEGREES = "°" ### SYMBOL_ARC_MINUTES const SYMBOL_ARC_MINUTES = "ʹ" ### SYMBOL_ARC_SECONDS const SYMBOL_ARC_SECONDS = "″" ### SYMBOL_RADIANS const SYMBOL_RADIANS = "rad" ### SYMBOL_GRADIANS const SYMBOL_GRADIANS = "grad" ### SYMBOL_REVOLUTIONS const SYMBOL_REVOLUTIONS = "rev" ### COEFFICIENT_DEGREES const COEFFICIENT_DEGREES = 1.0 ### COEFFICIENT_ARC_MINUTES const COEFFICIENT_ARC_MINUTES = 0.016667 ### COEFFICIENT_ARC_SECONDS const COEFFICIENT_ARC_SECONDS = 0.00027778 ### COEFFICIENT_RADIANS const COEFFICIENT_RADIANS = 57.2958 ### COEFFICIENT_GRADIANS const COEFFICIENT_GRADIANS = 0.9 ### COEFFICIENT_REVOLUTIONS const COEFFICIENT_REVOLUTIONS = 6.28319 Properties ---------- ### $converter protected \Measurements\UnitConverter $converter The converter used to represent the unit in terms of the dimension's base unit. * Visibility: **protected** ### $symbol protected string $symbol The symbolic representation of the unit. * Visibility: **protected** Methods ------- ### baseUnit mixed Measurements\BaseUnitConvertible::baseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is **static**. * This method is defined by [Measurements\BaseUnitConvertible](Measurements-BaseUnitConvertible.md) ### degrees \Measurements\Units\UnitAngle Measurements\Units\UnitAngle::degrees() Returns the degrees unit of rotation. * Visibility: **public** * This method is **static**. ### arcMinutes \Measurements\Units\UnitAngle Measurements\Units\UnitAngle::arcMinutes() Returns the arc minutes unit of rotation. * Visibility: **public** * This method is **static**. ### arcSeconds \Measurements\Units\UnitAngle Measurements\Units\UnitAngle::arcSeconds() Returns the arc seconds unit of rotation. * Visibility: **public** * This method is **static**. ### radians \Measurements\Units\UnitAngle Measurements\Units\UnitAngle::radians() Returns the radians unit of rotation. * Visibility: **public** * This method is **static**. ### gradians \Measurements\Units\UnitAngle Measurements\Units\UnitAngle::gradians() Returns the gradians unit of rotation. * Visibility: **public** * This method is **static**. ### revolutions \Measurements\Units\UnitAngle Measurements\Units\UnitAngle::revolutions() Returns the revolutions unit of rotation. * Visibility: **public** * This method is **static**. ### __construct mixed Measurements\Unit::__construct(string $symbol) Initializes a new unit with the specified symbol. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) #### Arguments * $symbol **string** - &lt;p&gt;The symbolic representation of the unit.&lt;/p&gt; ### converter \Measurements\UnitConverter Measurements\Dimension::converter() Returns the unit converter used to represent the unit in terms of the dimension's base unit. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### getBaseUnit mixed Measurements\Dimension::getBaseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### symbol string Measurements\Unit::symbol() Return the symbolic representation of the unit. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) ### isEqualTo boolean Measurements\Equatable::isEqualTo(mixed $other) Returns a boolean value that indicates whether the receiver is equal to another given object. * Visibility: **public** * This method is defined by [Measurements\Equatable](Measurements-Equatable.md) #### Arguments * $other **mixed** - &lt;p&gt;The object with which to compare the receiver.&lt;/p&gt; ### __toString string Measurements\Unit::__toString() Converts the unit to its string representation. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) <file_sep>/src/Quantities/Speed.php <?php namespace Measurements\Quantities; use Measurements\Unit; use Measurements\Measurement; use Measurements\Units\UnitSpeed; use Measurements\Units\UnitLength; use Measurements\Units\UnitDuration; use Measurements\Exceptions\UnitException; /** * The `Speed` class represents a specific quantities of speed. * * @method static Speed metersPerSecond(float $value) * @method static Speed kilometersPerHour(float $value) * @method static Speed milesPerHour(float $value) * @method static Speed knots(float $value) */ class Speed extends Measurement { /** * Initializes a new speed measurement with a specified floating-point value and unit. * * @param double $value The measurement value. * @param Unit $unit The unit of measure. * * @throws \Measurements\Exceptions\UnitException */ public function __construct($value, Unit $unit) { if (!$unit instanceof UnitSpeed) { throw new UnitException("Attempt to create a speed measurement from an invalid unit [$unit]!"); } parent::__construct($value, $unit); } /** * Returns a speed measurement computed from the specified length and duration. * * @param Length $length A length. * @param Duration $duration A duration. * * @return \Measurements\Quantities\Speed The speed that corresponds to the given length and duration. */ public static function fromLengthAndDuration(Length $length, Duration $duration) { $meters = $length->convertTo(UnitLength::meters()); $seconds = $duration->convertTo(UnitDuration::seconds()); $speed = $meters->value() / $seconds->value(); return new static($speed, UnitSpeed::metersPerSecond()); } } <file_sep>/.github/workflows/tests.yml name: Tests on: push: paths-ignore: - '**.md' pull_request: paths-ignore: - '**.md' jobs: build: strategy: matrix: php: [72, 74, 80, 81] runs-on: ubuntu-latest container: srcoder/development-php:php${{ matrix.php }}-fpm steps: - uses: actions/checkout@v2 - name: Validate composer.json and composer.lock run: composer2 validate - name: Install dependencies run: composer2 install --prefer-dist --no-progress --no-suggest - name: Run test suite run: ./vendor/bin/phpunit <file_sep>/src/Units/UnitPressure.php <?php namespace Measurements\Units; use Measurements\Dimension; use Measurements\Converters\UnitConverterLinear; /** * The `UnitPressure` class encapsulates units of measure for pressure. * You typically use instances of `UnitPressure` to represent specific quantities of pressure using the `Measurement` class. * * Pressure is the normal force over a surface. * The SI unit for pressure is the pascal (Pa), which is derived as one newton of force over one square meter (1Pa = 1N / 1m2). * * The base unit of `UnitPressure` is defined as newtons per meter squared (equivalent to Pascals). */ class UnitPressure extends Dimension { const SYMBOL_NEWTONS_PER_METERS_SQUARED = "N/m²"; const SYMBOL_GIGAPASCALS = "GPa"; const SYMBOL_MEGAPASCALS = "MPa"; const SYMBOL_KILOPASCALS = "kPa"; const SYMBOL_HECTOPASCALS = "hPa"; const SYMBOL_PASCALS = "Pa"; const SYMBOL_INCHES_OF_MERCURY = "inHg"; const SYMBOL_BARS = "bar"; const SYMBOL_MILLIBARS = "mbar"; const SYMBOL_MILLIMETERS_OF_MERCURY = "mmHg"; const SYMBOL_POUNDS_PER_SQUARE_INCH = "psi"; const COEFFICIENT_NEWTONS_PER_METERS_SQUARED = 1.0; const COEFFICIENT_GIGAPASCALS = 1E+9; const COEFFICIENT_MEGAPASCALS = 1E+6; const COEFFICIENT_KILOPASCALS = 1000.0; const COEFFICIENT_HECTOPASCALS = 100.0; const COEFFICIENT_PASCALS = 1.0; const COEFFICIENT_INCHES_OF_MERCURY = 3386.39; const COEFFICIENT_BARS = 1E+5; const COEFFICIENT_MILLIBARS = 100.0; const COEFFICIENT_MILLIMETERS_OF_MERCURY = 133.322; const COEFFICIENT_POUNDS_PER_SQUARE_INCH = 6894.76; /** * Returns the base unit of pressure, equal to newtons per meter squared. * * @return UnitPressure The base unit of pressure. */ public static function baseUnit() { return self::newtonsPerMeterSquared(); } /** * Returns the newtons per meter square unit of pressure (equivalent to Pascals). * * @return UnitPressure The newtons per meter square unit of pressure. */ public static function newtonsPerMeterSquared(): UnitPressure { return new static(static::SYMBOL_NEWTONS_PER_METERS_SQUARED, new UnitConverterLinear(static::COEFFICIENT_NEWTONS_PER_METERS_SQUARED)); } /** * Returns the pascals unit of pressure (equivalent to newtons per meter square). * * @return UnitPressure The pascals unit of pressure. */ public static function gigapascals(): UnitPressure { return new static(static::SYMBOL_GIGAPASCALS, new UnitConverterLinear(static::COEFFICIENT_GIGAPASCALS)); } /** * Returns the megapascals unit of pressure (equivalent to newtons per meter square). * * @return UnitPressure The megapascals unit of pressure. */ public static function megapascals(): UnitPressure { return new static(static::SYMBOL_MEGAPASCALS, new UnitConverterLinear(static::COEFFICIENT_MEGAPASCALS)); } /** * Returns the kilopascals unit of pressure. * * @return UnitPressure The kilopascals unit of pressure. */ public static function kilopascals(): UnitPressure { return new static(static::SYMBOL_KILOPASCALS, new UnitConverterLinear(static::COEFFICIENT_KILOPASCALS)); } /** * Returns the hectopascals unit of pressure. * * @return UnitPressure The hectopascals unit of pressure. */ public static function hectopascals(): UnitPressure { return new static(static::SYMBOL_HECTOPASCALS, new UnitConverterLinear(static::COEFFICIENT_HECTOPASCALS)); } /** * Returns the Pascals unit of pressure (equivalent to newtons per meter square). * * @return UnitPressure The Pascals unit of pressure. */ public static function pascals(): UnitPressure { return new static(static::SYMBOL_PASCALS, new UnitConverterLinear(static::COEFFICIENT_PASCALS)); } /** * Returns the inches of mercury unit of pressure. * * @return UnitPressure The inches of mercury unit of pressure. */ public static function inchesOfMercury(): UnitPressure { return new static(static::SYMBOL_INCHES_OF_MERCURY, new UnitConverterLinear(static::COEFFICIENT_INCHES_OF_MERCURY)); } /** * Returns the bars unit of pressure. * * @return UnitPressure The bars unit of pressure. */ public static function bars(): UnitPressure { return new static(static::SYMBOL_BARS, new UnitConverterLinear(static::COEFFICIENT_BARS)); } /** * Returns the millibars unit of pressure. * * @return UnitPressure The millibars unit of pressure. */ public static function millibars(): UnitPressure { return new static(static::SYMBOL_MILLIBARS, new UnitConverterLinear(static::COEFFICIENT_MILLIBARS)); } /** * Returns the millimeters of mercury unit of pressure. * * @return UnitPressure The millimeters of mercury unit of pressure. */ public static function millimetersOfMercury(): UnitPressure { return new static(static::SYMBOL_MILLIMETERS_OF_MERCURY, new UnitConverterLinear(static::COEFFICIENT_MILLIMETERS_OF_MERCURY)); } /** * Returns the pounds per square inch unit of pressure. * * @return UnitPressure The pounds per square inch unit of pressure. */ public static function poundsPerSquareInch(): UnitPressure { return new static(static::SYMBOL_POUNDS_PER_SQUARE_INCH, new UnitConverterLinear(static::COEFFICIENT_POUNDS_PER_SQUARE_INCH)); } } <file_sep>/doc/Measurements-Dimension.md Measurements\Dimension =============== `Dimension` is an abstract subclass of `Unit` that declares a programmatic interface for objects that represent a dimensional unit of measure. * Class name: Dimension * Namespace: Measurements * This is an **abstract** class * Parent class: [Measurements\Unit](Measurements-Unit.md) * This class implements: [Measurements\BaseUnitConvertible](Measurements-BaseUnitConvertible.md) Properties ---------- ### $converter protected \Measurements\UnitConverter $converter The converter used to represent the unit in terms of the dimension's base unit. * Visibility: **protected** ### $symbol protected string $symbol The symbolic representation of the unit. * Visibility: **protected** Methods ------- ### __construct mixed Measurements\Unit::__construct(string $symbol) Initializes a new unit with the specified symbol. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) #### Arguments * $symbol **string** - &lt;p&gt;The symbolic representation of the unit.&lt;/p&gt; ### converter \Measurements\UnitConverter Measurements\Dimension::converter() Returns the unit converter used to represent the unit in terms of the dimension's base unit. * Visibility: **public** ### getBaseUnit mixed Measurements\Dimension::getBaseUnit() Returns the base unit of the dimension. * Visibility: **public** ### symbol string Measurements\Unit::symbol() Return the symbolic representation of the unit. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) ### isEqualTo boolean Measurements\Equatable::isEqualTo(mixed $other) Returns a boolean value that indicates whether the receiver is equal to another given object. * Visibility: **public** * This method is defined by [Measurements\Equatable](Measurements-Equatable.md) #### Arguments * $other **mixed** - &lt;p&gt;The object with which to compare the receiver.&lt;/p&gt; ### __toString string Measurements\Unit::__toString() Converts the unit to its string representation. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) ### baseUnit mixed Measurements\BaseUnitConvertible::baseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is **static**. * This method is defined by [Measurements\BaseUnitConvertible](Measurements-BaseUnitConvertible.md) <file_sep>/tests/OperationTests.php <?php namespace Tests; use PHPUnit\Framework\TestCase; use Measurements\Measurement; use Measurements\Units\UnitLength; class OperationTests extends TestCase { /** @test */ public function it_adds_measurements() { $first = new Measurement(42, UnitLength::meters()); $second = new Measurement(8, UnitLength::meters()); $sum = $first->add($second); $this->assertTrue($sum->value() == 50, "42 m + 8 m should be equal to 50 m"); $this->assertTrue($sum->unit()->isEqualTo($first->unit()), "Resulting measurement should have the same unit as the initial one after addtion."); } /** @test */ public function it_adds_measurements_by_value() { $measurement = new Measurement(42, UnitLength::meters()); $sum = $measurement->addValue(8); $this->assertTrue($sum->value() == 50, "42 m + 8 should be equal to 50 m"); } /** @test */ public function it_adds_measurements_with_different_units() { $decimeters = new Measurement(42, UnitLength::decimeters()); $centimeters = new Measurement(80, UnitLength::centimeters()); $sum = $decimeters->add($centimeters); $this->assertTrue($sum->value() == 5, "42 dm + 8 cm should be equal to 5 m"); $this->assertTrue($sum->unit()->isEqualTo($decimeters->unit()->getBaseUnit()), "Adding measurements with different units should result in a measurement with a base unit."); } /** @test */ public function it_subtracts_measurements() { $first = new Measurement(42, UnitLength::meters()); $second = new Measurement(8, UnitLength::meters()); $subtraction = $first->subtract($second); $this->assertTrue($subtraction->value() == 34, "42 m - 8 m should be equal to 34 m"); $this->assertTrue($subtraction->unit()->isEqualTo($first->unit()), "Resulting measurement should have the same unit as the initial one after subtraction."); } /** @test */ public function it_subtracts_measurements_by_value() { $measurement = new Measurement(42, UnitLength::meters()); $subtraction = $measurement->subtractValue(8); $this->assertTrue($subtraction->value() == 34, "42 m - 8 should be equal to 34 m"); } /** @test */ public function it_subtracts_measurements_with_different_units() { $decimeters = new Measurement(42, UnitLength::decimeters()); $centimeters = new Measurement(20, UnitLength::centimeters()); $subtraction = $decimeters->subtract($centimeters); $this->assertTrue($subtraction->value() == 4, "42 dm - 20 cm should be equal to 4 m"); $this->assertTrue($subtraction->unit()->isEqualTo($decimeters->unit()->getBaseUnit()), "Subtracting measurements with different units should result in a measurement with a base unit."); } /** @test */ public function it_multiplies_measurements() { $first = new Measurement(4, UnitLength::meters()); $second = new Measurement(2, UnitLength::meters()); $multiplication = $first->multiplyBy($second); $this->assertTrue($multiplication->value() == 8, "4 m * 2 m should be equal to 8 m"); $this->assertTrue($multiplication->unit()->isEqualTo($first->unit()), "Resulting measurement should have the same unit as the initial one after multiplication."); } /** @test */ public function it_multiplies_measurements_by_value() { $measurement = new Measurement(4, UnitLength::meters()); $multiplication = $measurement->multiplyByValue(2); $this->assertTrue($multiplication->value() == 8, "4 m * 2 should be equal to 8 m"); } /** @test */ public function it_multiplies_measurements_with_different_units() { $decimeters = new Measurement(40, UnitLength::decimeters()); $centimeters = new Measurement(200, UnitLength::centimeters()); $multiplication = $decimeters->multiplyBy($centimeters); $this->assertTrue($multiplication->value() == 8, "40 dm - 200 cm should be equal to 8 m"); $this->assertTrue($multiplication->unit()->isEqualTo($decimeters->unit()->getBaseUnit()), "Multiplying measurements with different units should result in a measurement with a base unit."); } /** @test */ public function it_divides_measurements() { $first = new Measurement(4, UnitLength::meters()); $second = new Measurement(2, UnitLength::meters()); $division = $first->divideBy($second); $this->assertTrue($division->value() == 2, "4 m / 2 m should be equal to 2 m"); $this->assertTrue($division->unit()->isEqualTo($first->unit()), "Resulting measurement should have the same unit as the initial one after division."); } /** @test */ public function it_divides_measurements_by_value() { $measurement = new Measurement(4, UnitLength::meters()); $division = $measurement->divideByValue(2); $this->assertTrue($division->value() == 2, "4 m / 2 should be equal to 2 m"); } /** @test */ public function it_divides_measurements_with_different_units() { $decimeters = new Measurement(40, UnitLength::decimeters()); $centimeters = new Measurement(200, UnitLength::centimeters()); $division = $decimeters->divideBy($centimeters); $this->assertTrue($division->value() == 2, "40 dm / 200 cm should be equal to 2 m"); $this->assertTrue($division->unit()->isEqualTo($decimeters->unit()->getBaseUnit()), "Dividing measurements with different units should result in a measurement with a base unit."); } }<file_sep>/src/Quantities/Area.php <?php namespace Measurements\Quantities; use Measurements\Unit; use Measurements\Measurement; use Measurements\Units\UnitArea; use Measurements\Units\UnitLength; use Measurements\Exceptions\UnitException; /** * The `Area` class represents a specific quantities of area. * * @method static Area squareMegameters(float $value) * @method static Area squareKilometers(float $value) * @method static Area squareMeters(float $value) * @method static Area squareCentimeters(float $value) * @method static Area squareMillimeters(float $value) * @method static Area squareMicrometers(float $value) * @method static Area squareNanometers(float $value) * @method static Area squareInches(float $value) * @method static Area squareFeet(float $value) * @method static Area squareYards(float $value) * @method static Area squareMiles(float $value) * @method static Area acres(float $value) * @method static Area ares(float $value) * @method static Area hectares(float $value) */ class Area extends Measurement { /** * Initializes a new speed with a specified floating-point value and unit. * * @param double $value The measurement value. * @param Unit $unit The unit of measure. * * @throws \Measurements\Exceptions\UnitException */ public function __construct($value, Unit $unit) { if (!$unit instanceof UnitArea) { throw new UnitException("Attempt to create an area measurement from an invalid unit [$unit]!"); } parent::__construct($value, $unit); } /** * Returns the area measurement computed from the specified length. * * @param Length $length A length. * * @return \Measurements\Quantities\Area The area that corresponds to the given length. */ public static function fromEquivalentLengths(Length $length) { return static::fromLengthAndWidth($length, $length); } /** * Returns the area measurement computed from the specified length and width. * * @param Length $length A length. * @param Length $width A width. * * @return \Measurements\Quantities\Area The area that corresponds to the given length and width. */ public static function fromLengthAndWidth(Length $length, Length $width) { $length = $length->convertTo(UnitLength::meters()); $width = $width->convertTo(UnitLength::meters()); $area = $length->value() * $width->value(); return new static($area, UnitArea::squareMeters()); } } <file_sep>/tests/Units/UnitVolumeTests.php <?php namespace Tests\Units; use PHPUnit\Framework\TestCase; use Measurements\Measurement; use Measurements\Units\UnitVolume; class UnitVolumeTests extends TestCase { use InteractsWithUnits; /** @test */ public function it_defines_liters_as_base_unit() { $this->assertTrue(UnitVolume::baseUnit() == UnitVolume::liters(), "Volume should define liters as its base unit."); } /** @test */ public function it_converts_volumes() { $base = new Measurement(1, UnitVolume::baseUnit()); $this->assertMeasurementEquals($base->convertTo(UnitVolume::megaliters()), 1.0 / 1000000.0, $base, "megaliters"); $this->assertMeasurementEquals($base->convertTo(UnitVolume::kiloliters()), 1.0 / 1000.0, $base, "kiloliters"); $this->assertMeasurementEquals($base->convertTo(UnitVolume::liters()), 1.0, $base, "liters"); $this->assertMeasurementEquals($base->convertTo(UnitVolume::deciliters()), 1.0 / 0.1, $base, "deciliters"); $this->assertMeasurementEquals($base->convertTo(UnitVolume::centiliters()), 1.0 / 0.01, $base, "centiliters"); $this->assertMeasurementEquals($base->convertTo(UnitVolume::milliliters()), 1.0 / 0.001, $base, "milliliters"); $this->assertMeasurementEquals($base->convertTo(UnitVolume::cubicKilometers()), 1E-12, $base, "cubic kilometers"); $this->assertMeasurementEquals($base->convertTo(UnitVolume::cubicMeters()), 1.0 / 1000.0, $base, "cubic meters"); $this->assertMeasurementEquals($base->convertTo(UnitVolume::cubicDecimeters()), 1.0, $base, "cubic decimeters"); $this->assertMeasurementEquals($base->convertTo(UnitVolume::cubicMillimeters()), 1000, $base, "cubic millimeters"); $this->assertMeasurementEquals($base->convertTo(UnitVolume::cubicInches()), 1.0 / 0.0163871, $base, "cubic inches"); $this->assertMeasurementEquals($base->convertTo(UnitVolume::cubicFeet()), 1.0 / 28.3168, $base, "cubic feet"); $this->assertMeasurementEquals($base->convertTo(UnitVolume::cubicYards()), 1.0 / 764.555, $base, "cubic yards"); $this->assertMeasurementEquals($base->convertTo(UnitVolume::cubicMiles()), 1.0 / 4.168E+12, $base, "cubic miles"); $this->assertMeasurementEquals($base->convertTo(UnitVolume::acreFeet()), 1.0 / 1.233E+6, $base, "acre feet"); $this->assertMeasurementEquals($base->convertTo(UnitVolume::bushels()), 1.0 / 35.2391, $base, "bushels"); $this->assertMeasurementEquals($base->convertTo(UnitVolume::teaspoons()), 1.0 / 0.00492892, $base, "teaspoons"); $this->assertMeasurementEquals($base->convertTo(UnitVolume::tablespoons()), 1.0 / 0.0147868, $base, "tablespoons"); $this->assertMeasurementEquals($base->convertTo(UnitVolume::fluidOunces()), 1.0 / 0.0295735, $base, "fluid ounces"); $this->assertMeasurementEquals($base->convertTo(UnitVolume::cups()), 1.0 / 0.24, $base, "cups"); $this->assertMeasurementEquals($base->convertTo(UnitVolume::pints()), 1.0 / 0.473176, $base, "pints"); $this->assertMeasurementEquals($base->convertTo(UnitVolume::quarts()), 1.0 / 0.946353, $base, "quarts"); $this->assertMeasurementEquals($base->convertTo(UnitVolume::gallons()), 1.0 / 3.78541, $base, "gallons"); $this->assertMeasurementEquals($base->convertTo(UnitVolume::imperialTeaspoons()), 1.0 / 0.00591939, $base, "imperial teaspoons"); $this->assertMeasurementEquals($base->convertTo(UnitVolume::imperialTablespoons()), 1.0 / 0.0177582, $base, "imperial tablespoons"); $this->assertMeasurementEquals($base->convertTo(UnitVolume::imperialFluidOunces()), 1.0 / 0.0284131, $base, "imperial fluid ounces"); $this->assertMeasurementEquals($base->convertTo(UnitVolume::imperialPints()), 1.0 / 0.568261, $base, "imperial pints"); $this->assertMeasurementEquals($base->convertTo(UnitVolume::imperialQuarts()), 1.0 / 1.13652, $base, "imperial quarts"); $this->assertMeasurementEquals($base->convertTo(UnitVolume::imperialGallons()), 1.0 / 4.54609, $base, "imperial gallons"); $this->assertMeasurementEquals($base->convertTo(UnitVolume::metricCups()), 4, $base, "metric"); } }<file_sep>/src/Units/UnitIlluminance.php <?php namespace Measurements\Units; use Measurements\Dimension; use Measurements\Converters\UnitConverterLinear; /** * The `UnitIlluminance` class encapsulates units of measure for illuminance. * You typically use instances of `UnitIlluminance` to represent specific quantities of illuminance using the `Measurement` class. * * Illuminance is the luminous flux incident on a surface. * The SI unit for illuminance is the lux (lx), which is derived as one lumen per square meter (1lm / 1m2). * * The base unit of `UnitIlluminance` is defined as lux. */ class UnitIlluminance extends Dimension { const SYMBOL_LUX = "lx"; const COEFFICIENT_LUX = 1.0; /** * Returns the base unit of illuminance. * * @return UnitIlluminance The base unit of illuminance. */ public static function baseUnit() { return self::lux(); } /** * Returns the lux unit of illuminance. * * @return UnitIlluminance The lux unit of illuminance. */ public static function lux(): UnitIlluminance { return new static(static::SYMBOL_LUX, new UnitConverterLinear(static::COEFFICIENT_LUX)); } } <file_sep>/tests/Units/UnitTemperatureTests.php <?php namespace Tests\Units; use PHPUnit\Framework\TestCase; use Measurements\Measurement; use Measurements\Units\UnitTemperature; class UnitTemperatureTests extends TestCase { use InteractsWithUnits; /** @test */ public function it_defines_kelvin_as_base_unit() { $this->assertTrue(UnitTemperature::baseUnit() == UnitTemperature::kelvin(), "Temperature should define kelvin as its base unit."); } /** @test */ public function it_converts_temperatures() { $base = new Measurement(1, UnitTemperature::baseUnit()); $this->assertMeasurementEquals($base->convertTo(UnitTemperature::kelvin()), 1.0, $base, "kelvin"); $this->assertMeasurementEquals($base->convertTo(UnitTemperature::celsius()), -272.15, $base, "degree Celsius"); $this->assertMeasurementEquals($base->convertTo(UnitTemperature::fahrenheit()), -457.87, $base, "degree Fahrenheit"); } }<file_sep>/src/Units/UnitEnergy.php <?php namespace Measurements\Units; use Measurements\Dimension; use Measurements\Converters\UnitConverterLinear; /** * The `UnitEnergy` class encapsulates units of measure for energy. * You typically use instances of `UnitEnergy` to represent specific quantities of energy using the `Measurement` class. * * Energy is a fundamental property of matter than can be transferred and converted into different forms, such as kinetic, electric, and thermal. * The SI unit for energy is the joule (J), which is derived as the work of one meter of displacement in the direction of a force of one newton (1J = 1N ∙ 1m). * It can also be derived as the work required to displace an electric charge of one coulomb through an electrical potential difference of one volt (1J = 1C ∙ 1V), or the work required to produce one watt of power for one second (1J = 1W ∙ 1s). Energy is also commonly expressed in terms of the calorie (cal), or the energy needed to raise the temperature of one gram of water by one degree Celsius at a pressure of one atmosphere (1cal ≡ 4.184J). * * The base unit of `UnitEnergy` is defined as joules. */ class UnitEnergy extends Dimension { const SYMBOL_KILOJOULES = "KJ"; const SYMBOL_JOULES = "J"; const SYMBOL_KILOCALORIES = "kCal"; const SYMBOL_CALORIES = "cal"; const SYMBOL_KILOWATT_HOURS = "kWh"; const COEFFICIENT_KILOJOULES = 1000.0; const COEFFICIENT_JOULES = 1.0; const COEFFICIENT_KILOCALORIES = 4184.0; const COEFFICIENT_CALORIES = 4.184; const COEFFICIENT_KILOWATT_HOURS = 3600000.0; /** * Returns the base unit of energy. * * @return UnitEnergy The base unit of energy. */ public static function baseUnit() { return self::joules(); } /** * Returns the kilojoules unit of energy. * * @return UnitEnergy The kilojoules unit of energy. */ public static function kilojoules(): UnitEnergy { return new static(static::SYMBOL_KILOJOULES, new UnitConverterLinear(static::COEFFICIENT_KILOJOULES)); } /** * Returns the joules unit of energy. * * @return UnitEnergy The joules unit of energy. */ public static function joules(): UnitEnergy { return new static(static::SYMBOL_JOULES, new UnitConverterLinear(static::COEFFICIENT_JOULES)); } /** * Returns the kilocalories unit of energy. * * @return UnitEnergy The kilocalories unit of energy. */ public static function kilocalories(): UnitEnergy { return new static(static::SYMBOL_KILOCALORIES, new UnitConverterLinear(static::COEFFICIENT_KILOCALORIES)); } /** * Returns the calories unit of energy. * * @return UnitEnergy The calories unit of energy. */ public static function calories(): UnitEnergy { return new static(static::SYMBOL_CALORIES, new UnitConverterLinear(static::COEFFICIENT_CALORIES)); } /** * Returns the kilowatt hours unit of energy. * * @return UnitEnergy The kilowatt hours unit of energy. */ public static function kilowattHours(): UnitEnergy { return new static(static::SYMBOL_KILOWATT_HOURS, new UnitConverterLinear(static::COEFFICIENT_KILOWATT_HOURS)); } } <file_sep>/doc/Measurements-Units-UnitElectricCurrent.md Measurements\Units\UnitElectricCurrent =============== The `UnitElectricCurrent` class encapsulates units of measure for electric current. You typically use instances of `UnitElectricCurrent` to represent specific quantities of electric current using the `Measurement` class. Electric current is the flow of electric current. The SI unit for electric current is the ampere (A), which is defined in terms the production of electromagnetic force between two parallel linear conductors. It can also be expressed as the flow of one coulomb per second (1A = 1C / s). The base unit of `UnitElectricCurrent` is defined as amperes. * Class name: UnitElectricCurrent * Namespace: Measurements\Units * Parent class: [Measurements\Dimension](Measurements-Dimension.md) Constants ---------- ### SYMBOL_MEGAAMPERES const SYMBOL_MEGAAMPERES = "MA" ### SYMBOL_KILOAMPERES const SYMBOL_KILOAMPERES = "kA" ### SYMBOL_AMPERES const SYMBOL_AMPERES = "A" ### SYMBOL_MILLIAMPERES const SYMBOL_MILLIAMPERES = "mA" ### SYMBOL_MICROAMPERES const SYMBOL_MICROAMPERES = "µA" ### COEFFICIENT_MEGAAMPERES const COEFFICIENT_MEGAAMPERES = 1000000.0 ### COEFFICIENT_KILOAMPERES const COEFFICIENT_KILOAMPERES = 1000.0 ### COEFFICIENT_AMPERES const COEFFICIENT_AMPERES = 1.0 ### COEFFICIENT_MILLIAMPERES const COEFFICIENT_MILLIAMPERES = 0.001 ### COEFFICIENT_MICROAMPERES const COEFFICIENT_MICROAMPERES = 1.0E-6 Properties ---------- ### $converter protected \Measurements\UnitConverter $converter The converter used to represent the unit in terms of the dimension's base unit. * Visibility: **protected** ### $symbol protected string $symbol The symbolic representation of the unit. * Visibility: **protected** Methods ------- ### baseUnit mixed Measurements\BaseUnitConvertible::baseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is **static**. * This method is defined by [Measurements\BaseUnitConvertible](Measurements-BaseUnitConvertible.md) ### megaamperes \Measurements\Units\UnitElectricCurrent Measurements\Units\UnitElectricCurrent::megaamperes() Returns the megaamperes unit of electric current. * Visibility: **public** * This method is **static**. ### kiloamperes \Measurements\Units\UnitElectricCurrent Measurements\Units\UnitElectricCurrent::kiloamperes() Returns the kiloamperes unit of electric current. * Visibility: **public** * This method is **static**. ### amperes \Measurements\Units\UnitElectricCurrent Measurements\Units\UnitElectricCurrent::amperes() Returns the amperes unit of electric current. * Visibility: **public** * This method is **static**. ### milliamperes \Measurements\Units\UnitElectricCurrent Measurements\Units\UnitElectricCurrent::milliamperes() Returns the milliamperes unit of electric current. * Visibility: **public** * This method is **static**. ### microamperes \Measurements\Units\UnitElectricCurrent Measurements\Units\UnitElectricCurrent::microamperes() Returns the microamperes unit of electric current. * Visibility: **public** * This method is **static**. ### __construct mixed Measurements\Unit::__construct(string $symbol) Initializes a new unit with the specified symbol. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) #### Arguments * $symbol **string** - &lt;p&gt;The symbolic representation of the unit.&lt;/p&gt; ### converter \Measurements\UnitConverter Measurements\Dimension::converter() Returns the unit converter used to represent the unit in terms of the dimension's base unit. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### getBaseUnit mixed Measurements\Dimension::getBaseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### symbol string Measurements\Unit::symbol() Return the symbolic representation of the unit. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) ### isEqualTo boolean Measurements\Equatable::isEqualTo(mixed $other) Returns a boolean value that indicates whether the receiver is equal to another given object. * Visibility: **public** * This method is defined by [Measurements\Equatable](Measurements-Equatable.md) #### Arguments * $other **mixed** - &lt;p&gt;The object with which to compare the receiver.&lt;/p&gt; ### __toString string Measurements\Unit::__toString() Converts the unit to its string representation. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) <file_sep>/tests/Units/UnitLengthTests.php <?php namespace Tests\Units; use PHPUnit\Framework\TestCase; use Measurements\Measurement; use Measurements\Units\UnitLength; class UnitLengthTests extends TestCase { use InteractsWithUnits; /** @test */ public function it_defines_meters_as_base_unit() { $this->assertTrue(UnitLength::baseUnit() == UnitLength::meters(), "Length should define meters as its base unit."); } /** @test */ public function it_converts_lengths() { $base = new Measurement(1, UnitLength::baseUnit()); $this->assertMeasurementEquals($base->convertTo(UnitLength::megameters()), 1E-6, $base, "megameters"); $this->assertMeasurementEquals($base->convertTo(UnitLength::kilometers()), 0.001, $base, "kilometers"); $this->assertMeasurementEquals($base->convertTo(UnitLength::hectometers()), 0.01, $base, "hectometers"); $this->assertMeasurementEquals($base->convertTo(UnitLength::decameters()), 0.1, $base, "decameters"); $this->assertMeasurementEquals($base->convertTo(UnitLength::meters()), 1, $base, "meters"); $this->assertMeasurementEquals($base->convertTo(UnitLength::decimeters()), 10, $base, "decimeters"); $this->assertMeasurementEquals($base->convertTo(UnitLength::centimeters()), 100, $base, "centimeters"); $this->assertMeasurementEquals($base->convertTo(UnitLength::millimeters()), 1000, $base, "millimeters"); $this->assertMeasurementEquals($base->convertTo(UnitLength::micrometers()), 1E+6, $base, "micrometers"); $this->assertMeasurementEquals($base->convertTo(UnitLength::nanometers()), 1.0 / 1E-9, $base, "nanometers"); $this->assertMeasurementEquals($base->convertTo(UnitLength::picometers()), 1E+12, $base, "picometers"); $this->assertMeasurementEquals($base->convertTo(UnitLength::inches()), 1.0 / 0.0254, $base, "inches"); $this->assertMeasurementEquals($base->convertTo(UnitLength::feet()), 1.0 / 0.3048, $base, "feet"); $this->assertMeasurementEquals($base->convertTo(UnitLength::yards()), 1.0 / 0.9144, $base, "yards"); $this->assertMeasurementEquals($base->convertTo(UnitLength::miles()), 1.0 / 1609.34, $base, "miles"); $this->assertMeasurementEquals($base->convertTo(UnitLength::lightyears()), 1.0 / 9.461E+15, $base, "lightyears"); $this->assertMeasurementEquals($base->convertTo(UnitLength::nauticalMiles()), 1.0 / 1852.0, $base, "nautical miles"); $this->assertMeasurementEquals($base->convertTo(UnitLength::fathoms()), 1.0 / 1.8288, $base, "fathoms"); $this->assertMeasurementEquals($base->convertTo(UnitLength::furlongs()), 1.0 / 201.168, $base, "furlongs"); $this->assertMeasurementEquals($base->convertTo(UnitLength::astronomicalUnits()), 1.0 / 1.496E+11, $base, "astronomical units"); $this->assertMeasurementEquals($base->convertTo(UnitLength::parsecs()), 1.0 / 3.086E+16, $base, "parsecs"); } }<file_sep>/doc/Measurements-Units-UnitVolume.md Measurements\Units\UnitVolume =============== The `UnitVolume` class encapsulates units of measure for volume. You typically use instances of `UnitVolume` to represent specific quantities of volume using the `Measurement` class. Volume is a quantity of the extend of matter in three dimensions. The SI accepted unit of volume is the liter (L), which is derived as one cubic decimeter (1 dm3). Volume is also commonly expressed in terms of cubic meters (m3), gallons (gal), and cups (cup). The base unit of `UnitVolume` is defined as liters. * Class name: UnitVolume * Namespace: Measurements\Units * Parent class: [Measurements\Dimension](Measurements-Dimension.md) Constants ---------- ### SYMBOL_MEGALITERS const SYMBOL_MEGALITERS = "ML" ### SYMBOL_KILOLITERS const SYMBOL_KILOLITERS = "kL" ### SYMBOL_LITERS const SYMBOL_LITERS = "L" ### SYMBOL_DECILITERS const SYMBOL_DECILITERS = "dL" ### SYMBOL_CENTILITERS const SYMBOL_CENTILITERS = "cL" ### SYMBOL_MILLILITERS const SYMBOL_MILLILITERS = "mL" ### SYMBOL_CUBIC_KILOMETERS const SYMBOL_CUBIC_KILOMETERS = "km³" ### SYMBOL_CUBIC_METERS const SYMBOL_CUBIC_METERS = "m³" ### SYMBOL_CUBIC_DECIMETERS const SYMBOL_CUBIC_DECIMETERS = "dm³" ### SYMBOL_CUBIC_CENTIMETERS const SYMBOL_CUBIC_CENTIMETERS = "cm³" ### SYMBOL_CUBIC_MILLIMETERS const SYMBOL_CUBIC_MILLIMETERS = "mm³" ### SYMBOL_CUBIC_INCHES const SYMBOL_CUBIC_INCHES = "in³" ### SYMBOL_CUBIC_FEET const SYMBOL_CUBIC_FEET = "ft³" ### SYMBOL_CUBIC_YARDS const SYMBOL_CUBIC_YARDS = "yd³" ### SYMBOL_CUBIC_MILES const SYMBOL_CUBIC_MILES = "mi³" ### SYMBOL_ACRE_FEET const SYMBOL_ACRE_FEET = "af" ### SYMBOL_BUSHELS const SYMBOL_BUSHELS = "bsh" ### SYMBOL_TEASPOONS const SYMBOL_TEASPOONS = "tsp" ### SYMBOL_TABLESPOONS const SYMBOL_TABLESPOONS = "tbsp" ### SYMBOL_FLUID_OUNCES const SYMBOL_FLUID_OUNCES = "fl oz" ### SYMBOL_CUPS const SYMBOL_CUPS = "cup" ### SYMBOL_PINTS const SYMBOL_PINTS = "pt" ### SYMBOL_QUARTS const SYMBOL_QUARTS = "qt" ### SYMBOL_GALLONS const SYMBOL_GALLONS = "gal" ### SYMBOL_IMPERIAL_TEASPOONS const SYMBOL_IMPERIAL_TEASPOONS = "tsp Imperial" ### SYMBOL_IMPERIAL_TABLESPOONS const SYMBOL_IMPERIAL_TABLESPOONS = "tbsp Imperial" ### SYMBOL_IMPERIAL_FLUID_OUNCES const SYMBOL_IMPERIAL_FLUID_OUNCES = "fl oz Imperial" ### SYMBOL_IMPERIAL_PINTS const SYMBOL_IMPERIAL_PINTS = "pt Imperial" ### SYMBOL_IMPERIAL_QUARTS const SYMBOL_IMPERIAL_QUARTS = "qt Imperial" ### SYMBOL_IMPERIAL_GALLONS const SYMBOL_IMPERIAL_GALLONS = "gal Imperial" ### SYMBOL_METRIC_CUPS const SYMBOL_METRIC_CUPS = "metric cup Imperial" ### COEFFICIENT_MEGALITERS const COEFFICIENT_MEGALITERS = 1000000.0 ### COEFFICIENT_KILOLITERS const COEFFICIENT_KILOLITERS = 1000.0 ### COEFFICIENT_LITERS const COEFFICIENT_LITERS = 1.0 ### COEFFICIENT_DECILITERS const COEFFICIENT_DECILITERS = 0.1 ### COEFFICIENT_CENTILITERS const COEFFICIENT_CENTILITERS = 0.01 ### COEFFICIENT_MILLILITERS const COEFFICIENT_MILLILITERS = 0.001 ### COEFFICIENT_CUBIC_KILOMETERS const COEFFICIENT_CUBIC_KILOMETERS = 1000000000000.0 ### COEFFICIENT_CUBIC_METERS const COEFFICIENT_CUBIC_METERS = 1000.0 ### COEFFICIENT_CUBIC_DECIMETERS const COEFFICIENT_CUBIC_DECIMETERS = 1.0 ### COEFFICIENT_CUBIC_CENTIMETERS const COEFFICIENT_CUBIC_CENTIMETERS = 0.01 ### COEFFICIENT_CUBIC_MILLIMETERS const COEFFICIENT_CUBIC_MILLIMETERS = 0.001 ### COEFFICIENT_CUBIC_INCHES const COEFFICIENT_CUBIC_INCHES = 0.0163871 ### COEFFICIENT_CUBIC_FEET const COEFFICIENT_CUBIC_FEET = 28.3168 ### COEFFICIENT_CUBIC_YARDS const COEFFICIENT_CUBIC_YARDS = 764.5549999999999 ### COEFFICIENT_CUBIC_MILES const COEFFICIENT_CUBIC_MILES = 4168000000000.0 ### COEFFICIENT_ACRE_FEET const COEFFICIENT_ACRE_FEET = 1233000.0 ### COEFFICIENT_BUSHELS const COEFFICIENT_BUSHELS = 35.2391 ### COEFFICIENT_TEASPOONS const COEFFICIENT_TEASPOONS = 0.00492892 ### COEFFICIENT_TABLESPOONS const COEFFICIENT_TABLESPOONS = 0.0147868 ### COEFFICIENT_FLUID_OUNCES const COEFFICIENT_FLUID_OUNCES = 0.0295735 ### COEFFICIENT_CUPS const COEFFICIENT_CUPS = 0.24 ### COEFFICIENT_PINTS const COEFFICIENT_PINTS = 0.473176 ### COEFFICIENT_QUARTS const COEFFICIENT_QUARTS = 0.946353 ### COEFFICIENT_GALLONS const COEFFICIENT_GALLONS = 3.78541 ### COEFFICIENT_IMPERIAL_TEASPOONS const COEFFICIENT_IMPERIAL_TEASPOONS = 0.00591939 ### COEFFICIENT_IMPERIAL_TABLESPOONS const COEFFICIENT_IMPERIAL_TABLESPOONS = 0.0177582 ### COEFFICIENT_IMPERIAL_FLUID_OUNCES const COEFFICIENT_IMPERIAL_FLUID_OUNCES = 0.0284131 ### COEFFICIENT_IMPERIAL_PINTS const COEFFICIENT_IMPERIAL_PINTS = 0.568261 ### COEFFICIENT_IMPERIAL_QUARTS const COEFFICIENT_IMPERIAL_QUARTS = 1.13652 ### COEFFICIENT_IMPERIAL_GALLONS const COEFFICIENT_IMPERIAL_GALLONS = 4.54609 ### COEFFICIENT_METRIC_CUPS const COEFFICIENT_METRIC_CUPS = 0.25 Properties ---------- ### $converter protected \Measurements\UnitConverter $converter The converter used to represent the unit in terms of the dimension's base unit. * Visibility: **protected** ### $symbol protected string $symbol The symbolic representation of the unit. * Visibility: **protected** Methods ------- ### baseUnit mixed Measurements\BaseUnitConvertible::baseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is **static**. * This method is defined by [Measurements\BaseUnitConvertible](Measurements-BaseUnitConvertible.md) ### megaliters \Measurements\Units\UnitVolume Measurements\Units\UnitVolume::megaliters() Returns the megaliters unit of volume. * Visibility: **public** * This method is **static**. ### kiloliters \Measurements\Units\UnitVolume Measurements\Units\UnitVolume::kiloliters() Returns the kiloliters unit of volume. * Visibility: **public** * This method is **static**. ### liters \Measurements\Units\UnitVolume Measurements\Units\UnitVolume::liters() Returns the liters unit of volume. * Visibility: **public** * This method is **static**. ### deciliters \Measurements\Units\UnitVolume Measurements\Units\UnitVolume::deciliters() Returns the deciliters unit of volume. * Visibility: **public** * This method is **static**. ### centiliters \Measurements\Units\UnitVolume Measurements\Units\UnitVolume::centiliters() Returns the centiliters unit of volume. * Visibility: **public** * This method is **static**. ### milliliters \Measurements\Units\UnitVolume Measurements\Units\UnitVolume::milliliters() Returns the milliliters unit of volume. * Visibility: **public** * This method is **static**. ### cubicKilometers \Measurements\Units\UnitVolume Measurements\Units\UnitVolume::cubicKilometers() Returns the cubic kilometers unit of volume. * Visibility: **public** * This method is **static**. ### cubicMeters \Measurements\Units\UnitVolume Measurements\Units\UnitVolume::cubicMeters() Returns the cubic meters unit of volume. * Visibility: **public** * This method is **static**. ### cubicDecimeters \Measurements\Units\UnitVolume Measurements\Units\UnitVolume::cubicDecimeters() Returns the cubic decimeters unit of volume. * Visibility: **public** * This method is **static**. ### cubicMillimeters \Measurements\Units\UnitVolume Measurements\Units\UnitVolume::cubicMillimeters() Returns the cubic millimeters unit of volume. * Visibility: **public** * This method is **static**. ### cubicInches \Measurements\Units\UnitVolume Measurements\Units\UnitVolume::cubicInches() Returns the cubic inches unit of volume. * Visibility: **public** * This method is **static**. ### cubicFeet \Measurements\Units\UnitVolume Measurements\Units\UnitVolume::cubicFeet() Returns the cubic feet unit of volume. * Visibility: **public** * This method is **static**. ### cubicYards \Measurements\Units\UnitVolume Measurements\Units\UnitVolume::cubicYards() Returns the cubic yards unit of volume. * Visibility: **public** * This method is **static**. ### cubicMiles \Measurements\Units\UnitVolume Measurements\Units\UnitVolume::cubicMiles() Returns the cubic miles unit of volume. * Visibility: **public** * This method is **static**. ### acreFeet \Measurements\Units\UnitVolume Measurements\Units\UnitVolume::acreFeet() Returns the acre feet unit of volume. * Visibility: **public** * This method is **static**. ### bushels \Measurements\Units\UnitVolume Measurements\Units\UnitVolume::bushels() Returns the bushels unit of volume. * Visibility: **public** * This method is **static**. ### teaspoons \Measurements\Units\UnitVolume Measurements\Units\UnitVolume::teaspoons() Returns the tea spoons unit of volume. * Visibility: **public** * This method is **static**. ### tablespoons \Measurements\Units\UnitVolume Measurements\Units\UnitVolume::tablespoons() Returns the table spoons unit of volume. * Visibility: **public** * This method is **static**. ### fluidOunces \Measurements\Units\UnitVolume Measurements\Units\UnitVolume::fluidOunces() Returns the fluid ounces unit of volume. * Visibility: **public** * This method is **static**. ### cups \Measurements\Units\UnitVolume Measurements\Units\UnitVolume::cups() Returns the cups of volume. * Visibility: **public** * This method is **static**. ### pints \Measurements\Units\UnitVolume Measurements\Units\UnitVolume::pints() Returns the pints unit of volume. * Visibility: **public** * This method is **static**. ### quarts \Measurements\Units\UnitVolume Measurements\Units\UnitVolume::quarts() Returns the quarts unit of volume. * Visibility: **public** * This method is **static**. ### gallons \Measurements\Units\UnitVolume Measurements\Units\UnitVolume::gallons() Returns the gallons unit of volume. * Visibility: **public** * This method is **static**. ### imperialTeaspoons \Measurements\Units\UnitVolume Measurements\Units\UnitVolume::imperialTeaspoons() Returns the imperial tea spoons unit of volume. * Visibility: **public** * This method is **static**. ### imperialTablespoons \Measurements\Units\UnitVolume Measurements\Units\UnitVolume::imperialTablespoons() Returns the imperial table spoons unit of volume. * Visibility: **public** * This method is **static**. ### imperialFluidOunces \Measurements\Units\UnitVolume Measurements\Units\UnitVolume::imperialFluidOunces() Returns the imperial fluid ounces unit of volume. * Visibility: **public** * This method is **static**. ### imperialPints \Measurements\Units\UnitVolume Measurements\Units\UnitVolume::imperialPints() Returns the imperial pints unit of volume. * Visibility: **public** * This method is **static**. ### imperialQuarts \Measurements\Units\UnitVolume Measurements\Units\UnitVolume::imperialQuarts() Returns the imperial quarts unit of volume. * Visibility: **public** * This method is **static**. ### imperialGallons \Measurements\Units\UnitVolume Measurements\Units\UnitVolume::imperialGallons() Returns the imperial gallons unit of volume. * Visibility: **public** * This method is **static**. ### metricCups \Measurements\Units\UnitVolume Measurements\Units\UnitVolume::metricCups() Returns the metric cups unit of volume. * Visibility: **public** * This method is **static**. ### __construct mixed Measurements\Unit::__construct(string $symbol) Initializes a new unit with the specified symbol. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) #### Arguments * $symbol **string** - &lt;p&gt;The symbolic representation of the unit.&lt;/p&gt; ### converter \Measurements\UnitConverter Measurements\Dimension::converter() Returns the unit converter used to represent the unit in terms of the dimension's base unit. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### getBaseUnit mixed Measurements\Dimension::getBaseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### symbol string Measurements\Unit::symbol() Return the symbolic representation of the unit. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) ### isEqualTo boolean Measurements\Equatable::isEqualTo(mixed $other) Returns a boolean value that indicates whether the receiver is equal to another given object. * Visibility: **public** * This method is defined by [Measurements\Equatable](Measurements-Equatable.md) #### Arguments * $other **mixed** - &lt;p&gt;The object with which to compare the receiver.&lt;/p&gt; ### __toString string Measurements\Unit::__toString() Converts the unit to its string representation. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) <file_sep>/tests/QuantitiesTests.php <?php namespace Tests; use PHPUnit\Framework\TestCase; use BadMethodCallException; use Measurements\Measurement; use Measurements\Units\UnitLength; use Measurements\Units\UnitDuration; use Measurements\Quantities\Speed; use Measurements\Quantities\Length; use Measurements\Quantities\Duration; use Measurements\Exceptions\UnitException; class QuantitiesTests extends TestCase { /** @test */ public function it_creates_quantities() { $length = new Length(42, UnitLength::meters()); $duration = new Duration(42, UnitDuration::seconds()); $this->assertTrue($length == '42 m', "Length should print <42 m>."); $this->assertTrue($duration == '42 sec', "Length should print <42 sec>."); } /** @test */ public function creating_a_quantity_with_an_invalid_unit_throws_an_exception() { $this->expectException(UnitException::class); $invalid = new Length(42, UnitDuration::hours()); } /** @test */ public function it_creates_quantities_using_short_syntax() { $measurement = new Measurement(42, UnitLength::meters()); $length = new Length(42, UnitLength::meters()); $meters = Length::meters(42); $this->assertNotNull($meters, "It should be possible to create a measurement using the short method."); $this->assertTrue($meters instanceof Length, "A length instance should be of type ".Length::class); $this->assertTrue($meters->isEqualTo($length), "Measurements <$meters> and <$length> should be equals."); $this->assertTrue($meters->isEqualTo($measurement), "Measurements <$meters> and <$measurement> should be equals."); } /** @test */ public function creating_quantities_using_invalid_short_syntax_method_throws_an_exception() { $this->expectException(BadMethodCallException::class); $invalid = Length::hours(42); } /** @test */ public function it_creates_quantities_using_convenience_methods() { $distance = Length::kilometers(18); $time = Duration::hours(1); $speed = Speed::fromLengthAndDuration($distance, $time); $this->assertTrue($speed instanceof Speed, "A speed instance should be of type ".Speed::class); $this->assertEqualsWithDelta($speed->value(), 5, 0.1, "Creating a speed measurement from $distance and $time should be equal to 5 m/s"); $this->assertEqualsWithDelta($speed->toKilometersPerHour()->value(), 18, 0.1, "Converting a speed of 5 m/s to km/h should be equal to 18 km/h"); } }<file_sep>/doc/Measurements-Equatable.md Measurements\Equatable =============== A type that can be compared for value equality. * Interface name: Equatable * Namespace: Measurements * This is an **interface** Methods ------- ### isEqualTo boolean Measurements\Equatable::isEqualTo(mixed $other) Returns a boolean value that indicates whether the receiver is equal to another given object. * Visibility: **public** #### Arguments * $other **mixed** - &lt;p&gt;The object with which to compare the receiver.&lt;/p&gt; <file_sep>/doc/Measurements-Units-UnitPower.md Measurements\Units\UnitPower =============== The `UnitPower` class encapsulates units of measure for power. You typically use instances of `UnitPower` to represent specific quantities of power using the `Measurement` class. Power is the amount of energy used over time. The SI unit for power is the watt (W), which is derived as one joule per second (1W = 1J / 1s). The base unit of `UnitPower` is defined as watts. * Class name: UnitPower * Namespace: Measurements\Units * Parent class: [Measurements\Dimension](Measurements-Dimension.md) Constants ---------- ### SYMBOL_TERAWATTS const SYMBOL_TERAWATTS = "TW" ### SYMBOL_GIGAWATTS const SYMBOL_GIGAWATTS = "GW" ### SYMBOL_MEGAWATTS const SYMBOL_MEGAWATTS = "MW" ### SYMBOL_KILOWATTS const SYMBOL_KILOWATTS = "kW" ### SYMBOL_WATTS const SYMBOL_WATTS = "W" ### SYMBOL_MILLIWATTS const SYMBOL_MILLIWATTS = "mW" ### SYMBOL_MICROWATTS const SYMBOL_MICROWATTS = "µW" ### SYMBOL_NANOWATTS const SYMBOL_NANOWATTS = "nW" ### SYMBOL_PICOWATTS const SYMBOL_PICOWATTS = "pW" ### SYMBOL_FEMTOWATTS const SYMBOL_FEMTOWATTS = "fW" ### SYMBOL_HORSE_POWER const SYMBOL_HORSE_POWER = "hp" ### COEFFICIENT_TERAWATTS const COEFFICIENT_TERAWATTS = 1000000000000.0 ### COEFFICIENT_GIGAWATTS const COEFFICIENT_GIGAWATTS = 1000000000.0 ### COEFFICIENT_MEGAWATTS const COEFFICIENT_MEGAWATTS = 1000000.0 ### COEFFICIENT_KILOWATTS const COEFFICIENT_KILOWATTS = 1000.0 ### COEFFICIENT_WATTS const COEFFICIENT_WATTS = 1.0 ### COEFFICIENT_MILLIWATTS const COEFFICIENT_MILLIWATTS = 0.001 ### COEFFICIENT_MICROWATTS const COEFFICIENT_MICROWATTS = 1.0E-6 ### COEFFICIENT_NANOWATTS const COEFFICIENT_NANOWATTS = 1.0E-9 ### COEFFICIENT_PICOWATTS const COEFFICIENT_PICOWATTS = 1.0E-12 ### COEFFICIENT_FEMTOWATTS const COEFFICIENT_FEMTOWATTS = 1.0E-15 ### COEFFICIENT_HORSE_POWER const COEFFICIENT_HORSE_POWER = 745.7 Properties ---------- ### $converter protected \Measurements\UnitConverter $converter The converter used to represent the unit in terms of the dimension's base unit. * Visibility: **protected** ### $symbol protected string $symbol The symbolic representation of the unit. * Visibility: **protected** Methods ------- ### baseUnit mixed Measurements\BaseUnitConvertible::baseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is **static**. * This method is defined by [Measurements\BaseUnitConvertible](Measurements-BaseUnitConvertible.md) ### terawatts \Measurements\Units\UnitPower Measurements\Units\UnitPower::terawatts() Returns the terawatts unit of power. * Visibility: **public** * This method is **static**. ### gigawatts \Measurements\Units\UnitPower Measurements\Units\UnitPower::gigawatts() Returns the gigawatts unit of power. * Visibility: **public** * This method is **static**. ### megawatts \Measurements\Units\UnitPower Measurements\Units\UnitPower::megawatts() Returns the megawatts unit of power. * Visibility: **public** * This method is **static**. ### kilowatts \Measurements\Units\UnitPower Measurements\Units\UnitPower::kilowatts() Returns the kilowatts unit of power. * Visibility: **public** * This method is **static**. ### watts \Measurements\Units\UnitPower Measurements\Units\UnitPower::watts() Returns the watts unit of power. * Visibility: **public** * This method is **static**. ### milliwatts \Measurements\Units\UnitPower Measurements\Units\UnitPower::milliwatts() Returns the milliwatts unit of power. * Visibility: **public** * This method is **static**. ### microwatts \Measurements\Units\UnitPower Measurements\Units\UnitPower::microwatts() Returns the microwatts unit of power. * Visibility: **public** * This method is **static**. ### nanowatts \Measurements\Units\UnitPower Measurements\Units\UnitPower::nanowatts() Returns the nanowatts unit of power. * Visibility: **public** * This method is **static**. ### picowatts \Measurements\Units\UnitPower Measurements\Units\UnitPower::picowatts() Returns the picowatts unit of power. * Visibility: **public** * This method is **static**. ### femtowatts \Measurements\Units\UnitPower Measurements\Units\UnitPower::femtowatts() Returns the femtowatts unit of power. * Visibility: **public** * This method is **static**. ### horsepower \Measurements\Units\UnitPower Measurements\Units\UnitPower::horsepower() Returns the horsepower unit of power. * Visibility: **public** * This method is **static**. ### __construct mixed Measurements\Unit::__construct(string $symbol) Initializes a new unit with the specified symbol. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) #### Arguments * $symbol **string** - &lt;p&gt;The symbolic representation of the unit.&lt;/p&gt; ### converter \Measurements\UnitConverter Measurements\Dimension::converter() Returns the unit converter used to represent the unit in terms of the dimension's base unit. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### getBaseUnit mixed Measurements\Dimension::getBaseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### symbol string Measurements\Unit::symbol() Return the symbolic representation of the unit. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) ### isEqualTo boolean Measurements\Equatable::isEqualTo(mixed $other) Returns a boolean value that indicates whether the receiver is equal to another given object. * Visibility: **public** * This method is defined by [Measurements\Equatable](Measurements-Equatable.md) #### Arguments * $other **mixed** - &lt;p&gt;The object with which to compare the receiver.&lt;/p&gt; ### __toString string Measurements\Unit::__toString() Converts the unit to its string representation. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) <file_sep>/doc/Measurements-Quantities-Area.md Measurements\Quantities\Area =============== The `Area` class represents a specific quantities of area. * Class name: Area * Namespace: Measurements\Quantities * Parent class: Measurements\Measurement Methods ------- ### __construct mixed Measurements\Quantities\Area::__construct(double $value, \Measurements\Unit $unit) Initializes a new speed with a specified floating-point value and unit. * Visibility: **public** #### Arguments * $value **double** - &lt;p&gt;The measurement value.&lt;/p&gt; * $unit **[Measurements\Unit](Measurements-Unit.md)** - &lt;p&gt;The unit of measure.&lt;/p&gt; ### fromEquivalentLengths \Measurements\Quantities\Area Measurements\Quantities\Area::fromEquivalentLengths(\Measurements\Quantities\Length $length) Returns the area measurement computed from the specified length. * Visibility: **public** * This method is **static**. #### Arguments * $length **[Measurements\Quantities\Length](Measurements-Quantities-Length.md)** - &lt;p&gt;A length.&lt;/p&gt; ### fromLengthAndWidth \Measurements\Quantities\Area Measurements\Quantities\Area::fromLengthAndWidth(\Measurements\Quantities\Length $length, \Measurements\Quantities\Length $width) Returns the area measurement computed from the specified length and width. * Visibility: **public** * This method is **static**. #### Arguments * $length **[Measurements\Quantities\Length](Measurements-Quantities-Length.md)** - &lt;p&gt;A length.&lt;/p&gt; * $width **[Measurements\Quantities\Length](Measurements-Quantities-Length.md)** - &lt;p&gt;A width.&lt;/p&gt; <file_sep>/src/Units/UnitSpeed.php <?php namespace Measurements\Units; use Measurements\Dimension; use Measurements\Converters\UnitConverterLinear; /** * The `UnitSpeed` class encapsulates units of measure for speed. * You typically use instances of `UnitSpeed` to represent specific quantities of speed using the `Measurement` class. * * Speed is the magnitude of velocity, or the rate of change of position. * Speed can be expressed by SI derived units in terms of meters per second (m/s), and is also commonly expressed in terms of kilometers per hour (km/h) and miles per hour (mph). * * The base unit of `UnitSpeed` is defined as meters per second. */ class UnitSpeed extends Dimension { const SYMBOL_METERS_PER_SECOND = "m/s"; const SYMBOL_KILOMETERS_PER_HOUR = "km/h"; const SYMBOL_MILES_PER_HOUR = "mph"; const SYMBOL_KNOTS = "kn"; const COEFFICIENT_METERS_PER_SECOND = 1.0; const COEFFICIENT_KILOMETERS_PER_HOUR = 0.277778; const COEFFICIENT_MILES_PER_HOUR = 0.44704; const COEFFICIENT_KNOTS = 0.514444; /** * Returns the base unit of speed, equal to meters per second. * * @return UnitSpeed The base unit of speed. */ public static function baseUnit() { return self::metersPerSecond(); } /** * Returns the meters per second unit of speed. * * @return UnitSpeed The meters per second unit of speed. */ public static function metersPerSecond(): UnitSpeed { return new static(static::SYMBOL_METERS_PER_SECOND, new UnitConverterLinear(static::COEFFICIENT_METERS_PER_SECOND)); } /** * Returns the kilometers per second unit of speed. * * @return UnitSpeed The kilometers per second unit of speed. */ public static function kilometersPerHour(): UnitSpeed { return new static(static::SYMBOL_KILOMETERS_PER_HOUR, new UnitConverterLinear(static::COEFFICIENT_KILOMETERS_PER_HOUR)); } /** * Returns the miles per hours unit of speed. * * @return UnitSpeed The miles per hours unit of speed. */ public static function milesPerHour(): UnitSpeed { return new static(static::SYMBOL_MILES_PER_HOUR, new UnitConverterLinear(static::COEFFICIENT_MILES_PER_HOUR)); } /** * Returns the knots unit of speed. * * @return UnitSpeed The knots unit of speed. */ public static function knots(): UnitSpeed { return new static(static::SYMBOL_KNOTS, new UnitConverterLinear(static::COEFFICIENT_KNOTS)); } } <file_sep>/src/Quantities/ElectricResistance.php <?php namespace Measurements\Quantities; use Measurements\Unit; use Measurements\Measurement; use Measurements\Exceptions\UnitException; use Measurements\Units\UnitElectricResistance; /** * The `ElectricResistance` class represents a specific quantities of electric resistance. * * @method static ElectricResistance megaohms(float $value) * @method static ElectricResistance kiloohms(float $value) * @method static ElectricResistance ohms(float $value) * @method static ElectricResistance milliohms(float $value) * @method static ElectricResistance microohms(float $value) */ class ElectricResistance extends Measurement { /** * Initializes a new electric resistance measurement with a specified floating-point value and unit. * * @param double $value The measurement value. * @param Unit $unit The unit of measure. * * @throws \Measurements\Exceptions\UnitException */ public function __construct($value, Unit $unit) { if (!$unit instanceof UnitElectricResistance) { throw new UnitException("Attempt to create a electric resistance measurement from an invalid unit [$unit]!"); } parent::__construct($value, $unit); } } <file_sep>/tests/MeasurementTests.php <?php namespace Tests; use PHPUnit\Framework\TestCase; use Measurements\Measurement; use Measurements\Units\UnitLength; class MeasurementTests extends TestCase { /** @test */ public function it_creates_a_measurement() { $length = new Measurement(42, UnitLength::meters()); $this->assertNotNull($length); $this->assertTrue($length == '42 m', "Measurement should print <42 m>."); } /** @test */ public function it_returns_a_measurement_value() { $length = new Measurement(42, UnitLength::meters()); $this->assertTrue($length->value() == 42, "Measurement value should be 42."); } /** @test */ public function it_returns_a_measurement_unit() { $length = new Measurement(42, UnitLength::meters()); $this->assertTrue($length->unit() == UnitLength::meters(), "Measurement unit should be length."); } /** @test */ public function it_checks_equality_of_measures_with_same_unit() { $first = new Measurement(42, UnitLength::meters()); $second = new Measurement(42.0, UnitLength::meters()); $third = new Measurement(37, UnitLength::meters()); $this->assertTrue($first->isEqualTo($second), "Measurements should be equal."); $this->assertFalse($first->isEqualTo($third), "Measurements should not be equal."); } /** @test */ public function it_checks_equality_of_measures_with_different_unit() { $meters = new Measurement(42, UnitLength::meters()); $centimeters = new Measurement(4200, UnitLength::centimeters()); $other = new Measurement(420, UnitLength::centimeters()); $this->assertTrue($meters->isEqualTo($centimeters), "Measurements should be equal."); $this->assertFalse($meters->isEqualTo($other), "Measurements should not be equal."); } }<file_sep>/src/Units/UnitDispersion.php <?php namespace Measurements\Units; use Measurements\Dimension; use Measurements\Converters\UnitConverterLinear; /** * The `UnitDispersion` class encapsulates units of measure for an amount-of-substance fraction. * You typically use instances of `UnitDispersion` to represent specific quantities of dispersion using the `Measurement` class. * * Dispersion describes the the amount of a constituent divided by the amount of all other constituents in a mixture. * Dispersion is a dimensionless quantity that is commonly expressed in “parts-per” notation, such as “parts per million” (ppm), to describe small relative quantities. * The base unit of `UnitDispersion` is defined as parts per million. */ class UnitDispersion extends Dimension { const SYMBOL_PARTS_PER_MILLION = "ppm"; const COEFFICIENT_PARTS_PER_MILLION = 1.0; /** * Returns the base dispersion unit, equal to parts per million. * * @return UnitDispersion The base dispersion unit. */ public static function baseUnit() { return self::partsPerMillion(); } /** * Returns the parts per million unit. * * @return UnitDispersion The parts per million unit. */ public static function partsPerMillion(): UnitDispersion { return new static(static::SYMBOL_PARTS_PER_MILLION, new UnitConverterLinear(static::COEFFICIENT_PARTS_PER_MILLION)); } } <file_sep>/.travis.yml language: php sudo: false php: - 7.2 - 7.4 - 8.0 - 8.1 before_script: - composer self-update - composer install --no-interaction notifications: email: false script: - vendor/bin/phpunit <file_sep>/tests/ComparisonTests.php <?php namespace Tests; use PHPUnit\Framework\TestCase; use Measurements\Measurement; use Measurements\Units\UnitLength; use Measurements\Units\UnitDuration; use Measurements\Exceptions\UnitException; class ComparisonTests extends TestCase { /** @test */ public function compared_measurements_must_have_same_units() { $meters = new Measurement(10, UnitLength::meters()); $centimeters = new Measurement(10, UnitLength::centimeters()); $seconds = new Measurement(10, UnitDuration::seconds()); $comparison = function($lhs, $rhs) { return 0; }; $this->assertTrue($meters->compareTo($centimeters, $comparison) == 0, "Meters should be compared to centimeters."); $this->expectException(UnitException::class); $meters->compareTo($seconds, $comparison); } /** @test */ public function a_measurement_can_be_compared() { $big = new Measurement(10, UnitLength::meters()); $small = new Measurement(5, UnitLength::meters()); $smaller = new Measurement(20, UnitLength::centimeters()); $equal = new Measurement(1000, UnitLength::centimeters()); $this->assertTrue($big->isGreaterThan($small), "{$big} should be greater than {$small}"); $this->assertTrue($big->isGreaterThan($smaller), "{$big} should be greater than {$smaller}"); $this->assertTrue($small->isLessThan($big), "{$small} should be less than {$big}"); $this->assertTrue($smaller->isLessThan($big), "{$smaller} should be less than {$big}"); $this->assertTrue($big->isEqualTo($equal), "{$big} should be equal to {$equal}"); $this->assertTrue($big->isGreaterThanOrEqualTo($equal), "{$big} should be greater than or equal to {$equal}"); $this->assertTrue($big->isLessThanOrEqualTo($equal), "{$big} should be less than or equal to {$equal}"); } }<file_sep>/doc/Measurements-Converters-UnitConverterLinear.md Measurements\Converters\UnitConverterLinear =============== `UnitConverterLinear` is a `UnitConverter` subclass for converting between units using a linear equation. A linear equation for unit conversion takes the form y = mx + b, such that: - y is the value in terms of the base unit of the dimension - m is the known coefficient used for this unit's conversion - x is the value in terms of the unit on which this method is called - b is the known constant used for this unit's conversion * Class name: UnitConverterLinear * Namespace: Measurements\Converters * This class implements: [Measurements\UnitConverter](Measurements-UnitConverter.md) Properties ---------- ### $coefficient protected double $coefficient The coefficient used in the linear unit conversion calculation. * Visibility: **protected** ### $constant protected double $constant The constant used in the linear unit conversion calculation. * Visibility: **protected** Methods ------- ### __construct mixed Measurements\Converters\UnitConverterLinear::__construct(double $coefficient, double $constant) Initializes the unit converter with the specified coefficient and constant. * Visibility: **public** #### Arguments * $coefficient **double** - &lt;p&gt;The coefficient used in the linear unit conversion calculation.&lt;/p&gt; * $constant **double** - &lt;p&gt;The constant used in the linear unit conversion calculation.&lt;/p&gt; ### baseUnitValueFromValue mixed Measurements\UnitConverter::baseUnitValueFromValue($value) * Visibility: **public** * This method is defined by [Measurements\UnitConverter](Measurements-UnitConverter.md) #### Arguments * $value **mixed** ### valueFromBaseUnitValue mixed Measurements\UnitConverter::valueFromBaseUnitValue($baseUnitValue) * Visibility: **public** * This method is defined by [Measurements\UnitConverter](Measurements-UnitConverter.md) #### Arguments * $baseUnitValue **mixed** <file_sep>/doc/Measurements-Units-UnitIlluminance.md Measurements\Units\UnitIlluminance =============== The `UnitIlluminance` class encapsulates units of measure for illuminance. You typically use instances of `UnitIlluminance` to represent specific quantities of illuminance using the `Measurement` class. Illuminance is the luminous flux incident on a surface. The SI unit for illuminance is the lux (lx), which is derived as one lumen per square meter (1lm / 1m2). The base unit of `UnitIlluminance` is defined as lux. * Class name: UnitIlluminance * Namespace: Measurements\Units * Parent class: [Measurements\Dimension](Measurements-Dimension.md) Constants ---------- ### SYMBOL_LUX const SYMBOL_LUX = "lx" ### COEFFICIENT_LUX const COEFFICIENT_LUX = 1.0 Properties ---------- ### $converter protected \Measurements\UnitConverter $converter The converter used to represent the unit in terms of the dimension's base unit. * Visibility: **protected** ### $symbol protected string $symbol The symbolic representation of the unit. * Visibility: **protected** Methods ------- ### baseUnit mixed Measurements\BaseUnitConvertible::baseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is **static**. * This method is defined by [Measurements\BaseUnitConvertible](Measurements-BaseUnitConvertible.md) ### lux \Measurements\Units\UnitIlluminance Measurements\Units\UnitIlluminance::lux() Returns the lux unit of illuminance. * Visibility: **public** * This method is **static**. ### __construct mixed Measurements\Unit::__construct(string $symbol) Initializes a new unit with the specified symbol. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) #### Arguments * $symbol **string** - &lt;p&gt;The symbolic representation of the unit.&lt;/p&gt; ### converter \Measurements\UnitConverter Measurements\Dimension::converter() Returns the unit converter used to represent the unit in terms of the dimension's base unit. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### getBaseUnit mixed Measurements\Dimension::getBaseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### symbol string Measurements\Unit::symbol() Return the symbolic representation of the unit. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) ### isEqualTo boolean Measurements\Equatable::isEqualTo(mixed $other) Returns a boolean value that indicates whether the receiver is equal to another given object. * Visibility: **public** * This method is defined by [Measurements\Equatable](Measurements-Equatable.md) #### Arguments * $other **mixed** - &lt;p&gt;The object with which to compare the receiver.&lt;/p&gt; ### __toString string Measurements\Unit::__toString() Converts the unit to its string representation. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) <file_sep>/tests/Units/UnitEnergyTests.php <?php namespace Tests\Units; use PHPUnit\Framework\TestCase; use Measurements\Measurement; use Measurements\Units\UnitEnergy; class UnitEnergyTests extends TestCase { use InteractsWithUnits; /** @test */ public function it_defines_joules_as_base_unit() { $this->assertTrue(UnitEnergy::baseUnit() == UnitEnergy::joules(), "Energy should define joules as its base unit."); } /** @test */ public function it_converts_energies() { $base = new Measurement(1, UnitEnergy::baseUnit()); $this->assertMeasurementEquals($base->convertTo(UnitEnergy::kilojoules()), 0.001, $base, "kilojoules"); $this->assertMeasurementEquals($base->convertTo(UnitEnergy::joules()), 1.0, $base, "joules"); $this->assertMeasurementEquals($base->convertTo(UnitEnergy::kilocalories()), 1.0 / 4184.0, $base, "kilocalories"); $this->assertMeasurementEquals($base->convertTo(UnitEnergy::calories()), 1.0 / 4.184, $base, "calories"); $this->assertMeasurementEquals($base->convertTo(UnitEnergy::kilowattHours()), 1.0 / 3600000.0, $base, "kilowatt"); } }<file_sep>/src/Units/UnitTemperature.php <?php namespace Measurements\Units; use Measurements\Dimension; use Measurements\Converters\UnitConverterLinear; /** * The `UnitTemperature` class encapsulates units of measure for temperature. * You typically use instances of `UnitTemperature` to represent specific quantities of temperature using the `Measurement` class. * * Temperature is a comparative measure of thermal energy. * The SI unit for temperature is the kelvin (K), which is defined in terms of the triple point of water. * Temperature is also commonly measured by degrees of various scales, including Celsius (°C) and Fahrenheit (°F). * * The base unit of `UnitTemperature` is defined as kelvin. */ class UnitTemperature extends Dimension { const SYMBOL_KELVIN = "K"; const SYMBOL_DEGREES_CELSIUS = "°C"; const SYMBOL_DEGREES_FAHRENHEIT = "°F"; const COEFFICIENT_KELVIN = 1.0; const COEFFICIENT_DEGREES_CELSIUS = 1.0; const COEFFICIENT_DEGREES_FAHRENHEIT = 5.0 / 9.0; const CONSTANT_DEGREES_CELSIUS = 273.15; const CONSTANT_DEGREES_FAHRENHEIT = 255.37222222222427; /** * Returns the base unit of temperature, equal to kelvin. * * @return UnitTemperature The base unit of temperature. */ public static function baseUnit() { return self::kelvin(); } /** * Returns the kelvin unit of temperature. * * @return UnitTemperature The kelvin unit of temperature. */ public static function kelvin(): UnitTemperature { return new static(static::SYMBOL_KELVIN, new UnitConverterLinear(static::COEFFICIENT_KELVIN)); } /** * Returns the degree Celsius unit of temperature. * * @return UnitTemperature The degree Celsius unit of temperature. */ public static function celsius(): UnitTemperature { return new static(static::SYMBOL_DEGREES_CELSIUS, new UnitConverterLinear(static::COEFFICIENT_DEGREES_CELSIUS, static::CONSTANT_DEGREES_CELSIUS)); } /** * Returns the degree Fahrenheit unit of temperature. * * @return UnitTemperature The degree Fahrenheit unit of temperature. */ public static function fahrenheit(): UnitTemperature { return new static(static::SYMBOL_DEGREES_FAHRENHEIT, new UnitConverterLinear(static::COEFFICIENT_DEGREES_FAHRENHEIT, static::CONSTANT_DEGREES_FAHRENHEIT)); } } <file_sep>/src/Converters/UnitConverterReciprocal.php <?php namespace Measurements\Converters; use Measurements\UnitConverter; /** * `UnitConverterReciprocal` is a `UnitConverter` subclass for converting between units using a reciprocal function. */ class UnitConverterReciprocal implements UnitConverter { /** * The reciprocal value used in the unit conversion calculation. * * @var double */ protected $reciprocal; /** * Initializes the unit converter with the specified reciprocal value. * * @param double $reciprocal The reciprocal value used in the unit conversion calculation. */ public function __construct($reciprocal) { $this->reciprocal = (double)$reciprocal; } public function baseUnitValueFromValue($value) { return $this->reciprocal / (double)$value; } public function valueFromBaseUnitValue($baseUnitValue) { return $this->reciprocal / (double)$baseUnitValue; } } <file_sep>/tests/Units/UnitElectricPotentialDifferenceTests.php <?php namespace Tests\Units; use PHPUnit\Framework\TestCase; use Measurements\Measurement; use Measurements\Units\UnitElectricPotentialDifference; class UnitElectricPotentialDifferenceTests extends TestCase { use InteractsWithUnits; /** @test */ public function it_defines_volts_as_base_unit() { $this->assertTrue(UnitElectricPotentialDifference::baseUnit() == UnitElectricPotentialDifference::volts(), "Electric potential difference should define volts as its base unit."); } /** @test */ public function it_converts_electrical_potential_differences() { $base = new Measurement(1, UnitElectricPotentialDifference::baseUnit()); $this->assertMeasurementEquals($base->convertTo(UnitElectricPotentialDifference::megavolts()), 1E-6, $base, "megavolts"); $this->assertMeasurementEquals($base->convertTo(UnitElectricPotentialDifference::kilovolts()), 0.001, $base, "kilovolts"); $this->assertMeasurementEquals($base->convertTo(UnitElectricPotentialDifference::volts()), 1.0, $base, "volts"); $this->assertMeasurementEquals($base->convertTo(UnitElectricPotentialDifference::millivolts()), 1000, $base, "millivolts"); $this->assertMeasurementEquals($base->convertTo(UnitElectricPotentialDifference::microvolts()), 1E+6, $base, "microvolts"); } }<file_sep>/src/Exceptions/MeasurementValueException.php <?php namespace Measurements\Exceptions; class MeasurementValueException extends \Exception {} <file_sep>/tests/Units/UnitFuelEfficiencyTests.php <?php namespace Tests\Units; use PHPUnit\Framework\TestCase; use Measurements\Measurement; use Measurements\Units\UnitFuelEfficiency; class UnitFuelEfficiencyTests extends TestCase { use InteractsWithUnits; /** @test */ public function it_defines_liters_per_100_kilometers_as_base_unit() { $this->assertTrue(UnitFuelEfficiency::baseUnit() == UnitFuelEfficiency::litersPer100Kilometers(), "Fuel Efficiency should define liters per 100 kilometers as its base unit."); } /** @test */ public function it_converts_fuel_efficiencies() { $base = new Measurement(1, UnitFuelEfficiency::baseUnit()); $this->assertMeasurementEquals($base->convertTo(UnitFuelEfficiency::litersPer100Kilometers()), 1.0, $base, "liters per 100 kilometers"); $this->assertMeasurementEquals($base->convertTo(UnitFuelEfficiency::milesPerGallon()), 235.215, $base, "miles per gallon"); $this->assertMeasurementEquals($base->convertTo(UnitFuelEfficiency::milesPerImperialGallon()), 282.481, $base, "miles per imperial gallon"); $this->assertMeasurementEquals($base->convertTo(UnitFuelEfficiency::kilometersPerLiter()), 100.0, $base, "kilometers per liter"); $base = new Measurement(5, UnitFuelEfficiency::baseUnit()); $this->assertEquals(20.0, $base->convertTo(UnitFuelEfficiency::kilometersPerLiter())->value()); } } <file_sep>/tests/Units/InteractsWithUnits.php <?php namespace Tests\Units; use Measurements\Measurement; trait InteractsWithUnits { public function assertMeasurementEquals(Measurement $measurement, $value, $base, $unit, $accuracy = 1E-9) { $this->assertEqualsWithDelta($measurement->value(), $value, $accuracy, "{$base} converted to {$unit} should be equal to {$value} {$measurement->unit()} instead of {$measurement}."); } }<file_sep>/doc/Measurements-Units-UnitDispersion.md Measurements\Units\UnitDispersion =============== The `UnitDispersion` class encapsulates units of measure for an amount-of-substance fraction. You typically use instances of `UnitDispersion` to represent specific quantities of dispersion using the `Measurement` class. Dispersion describes the the amount of a constituent divided by the amount of all other constituents in a mixture. Dispersion is a dimensionless quantity that is commonly expressed in “parts-per” notation, such as “parts per million” (ppm), to describe small relative quantities. The base unit of `UnitDispersion` is defined as parts per million. * Class name: UnitDispersion * Namespace: Measurements\Units * Parent class: [Measurements\Dimension](Measurements-Dimension.md) Constants ---------- ### SYMBOL_PARTS_PER_MILLION const SYMBOL_PARTS_PER_MILLION = "ppm" ### COEFFICIENT_PARTS_PER_MILLION const COEFFICIENT_PARTS_PER_MILLION = 1.0 Properties ---------- ### $converter protected \Measurements\UnitConverter $converter The converter used to represent the unit in terms of the dimension's base unit. * Visibility: **protected** ### $symbol protected string $symbol The symbolic representation of the unit. * Visibility: **protected** Methods ------- ### baseUnit mixed Measurements\BaseUnitConvertible::baseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is **static**. * This method is defined by [Measurements\BaseUnitConvertible](Measurements-BaseUnitConvertible.md) ### partsPerMillion \Measurements\Units\UnitDispersion Measurements\Units\UnitDispersion::partsPerMillion() Returns the parts per million unit. * Visibility: **public** * This method is **static**. ### __construct mixed Measurements\Unit::__construct(string $symbol) Initializes a new unit with the specified symbol. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) #### Arguments * $symbol **string** - &lt;p&gt;The symbolic representation of the unit.&lt;/p&gt; ### converter \Measurements\UnitConverter Measurements\Dimension::converter() Returns the unit converter used to represent the unit in terms of the dimension's base unit. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### getBaseUnit mixed Measurements\Dimension::getBaseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### symbol string Measurements\Unit::symbol() Return the symbolic representation of the unit. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) ### isEqualTo boolean Measurements\Equatable::isEqualTo(mixed $other) Returns a boolean value that indicates whether the receiver is equal to another given object. * Visibility: **public** * This method is defined by [Measurements\Equatable](Measurements-Equatable.md) #### Arguments * $other **mixed** - &lt;p&gt;The object with which to compare the receiver.&lt;/p&gt; ### __toString string Measurements\Unit::__toString() Converts the unit to its string representation. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) <file_sep>/tests/Units/UnitAccelerationTests.php <?php namespace Tests\Units; use PHPUnit\Framework\TestCase; use Measurements\Measurement; use Measurements\Units\UnitAcceleration; class UnitAccelerationTests extends TestCase { use InteractsWithUnits; /** @test */ public function it_defines_metersPerSecondSquared_as_base_unit() { $this->assertTrue(UnitAcceleration::baseUnit() == UnitAcceleration::metersPerSecondSquared(), "Acceleration should define Meters per second squared as its base unit."); } /** @test */ public function it_converts_accelerations() { $base = new Measurement(1, UnitAcceleration::baseUnit()); $this->assertMeasurementEquals($base->convertTo(UnitAcceleration::metersPerSecondSquared()), 1.0, $base, "meters per second squared"); $this->assertMeasurementEquals($base->convertTo(UnitAcceleration::gravity()), 1.0 / 9.81, $base, "gravity"); } }<file_sep>/src/UnitConverter.php <?php namespace Measurements; /** * A `UnitConverter` describes how to convert a unit to and from the base unit of its dimension. * Use the `UnitConverter` interface to implement new ways of converting a unit. */ interface UnitConverter { /* * For a given unit, returns the specified value of that unit in terms of the base unit of its dimension. * * @param double $value The value in terms of the unit class. * * @return double The value in terms of the base unit. */ public function baseUnitValueFromValue($value); /* * For a given unit, returns the specified value of the base unit in terms of that unit. * * @param double $baseUnitValue The value in terms of the base unit. * * @return double The value in terms of a given unit. */ public function valueFromBaseUnitValue($baseUnitValue); } <file_sep>/doc/Measurements-Units-UnitLength.md Measurements\Units\UnitLength =============== The `UnitLength` class encapsulates units of measure for length. You typically use instances of `UnitLength` to represent specific quantities of length using the `Measurement` class. Length is the dimensional extent of matter. The SI unit for length is the meter (m), which is defined in terms of the distance traveled by light in a vacuum. The base unit of `UnitLength` is defined as meters. * Class name: UnitLength * Namespace: Measurements\Units * Parent class: [Measurements\Dimension](Measurements-Dimension.md) Constants ---------- ### SYMBOL_MEGAMETERS const SYMBOL_MEGAMETERS = "Mm" ### SYMBOL_KILOMETERS const SYMBOL_KILOMETERS = "km" ### SYMBOL_HECTOMETERS const SYMBOL_HECTOMETERS = "hm" ### SYMBOL_DECAMETERS const SYMBOL_DECAMETERS = "dam" ### SYMBOL_METERS const SYMBOL_METERS = "m" ### SYMBOL_DECIMETERS const SYMBOL_DECIMETERS = "dm" ### SYMBOL_CENTIMETERS const SYMBOL_CENTIMETERS = "cm" ### SYMBOL_MILLIMETERS const SYMBOL_MILLIMETERS = "mm" ### SYMBOL_MICROMETERS const SYMBOL_MICROMETERS = "µm" ### SYMBOL_NANOMETERS const SYMBOL_NANOMETERS = "nm" ### SYMBOL_PICOMETERS const SYMBOL_PICOMETERS = "pm" ### SYMBOL_INCHES const SYMBOL_INCHES = "in" ### SYMBOL_FEET const SYMBOL_FEET = "ft" ### SYMBOL_YARDS const SYMBOL_YARDS = "yd" ### SYMBOL_MILES const SYMBOL_MILES = "mi" ### SYMBOL_LIGHTYEARS const SYMBOL_LIGHTYEARS = "ly" ### SYMBOL_NAUTICAL_MILES const SYMBOL_NAUTICAL_MILES = "NM" ### SYMBOL_FATHOMS const SYMBOL_FATHOMS = "ftm" ### SYMBOL_FURLONGS const SYMBOL_FURLONGS = "fur" ### SYMBOL_ASTRONOMIC_UNITS const SYMBOL_ASTRONOMIC_UNITS = "ua" ### SYMBOL_PARSECS const SYMBOL_PARSECS = "pc" ### COEFFICIENT_MEGAMETERS const COEFFICIENT_MEGAMETERS = 1000000.0 ### COEFFICIENT_KILOMETERS const COEFFICIENT_KILOMETERS = 1000.0 ### COEFFICIENT_HECTOMETERS const COEFFICIENT_HECTOMETERS = 100.0 ### COEFFICIENT_DECAMETERS const COEFFICIENT_DECAMETERS = 10.0 ### COEFFICIENT_METERS const COEFFICIENT_METERS = 1.0 ### COEFFICIENT_DECIMETERS const COEFFICIENT_DECIMETERS = 0.1 ### COEFFICIENT_CENTIMETERS const COEFFICIENT_CENTIMETERS = 0.01 ### COEFFICIENT_MILLIMETERS const COEFFICIENT_MILLIMETERS = 0.001 ### COEFFICIENT_MICROMETERS const COEFFICIENT_MICROMETERS = 1.0E-6 ### COEFFICIENT_NANOMETERS const COEFFICIENT_NANOMETERS = 1.0E-9 ### COEFFICIENT_PICOMETERS const COEFFICIENT_PICOMETERS = 1.0E-12 ### COEFFICIENT_INCHES const COEFFICIENT_INCHES = 0.0254 ### COEFFICIENT_FEET const COEFFICIENT_FEET = 0.3048 ### COEFFICIENT_YARDS const COEFFICIENT_YARDS = 0.9144 ### COEFFICIENT_MILES const COEFFICIENT_MILES = 1609.34 ### COEFFICIENT_LIGHTYEARS const COEFFICIENT_LIGHTYEARS = 9461000000000000.0 ### COEFFICIENT_NAUTICAL_MILES const COEFFICIENT_NAUTICAL_MILES = 1852.0 ### COEFFICIENT_FATHOMS const COEFFICIENT_FATHOMS = 1.8288 ### COEFFICIENT_FURLONGS const COEFFICIENT_FURLONGS = 201.168 ### COEFFICIENT_ASTRONOMIC_UNITS const COEFFICIENT_ASTRONOMIC_UNITS = 149600000000.0 ### COEFFICIENT_PARSECS const COEFFICIENT_PARSECS = 3.086E+16 Properties ---------- ### $converter protected \Measurements\UnitConverter $converter The converter used to represent the unit in terms of the dimension's base unit. * Visibility: **protected** ### $symbol protected string $symbol The symbolic representation of the unit. * Visibility: **protected** Methods ------- ### baseUnit mixed Measurements\BaseUnitConvertible::baseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is **static**. * This method is defined by [Measurements\BaseUnitConvertible](Measurements-BaseUnitConvertible.md) ### megameters \Measurements\Units\UnitLength Measurements\Units\UnitLength::megameters() Returns the megameters unit of length. * Visibility: **public** * This method is **static**. ### kilometers \Measurements\Units\UnitLength Measurements\Units\UnitLength::kilometers() Returns the kilometers unit of length. * Visibility: **public** * This method is **static**. ### hectometers \Measurements\Units\UnitLength Measurements\Units\UnitLength::hectometers() Returns the hectometers unit of length. * Visibility: **public** * This method is **static**. ### decameters \Measurements\Units\UnitLength Measurements\Units\UnitLength::decameters() Returns the decameters unit of length. * Visibility: **public** * This method is **static**. ### meters \Measurements\Units\UnitLength Measurements\Units\UnitLength::meters() Returns the meters unit of length. * Visibility: **public** * This method is **static**. ### decimeters \Measurements\Units\UnitLength Measurements\Units\UnitLength::decimeters() Returns the decimeters unit of length. * Visibility: **public** * This method is **static**. ### centimeters \Measurements\Units\UnitLength Measurements\Units\UnitLength::centimeters() Returns the centimeters unit of length. * Visibility: **public** * This method is **static**. ### millimeters \Measurements\Units\UnitLength Measurements\Units\UnitLength::millimeters() Returns the millimeters unit of length. * Visibility: **public** * This method is **static**. ### micrometers \Measurements\Units\UnitLength Measurements\Units\UnitLength::micrometers() Returns the micrometers unit of length. * Visibility: **public** * This method is **static**. ### nanometers \Measurements\Units\UnitLength Measurements\Units\UnitLength::nanometers() Returns the nanometers unit of length. * Visibility: **public** * This method is **static**. ### picometers \Measurements\Units\UnitLength Measurements\Units\UnitLength::picometers() Returns the picometers unit of length. * Visibility: **public** * This method is **static**. ### inches \Measurements\Units\UnitLength Measurements\Units\UnitLength::inches() Returns the inches unit of length. * Visibility: **public** * This method is **static**. ### feet \Measurements\Units\UnitLength Measurements\Units\UnitLength::feet() Returns the feet unit of length. * Visibility: **public** * This method is **static**. ### yards \Measurements\Units\UnitLength Measurements\Units\UnitLength::yards() Returns the yards unit of length. * Visibility: **public** * This method is **static**. ### miles \Measurements\Units\UnitLength Measurements\Units\UnitLength::miles() Returns the miles unit of length. * Visibility: **public** * This method is **static**. ### lightyears \Measurements\Units\UnitLength Measurements\Units\UnitLength::lightyears() Returns the lightyears unit of length. * Visibility: **public** * This method is **static**. ### nauticalMiles \Measurements\Units\UnitLength Measurements\Units\UnitLength::nauticalMiles() Returns the nautical miles unit of length. * Visibility: **public** * This method is **static**. ### fathoms \Measurements\Units\UnitLength Measurements\Units\UnitLength::fathoms() Returns the fathoms unit of length. * Visibility: **public** * This method is **static**. ### furlongs \Measurements\Units\UnitLength Measurements\Units\UnitLength::furlongs() Returns the furlongs unit of length. * Visibility: **public** * This method is **static**. ### astronomicalUnits \Measurements\Units\UnitLength Measurements\Units\UnitLength::astronomicalUnits() Returns the astronomical units unit of length. * Visibility: **public** * This method is **static**. ### parsecs \Measurements\Units\UnitLength Measurements\Units\UnitLength::parsecs() Returns the parsecs unit of length. * Visibility: **public** * This method is **static**. ### __construct mixed Measurements\Unit::__construct(string $symbol) Initializes a new unit with the specified symbol. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) #### Arguments * $symbol **string** - &lt;p&gt;The symbolic representation of the unit.&lt;/p&gt; ### converter \Measurements\UnitConverter Measurements\Dimension::converter() Returns the unit converter used to represent the unit in terms of the dimension's base unit. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### getBaseUnit mixed Measurements\Dimension::getBaseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### symbol string Measurements\Unit::symbol() Return the symbolic representation of the unit. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) ### isEqualTo boolean Measurements\Equatable::isEqualTo(mixed $other) Returns a boolean value that indicates whether the receiver is equal to another given object. * Visibility: **public** * This method is defined by [Measurements\Equatable](Measurements-Equatable.md) #### Arguments * $other **mixed** - &lt;p&gt;The object with which to compare the receiver.&lt;/p&gt; ### __toString string Measurements\Unit::__toString() Converts the unit to its string representation. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) <file_sep>/doc/Measurements-Units-UnitDuration.md Measurements\Units\UnitDuration =============== The `UnitDuration` class encapsulates units of measure for duration of time. You typically use instances of `UnitDuration` to represent specific quantities of planar angle using the `Measurement` class. Duration is a quantity of time. The SI unit for time is the second (sec). Duration is also commonly expressed in terms of minutes (min) and hours (hr). The base unit of `UnitDuration` is defined as seconds. * Class name: UnitDuration * Namespace: Measurements\Units * Parent class: [Measurements\Dimension](Measurements-Dimension.md) Constants ---------- ### SYMBOL_SECONDS const SYMBOL_SECONDS = "sec" ### SYMBOL_MINUTES const SYMBOL_MINUTES = "min" ### SYMBOL_HOURS const SYMBOL_HOURS = "hr" ### COEFFICIENT_SECONDS const COEFFICIENT_SECONDS = 1.0 ### COEFFICIENT_MINUTES const COEFFICIENT_MINUTES = 60.0 ### COEFFICIENT_HOURS const COEFFICIENT_HOURS = 3600.0 Properties ---------- ### $converter protected \Measurements\UnitConverter $converter The converter used to represent the unit in terms of the dimension's base unit. * Visibility: **protected** ### $symbol protected string $symbol The symbolic representation of the unit. * Visibility: **protected** Methods ------- ### baseUnit mixed Measurements\BaseUnitConvertible::baseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is **static**. * This method is defined by [Measurements\BaseUnitConvertible](Measurements-BaseUnitConvertible.md) ### seconds \Measurements\Units\UnitDuration Measurements\Units\UnitDuration::seconds() Returns the second unit of duration. * Visibility: **public** * This method is **static**. ### minutes \Measurements\Units\UnitDuration Measurements\Units\UnitDuration::minutes() Returns the minute unit of duration. * Visibility: **public** * This method is **static**. ### hours \Measurements\Units\UnitDuration Measurements\Units\UnitDuration::hours() Returns the hour unit of duration. * Visibility: **public** * This method is **static**. ### __construct mixed Measurements\Unit::__construct(string $symbol) Initializes a new unit with the specified symbol. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) #### Arguments * $symbol **string** - &lt;p&gt;The symbolic representation of the unit.&lt;/p&gt; ### converter \Measurements\UnitConverter Measurements\Dimension::converter() Returns the unit converter used to represent the unit in terms of the dimension's base unit. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### getBaseUnit mixed Measurements\Dimension::getBaseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### symbol string Measurements\Unit::symbol() Return the symbolic representation of the unit. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) ### isEqualTo boolean Measurements\Equatable::isEqualTo(mixed $other) Returns a boolean value that indicates whether the receiver is equal to another given object. * Visibility: **public** * This method is defined by [Measurements\Equatable](Measurements-Equatable.md) #### Arguments * $other **mixed** - &lt;p&gt;The object with which to compare the receiver.&lt;/p&gt; ### __toString string Measurements\Unit::__toString() Converts the unit to its string representation. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) <file_sep>/src/Equatable.php <?php namespace Measurements; /** * A type that can be compared for value equality. */ interface Equatable { /** * Returns a boolean value that indicates whether the receiver is equal to another given object. * * @param mixed $other The object with which to compare the receiver. * * @return bool `true` if both objects are equal, otherwise `false`. */ public function isEqualTo($other); } <file_sep>/src/Quantities/Volume.php <?php namespace Measurements\Quantities; use Measurements\Unit; use Measurements\Measurement; use Measurements\Units\UnitLength; use Measurements\Units\UnitVolume; use Measurements\Exceptions\UnitException; /** * The `Volume` class represents a specific quantities of volume. * * @method static Volume megaliters(float $value) * @method static Volume kiloliters(float $value) * @method static Volume liters(float $value) * @method static Volume deciliters(float $value) * @method static Volume centiliters(float $value) * @method static Volume milliliters(float $value) * @method static Volume cubicKilometers(float $value) * @method static Volume cubicMeters(float $value) * @method static Volume cubicDecimeters(float $value) * @method static Volume cubicMillimeters(float $value) * @method static Volume cubicInches(float $value) * @method static Volume cubicFeet(float $value) * @method static Volume cubicYards(float $value) * @method static Volume cubicMiles(float $value) * @method static Volume acreFeet(float $value) * @method static Volume bushels(float $value) * @method static Volume teaspoons(float $value) * @method static Volume tablespoons(float $value) * @method static Volume fluidOunces(float $value) * @method static Volume cups(float $value) * @method static Volume pints(float $value) * @method static Volume quarts(float $value) * @method static Volume gallons(float $value) * @method static Volume imperialTeaspoons(float $value) * @method static Volume imperialTablespoons(float $value) * @method static Volume imperialFluidOunces(float $value) * @method static Volume imperialPints(float $value) * @method static Volume imperialQuarts(float $value) * @method static Volume imperialGallons(float $value) * @method static Volume metricCups(float $value) */ class Volume extends Measurement { /** * Initializes a new volume measurement with a specified floating-point value and unit. * * @param double $value The measurement value. * @param Unit $unit The unit of measure. * * @throws \Measurements\Exceptions\UnitException */ public function __construct($value, Unit $unit) { if (! $unit instanceof UnitVolume) { throw new UnitException("Attempt to create a volume measurement from an invalid unit [$unit]!"); } parent::__construct($value, $unit); } /** * Returns a volume measurement computed from a specified length. * * @param Length $length A length. * * @return \Measurements\Quantities\Volume The volume that corresponds to the given length. */ public static function fromEquivalentLengths(Length $length) { return static::fromLengths($length, $length, $length); } /** * Returns a volume measurement computed from the specified length, width and height. * * @param Length $length A length. * @param Length $width A width. * @param Length $height A height. * * @return \Measurements\Quantities\Volume The volume that corresponds to the given length, width and height. */ public static function fromLengths(Length $length, Length $width, Length $height) { $length = $length->convertTo(UnitLength::meters()); $width = $width->convertTo(UnitLength::meters()); $height = $height->convertTo(UnitLength::meters()); $volume = $length->value() * $width->value() * $height->value(); $volumeInCubicMeters = new static($volume, UnitVolume::cubicMeters()); return $volumeInCubicMeters->convertTo(UnitVolume::baseUnit()); } } <file_sep>/doc/Measurements-Units-UnitAcceleration.md Measurements\Units\UnitAcceleration =============== The `UnitAcceleration` class encapsulates units of measure for acceleration. You typically use instances of `UnitAcceleration` to represent specific quantities of acceleration using the `Measurement class. Acceleration is the rate of change of velocity. Acceleration can be expressed by SI derived units in terms of meters per second squared (m/s²). The base unit of `UnitAcceleration` is defined as meters per second squared. * Class name: UnitAcceleration * Namespace: Measurements\Units * Parent class: [Measurements\Dimension](Measurements-Dimension.md) Constants ---------- ### SYMBOL_METERS_PER_SECONDS_SQUARED const SYMBOL_METERS_PER_SECONDS_SQUARED = "m/s²" ### SYMBOL_GRAVITY const SYMBOL_GRAVITY = "g" ### COEFFICIENT_METERS_PER_SECONDS_SQUARED const COEFFICIENT_METERS_PER_SECONDS_SQUARED = 1.0 ### COEFFICIENT_GRAVITY const COEFFICIENT_GRAVITY = 9.81 Properties ---------- ### $converter protected \Measurements\UnitConverter $converter The converter used to represent the unit in terms of the dimension's base unit. * Visibility: **protected** ### $symbol protected string $symbol The symbolic representation of the unit. * Visibility: **protected** Methods ------- ### baseUnit mixed Measurements\BaseUnitConvertible::baseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is **static**. * This method is defined by [Measurements\BaseUnitConvertible](Measurements-BaseUnitConvertible.md) ### metersPerSecondSquared \Measurements\Units\UnitAcceleration Measurements\Units\UnitAcceleration::metersPerSecondSquared() Returns the meter per second squared unit of acceleration. * Visibility: **public** * This method is **static**. ### gravity \Measurements\Units\UnitAcceleration Measurements\Units\UnitAcceleration::gravity() Returns the gravity unit of acceleration. * Visibility: **public** * This method is **static**. ### __construct mixed Measurements\Unit::__construct(string $symbol) Initializes a new unit with the specified symbol. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) #### Arguments * $symbol **string** - &lt;p&gt;The symbolic representation of the unit.&lt;/p&gt; ### converter \Measurements\UnitConverter Measurements\Dimension::converter() Returns the unit converter used to represent the unit in terms of the dimension's base unit. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### getBaseUnit mixed Measurements\Dimension::getBaseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### symbol string Measurements\Unit::symbol() Return the symbolic representation of the unit. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) ### isEqualTo boolean Measurements\Equatable::isEqualTo(mixed $other) Returns a boolean value that indicates whether the receiver is equal to another given object. * Visibility: **public** * This method is defined by [Measurements\Equatable](Measurements-Equatable.md) #### Arguments * $other **mixed** - &lt;p&gt;The object with which to compare the receiver.&lt;/p&gt; ### __toString string Measurements\Unit::__toString() Converts the unit to its string representation. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) <file_sep>/src/Comparable.php <?php namespace Measurements; /** * Instances of conforming types can be compared. */ interface Comparable extends Equatable { /** * Returns a Boolean value that indicates whether the receiver is greater than another given object. * * @param mixed $object The object with which to compare the receiver. * * @return bool `true` if the receiver is greater than object, otherwise `false`. */ public function isGreaterThan($object); /** * Returns a Boolean value that indicates whether the receiver is greater than or equal to another given object. * * @param mixed $object The object with which to compare the receiver. * * @return bool `true` if the receiver is greater than or equal to object, otherwise `false`. */ public function isGreaterThanOrEqualTo($object); /** * Returns a Boolean value that indicates whether the receiver is less than another given object. * * @param mixed $object The object with which to compare the receiver. * * @return bool `true` if the receiver is less than object, otherwise `false`. */ public function isLessThan($object); /** * Returns a Boolean value that indicates whether the receiver is less than or equal to another given object. * * @param mixed $object The object with which to compare the receiver. * * @return bool `true` if the receiver is less than or equal to object, otherwise `false`. */ public function isLessThanOrEqualTo($object); /** * Compares the receiver to another given object. * * @param mixed $object The object with which to compare the receiver. * @param callable $comparison The closure used to compare objects. * * @return mixed The result of the comparison between the receiver and the given object. */ public function compareTo($object, callable $comparison); } <file_sep>/src/Quantities/Pressure.php <?php namespace Measurements\Quantities; use Measurements\Unit; use Measurements\Measurement; use Measurements\Units\UnitPressure; use Measurements\Exceptions\UnitException; /** * The `Pressure` class represents a specific quantities of pressure. * * @method static Pressure newtonsPerMeterSquared(float $value) * @method static Pressure gigapascals(float $value) * @method static Pressure megapascals(float $value) * @method static Pressure kilopascals(float $value) * @method static Pressure hectopascals(float $value) * @method static Pressure pascals(float $value) * @method static Pressure inchesOfMercury(float $value) * @method static Pressure bars(float $value) * @method static Pressure millibars(float $value) * @method static Pressure millimetersOfMercury(float $value) * @method static Pressure poundsPerSquareInch(float $value) */ class Pressure extends Measurement { /** * Initializes a new pressure measurement with a specified floating-point value and unit. * * @param double $value The measurement value. * @param Unit $unit The unit of measure. * * @throws \Measurements\Exceptions\UnitException */ public function __construct($value, Unit $unit) { if (!$unit instanceof UnitPressure) { throw new UnitException("Attempt to create a pressure measurement from an invalid unit [$unit]!"); } parent::__construct($value, $unit); } } <file_sep>/src/Units/UnitAcceleration.php <?php namespace Measurements\Units; use Measurements\Dimension; use Measurements\Converters\UnitConverterLinear; /** * The `UnitAcceleration` class encapsulates units of measure for acceleration. * You typically use instances of `UnitAcceleration` to represent specific quantities of acceleration using the `Measurement class. * * Acceleration is the rate of change of velocity. Acceleration can be expressed by SI derived units in terms of meters per second squared (m/s²). * * The base unit of `UnitAcceleration` is defined as meters per second squared. */ class UnitAcceleration extends Dimension { const SYMBOL_METERS_PER_SECONDS_SQUARED = "m/s²"; const SYMBOL_GRAVITY = "g"; const COEFFICIENT_METERS_PER_SECONDS_SQUARED = 1.0; const COEFFICIENT_GRAVITY = 9.81; /** * Returns the base acceleration unit, equal to metersPerSecondSquared. * * @return UnitAcceleration The base acceleration unit. */ public static function baseUnit() { return self::metersPerSecondSquared(); } /** * Returns the meter per second squared unit of acceleration. * * @return UnitAcceleration The meter per second squared unit of acceleration. */ public static function metersPerSecondSquared(): UnitAcceleration { return new static(static::SYMBOL_METERS_PER_SECONDS_SQUARED, new UnitConverterLinear(static::COEFFICIENT_METERS_PER_SECONDS_SQUARED)); } /** * Returns the gravity unit of acceleration. * * @return UnitAcceleration The gravity unit of acceleration. */ public static function gravity(): UnitAcceleration { return new static(static::SYMBOL_GRAVITY, new UnitConverterLinear(static::COEFFICIENT_GRAVITY)); } } <file_sep>/src/Quantities/ElectricCurrent.php <?php namespace Measurements\Quantities; use Measurements\Unit; use Measurements\Measurement; use Measurements\Units\UnitElectricCurrent; use Measurements\Exceptions\UnitException; /** * The `ElectricCurrent` class represents a specific quantities of electric current. * * @method static ElectricCurrent megaamperes(float $value) * @method static ElectricCurrent kiloamperes(float $value) * @method static ElectricCurrent amperes(float $value) * @method static ElectricCurrent milliamperes(float $value) * @method static ElectricCurrent microamperes(float $value) */ class ElectricCurrent extends Measurement { /** * Initializes a new electric current measurement with a specified floating-point value and unit. * * @param double $value The measurement value. * @param Unit $unit The unit of measure. * * @throws \Measurements\Exceptions\UnitException */ public function __construct($value, Unit $unit) { if (!$unit instanceof UnitElectricCurrent) { throw new UnitException("Attempt to create a electric current measurement from an invalid unit [$unit]!"); } parent::__construct($value, $unit); } } <file_sep>/tests/Units/UnitFrequencyTests.php <?php namespace Tests\Units; use PHPUnit\Framework\TestCase; use Measurements\Measurement; use Measurements\Units\UnitFrequency; class UnitFrequencyTests extends TestCase { use InteractsWithUnits; /** @test */ public function it_defines_hertz_as_base_unit() { $this->assertTrue(UnitFrequency::baseUnit() == UnitFrequency::hertz(), "Frequency should define hertz as its base unit."); } /** @test */ public function it_converts_frequencies() { $base = new Measurement(1, UnitFrequency::baseUnit()); $this->assertMeasurementEquals($base->convertTo(UnitFrequency::terahertz()), 1.0 / 1E+12, $base, "terahertz"); $this->assertMeasurementEquals($base->convertTo(UnitFrequency::gigahertz()), 1.0 / 1E+9, $base, "gigahertz"); $this->assertMeasurementEquals($base->convertTo(UnitFrequency::megahertz()), 1.0 / 1E+6, $base, "megahertz"); $this->assertMeasurementEquals($base->convertTo(UnitFrequency::kilohertz()), 0.001, $base, "kilohertz"); $this->assertMeasurementEquals($base->convertTo(UnitFrequency::hertz()), 1.0, $base, "hertz"); $this->assertMeasurementEquals($base->convertTo(UnitFrequency::millihertz()), 1000, $base, "millihertz"); $this->assertMeasurementEquals($base->convertTo(UnitFrequency::microhertz()), 1.0 / 1E-6, $base, "microhertz"); $this->assertMeasurementEquals($base->convertTo(UnitFrequency::nanohertz()), 1.0 / 1E-9, $base, "nanohertz"); } }<file_sep>/ReadMe.md # Measurements & Units ![Build Status](https://github.com/marfurt/measurements/actions/workflows/tests.yml/badge.svg?branch=master) [![Latest Stable Version](https://poser.pugx.org/nmarfurt/measurements/v/stable)](https://packagist.org/packages/nmarfurt/measurements) [![License](https://poser.pugx.org/nmarfurt/measurements/license)](https://packagist.org/packages/nmarfurt/measurements) ## About This is a PHP library for representing and converting dimensional units of measure. This is inspired by the [Measurement API](https://developer.apple.com/reference/foundation/nsmeasurement) in the Apple Foundation Framework. ## Installation The package can be installed via [Composer](https://getcomposer.org): ```shell composer require nmarfurt/measurements ``` ## Library Classes ### Unit `Unit` is the abstract superclass of units. Each instance of an `Unit` subclass consists of a symbol, which can be used to create string representations of `Measurement` objects. ### Dimension `Dimension` is an abstract subclass of `Unit` that represents unit families or a dimensional unit of measure, which can be converted into different units of the same type. Each instance of an `Dimension` subclass has a converter, which is used to represent the unit in terms of the dimension's base unit provided by the `baseUnit()` method. > The library provides concrete subclasses for many of the most common types of physical units (listed below). > If you need a custom unit type to represent a custom or derived unit, you can subclass `Dimension`. If you need to represent dimensionless units, subclass `Unit` directly. ### UnitConverter A `UnitConverter` describes how to convert a unit to and from the base unit of its dimension. `UnitConverterLinear` is a `UnitConverter` subclass for converting between units using a linear equation. You can define your own converters if needed. ### Measurement A `Measurement` object represents a measured quantity, using a unit of measure and a value. The `Measurement` class provides a programmatic interface to converting measurements into different units, as well as calculating the sum or difference between two measurements. `Measurement` objects are initialized with a `Unit` object and double value. They are immutable and cannot be changed after being created. > The library provides specific subclasses (so called Quantities) for measurements that correspond to the provided units (see the list below). ## Provided Units & Quantities The library provides concrete subclasses for many of the most common types of physical units: | Dimension Subclass | Description | Base Unit | Measurement Subclass | | ------------------ | ----------- | --------- | -------------------- | | UnitAcceleration | Unit of measure for acceleration | meters per second squared `m/s²` | Acceleration | UnitAngle | Unit of measure for planar angle and rotation | degrees `°` | Angle | UnitArea | Unit of measure for area | square meters `m²` | Area | UnitConcentrationMass | Unit of measure for concentration of mass | milligrams per deciliter `mg/dL` | ConcentrationMass | UnitDispersion | Unit of measure for dispersion | parts per million `ppm` | Dispersion | UnitDuration | Unit of measure for duration | seconds `sec` | Duration | UnitElectricCharge | Unit of measure for electric charge | coulombs `C` | ElectricCharge | UnitElectricCurrent | Unit of measure for electric current | amperes `A` | ElectricCurrent | UnitElectricPotentialDifference | Unit of measure for electric potential difference | volts `V` | ElectricPotentialDifference | UnitElectricResistance | Unit of measure for electric resistance | ohms `Ω` | ElectricResistance | UnitEnergy | Unit of measure for energy | joules `J` | Energy | UnitFrequency | Unit of measure for frequency | hertz `Hz` | Frequency | UnitFuelEfficiency | Unit of measure for fuel consumption | liters per 100 kilometers `L/100km` | FuelEfficiency | UnitIlluminance | Unit of measure for illuminance | lux `lx` | Illuminance | UnitLength | Unit of measure for length | meters `m` | Length | UnitMass | Unit of measure for mass | kilograms `kg` | Mass | UnitPower | Unit of measure for power | watts `W`| Power | UnitPressure | Unit of measure for pressure | newtons per square meter `N/m²`| Pressure | UnitRadioactivity | Unit of measure for radioactivity | becquerel `Bq`| Radioactivity | UnitSpeed | Unit of measure for speed | meters per second `m/s`| Speed | UnitTemperature | Unit of measure for temperature | kelvin `K`| Temperature | UnitVolume | Unit of measure for volume | liters `L`| Volume ## Usage ### Using Measurements You can define measurements as follows: ``` php use Measurements\Measurement; use Measurements\Units\UnitLength; use Measurements\Units\UnitDuration; $length = new Measurement(4.48, UnitLength::meters()); echo $length; // = 4.48 m $duration = new Measurement(1.5, UnitDuration::hours()); echo $duration; // = 1.5 hr ``` You may want to enforce the unit type of a measurement by using the provided measurement subclasses (_aka_ _Quantities_): ``` php use Measurements\Units\UnitLength; use Measurements\Units\UnitDuration; use Measurements\Quantities\Length; use Measurements\Quantities\Duration; $length = new Length(4.48, UnitLength::meters()); echo $length; // = 4.48 m $duration = new Duration(1.5, UnitDuration::hours()); echo $duration; // = 1.5 hr $invalid = new Length(4.48, UnitDuration::hours()); // Will throw a UnitException exception ``` The _Quantities_ objects also provide the benefit of an expressive syntax to create measurements. They make use of the `__callStatic()` magic-method to create a new instance by resolving the derived dimension. ``` php use Measurements\Quantities\Length; use Measurements\Quantities\Duration; $length = Length::meters(4.48); echo $length; // = 4.48 m $duration = Duration::hours(1.5); echo $duration; // = 1.5 hr $invalid = Length::hours(4.48); // Will throw a BadMethodCallException exception ``` Some of the _Measurement_ subclasses expose convenience methods to easily create instances from other measurements. ``` php use Measurements\Quantities\Length; use Measurements\Quantities\Duration; $distance = Length::kilometers(18); $time = Duration::hours(1); $speed = Speed::fromLengthAndDuration($distance, $time); echo $speed->toString(); // 5 m/s ``` ### Converting Measurements _Measurement_ objects of the same dimension can be converted from one unit of measure to another. ``` php use Measurements\Measurement; use Measurements\Units\UnitLength; $meters = new Measurement(4.48, UnitLength::meters()); $centimeters = $meters->convertTo(UnitLength::centimeters()); echo $centimeters; // = 448 cm ``` Measurements created as _Quantities_ objects also provide a short syntax to convert them. They make use of the `__call()` magic-method to resolve the derived dimension. ``` php use Measurements\Quantities\Length; $meters = Length::meters(4.48); $centimeters = $meters->toCentimeters(); echo $centimeters; // = 448 cm ``` ### Making Arithmetic Operations _Measurement_ objects support different operations, including `add` (`+`), `subtract` (`-`), `multiply` (`*`) and `divide` (`/`). Since _Measurement_ objects are immutable, new instances are returned. ``` php use Measurements\Measurement; use Measurements\Units\UnitLength; $first = new Measurement(4.48, UnitLength::meters()); $second = new Measurement(2.02, UnitLength::meters()); echo $first->add($second); // = 6.5 m echo $first->subtract($second); // = 2.46 m echo $first->multiplyBy($second); // = 9.0496 m echo $first->divideBy($second); // = 2.2178217822 m ``` Conversions are automatically applied while making operations on measurements with different units. The returned measurement is defined in the base unit. ``` php use Measurements\Measurement; use Measurements\Units\UnitLength; $decimeters = new Measurement(44.8, UnitLength::decimeters()); $centimeters = new Measurement(202, UnitLength::centimeters()); echo $decimeters->add($centimeters); // = 6.5 m echo $decimeters->subtract($centimeters); // = 2.46 m echo $decimeters->multiplyBy($centimeters); // = 9.0496 m echo $decimeters->divideBy($centimeters); // = 2.2178217822 m ``` It is also possible to make arithmetic operations on a measurement using values. ``` php use Measurements\Measurement; use Measurements\Units\UnitLength; $centimeters = new Measurement(42, UnitLength::centimeters()); echo $centimeters->addValue(8); // = 50 cm echo $centimeters->subtractValue(12); // = 30 cm echo $centimeters->multiplyByValue(2); // = 84 cm echo $centimeters->divideByValue(2); // = 21 cm ``` ### Working with Custom Units In addition to provided units, you can define custom units. Custom units can be initialized from a symbol and converter of an existing type or implemented as a class method of an existing type for additional convenience. You can also define your own `Dimension` subclass to represent an entirely new unit dimension. #### Initializing a Custom Unit with a Specified Symbol and Definition The simplest way to define a custom unit is to create a new instance of an existing `Dimension` subclass. For example, let define a _jump_ as a custom, nonstandard unit of length (1 jump = 1.82 m). You can create a new instance of `UnitLength` as follows: ``` php $jump = new UnitLength("jump", new UnitConverterLinear(1.82)); ``` #### Extending Existing Dimension Subclasses Alternatively, you can extend an existing `Dimension` subclass to define a new unit. For example, let define our new _jump_ unit as custom subclass: ``` php class UnitJump extends UnitLength { public static function jumps() { return new static("jump", new UnitConverterLinear(1.82)); } } ``` #### Creating a Custom Dimension Subclass You can create a new subclass of `Dimension` to describe a new unit dimension. For example, let define units for digital data. In computing and telecommunications, a unit of information is the capacity of some standard data storage system or communication channel, used to measure the capacities of other systems and channels. Bytes, or multiples thereof, are common units used to specify the sizes of computer files and the capacity of storage units. You can implement a `UnitDigitalData` class that defines units of digital information as follows: ``` php class UnitDigitalData extends Dimension { public static function baseUnit() { return static::bytes(); } public static function bytes() { return new UnitDigitalData("B", new UnitConverterLinear(1.0)); } public static function kilobytes() { return new UnitDigitalData("kB", new UnitConverterLinear(1000)); } public static function megabytes() { return new UnitDigitalData("MB", new UnitConverterLinear(1000000)); } public static function kibibytes() { return new UnitDigitalData("KiB", new UnitConverterLinear(1024)); } public static function mebibytes() { return new UnitDigitalData("MiB", new UnitConverterLinear(1048576)); } // ... } ``` ## Generating API Documentation ```shell phpdoc -d ./src/ -t ./doc/generated --template="xml" phpdocmd ./doc/generated/structure.xml doc/ ``` ## License This library is open-sourced software licensed under the [MIT license](http://opensource.org/licenses/MIT). <file_sep>/src/Quantities/Angle.php <?php namespace Measurements\Quantities; use Measurements\Unit; use Measurements\Measurement; use Measurements\Units\UnitAngle; use Measurements\Exceptions\UnitException; /** * The `Angle` class represents specific quantities of angle. * * @method static Angle degrees(float $value) * @method static Angle arcMinutes(float $value) * @method static Angle arcSeconds(float $value) * @method static Angle radians(float $value) * @method static Angle gradians(float $value) * @method static Angle revolutions(float $value) */ class Angle extends Measurement { /** * Initializes a new angle with a specified floating-point value and unit. * * @param double $value The measurement value. * @param Unit $unit The unit of measure. * * @throws \Measurements\Exceptions\UnitException */ public function __construct($value, Unit $unit) { if (!$unit instanceof UnitAngle) { throw new UnitException("Attempt to create an angle measurement from an invalid unit [$unit]!"); } parent::__construct($value, $unit); } } <file_sep>/tests/Units/UnitDurationTests.php <?php namespace Tests\Units; use PHPUnit\Framework\TestCase; use Measurements\Measurement; use Measurements\Units\UnitDuration; class UnitDurationTests extends TestCase { use InteractsWithUnits; /** @test */ public function it_defines_seconds_as_base_unit() { $this->assertTrue(UnitDuration::baseUnit() == UnitDuration::seconds(), "Duration should define seconds as its base unit."); } /** @test */ public function it_converts_durations() { $base = new Measurement(3600, UnitDuration::baseUnit()); $this->assertMeasurementEquals($base->convertTo(UnitDuration::seconds()), 3600, $base, "seconds"); $this->assertMeasurementEquals($base->convertTo(UnitDuration::minutes()), 60, $base, "minutes"); $this->assertMeasurementEquals($base->convertTo(UnitDuration::hours()), 1, $base, "hours"); } }<file_sep>/tests/UnitTests.php <?php namespace Tests; use PHPUnit\Framework\TestCase; use Measurements\Units\UnitLength; use Measurements\Units\UnitDuration; class UnitTests extends TestCase { /** @test */ public function units_can_be_checked_for_equality() { $meters = UnitLength::meters(); $kilometers = UnitLength::kilometers(); $hours = UnitDuration::hours(); $this->assertFalse($meters->isEqualTo($kilometers), "Meters unit should not be equal to kilometers unit."); $this->assertFalse($meters->isEqualTo($hours), "Meters unit should not be equal to hours unit."); $this->assertTrue($meters->isEqualTo(UnitLength::meters()), "An instance of meters unit should be equal to another instance of meters unit."); } }<file_sep>/src/Units/UnitAngle.php <?php namespace Measurements\Units; use Measurements\Dimension; use Measurements\Converters\UnitConverterLinear; /** * The `UnitAngle` class encapsulates units of measure for rotation. * You typically use instances of `UnitAngle` to represent specific quantities of planar angle using the `Measurement` class. * * Angle is a quantity of rotation. The SI unit for angle is the radian (rad), which is dimensionless and defined to be the the angle subtended by an arc that is equal in length to the radius of a circle. * Angle is also commonly expressed in terms of degrees (°) and revolutions (rev). * * The base unit of `UnitAngle` is defined as degrees. */ class UnitAngle extends Dimension { const SYMBOL_DEGREES = "°"; const SYMBOL_ARC_MINUTES = "ʹ"; const SYMBOL_ARC_SECONDS = "″"; const SYMBOL_RADIANS = "rad"; const SYMBOL_GRADIANS = "grad"; const SYMBOL_REVOLUTIONS = "rev"; const COEFFICIENT_DEGREES = 1.0; const COEFFICIENT_ARC_MINUTES = 0.016667; const COEFFICIENT_ARC_SECONDS = 0.00027778; const COEFFICIENT_RADIANS = 57.2958; const COEFFICIENT_GRADIANS = 0.9; const COEFFICIENT_REVOLUTIONS = 6.28319; /** * Returns the base unit of rotation, equal to degrees. * * @return UnitAngle The base unit of rotation. */ public static function baseUnit() { return self::degrees(); } /** * Returns the degrees unit of rotation. * * @return UnitAngle The degrees unit of rotation. */ public static function degrees(): UnitAngle { return new static(static::SYMBOL_DEGREES, new UnitConverterLinear(static::COEFFICIENT_DEGREES)); } /** * Returns the arc minutes unit of rotation. * * @return UnitAngle The arc minutes unit of rotation. */ public static function arcMinutes(): UnitAngle { return new static(static::SYMBOL_ARC_MINUTES, new UnitConverterLinear(static::COEFFICIENT_ARC_MINUTES)); } /** * Returns the arc seconds unit of rotation. * * @return UnitAngle The arc seconds unit of rotation. */ public static function arcSeconds(): UnitAngle { return new static(static::SYMBOL_ARC_SECONDS, new UnitConverterLinear(static::COEFFICIENT_ARC_SECONDS)); } /** * Returns the radians unit of rotation. * * @return UnitAngle The radians unit of rotation. */ public static function radians(): UnitAngle { return new static(static::SYMBOL_RADIANS, new UnitConverterLinear(static::COEFFICIENT_RADIANS)); } /** * Returns the gradians unit of rotation. * * @return UnitAngle The gradians unit of rotation. */ public static function gradians(): UnitAngle { return new static(static::SYMBOL_GRADIANS, new UnitConverterLinear(static::COEFFICIENT_GRADIANS)); } /** * Returns the revolutions unit of rotation. * * @return UnitAngle The revolutions unit of rotation. */ public static function revolutions(): UnitAngle { return new static(static::SYMBOL_REVOLUTIONS, new UnitConverterLinear(static::COEFFICIENT_REVOLUTIONS)); } } <file_sep>/src/Converters/UnitConverterLinear.php <?php namespace Measurements\Converters; use Measurements\UnitConverter; /** * `UnitConverterLinear` is a `UnitConverter` subclass for converting between units using a linear equation. * A linear equation for unit conversion takes the form y = mx + b, such that: * - y is the value in terms of the base unit of the dimension * - m is the known coefficient used for this unit's conversion * - x is the value in terms of the unit on which this method is called * - b is the known constant used for this unit's conversion */ class UnitConverterLinear implements UnitConverter { /** * The coefficient used in the linear unit conversion calculation. * * @var double */ protected $coefficient; /** * The constant used in the linear unit conversion calculation. * * @var double */ protected $constant; /** * Initializes the unit converter with the specified coefficient and constant. * * @param double $coefficient The coefficient used in the linear unit conversion calculation. * @param double $constant The constant used in the linear unit conversion calculation. */ public function __construct($coefficient, $constant = 0.0) { $this->coefficient = (double)$coefficient; $this->constant = (double)$constant; } public function baseUnitValueFromValue($value) { // Performs the conversion in the form of y = mx + b, where x represents the value passed in and y represents the value returned. return (double)$value * $this->coefficient + $this->constant; } public function valueFromBaseUnitValue($baseUnitValue) { // Performs the inverse conversion in the form of x = (y - b) / m, where y represents the value passed in and x represents the value returned. return ((double)$baseUnitValue - $this->constant) / $this->coefficient; } } <file_sep>/doc/Measurements-Units-UnitArea.md Measurements\Units\UnitArea =============== The `UnitArea` class encapsulates units of measure for area. You typically use instances of `UnitArea` to represent specific quantities of area using the `Measurement` class. Area is a quantity of extent in two dimensions. Area can be expressed by SI derived units in terms of square meters (m2). Area is also commonly measured in square feet (ft2) and acres (ac). The base unit of `UnitArea` is defined as square meters. * Class name: UnitArea * Namespace: Measurements\Units * Parent class: [Measurements\Dimension](Measurements-Dimension.md) Constants ---------- ### SYMBOL_SQUARE_MEGAMETERS const SYMBOL_SQUARE_MEGAMETERS = "Mm²" ### SYMBOL_SQUARE_KILOMETERS const SYMBOL_SQUARE_KILOMETERS = "km²" ### SYMBOL_SQUARE_METERS const SYMBOL_SQUARE_METERS = "m²" ### SYMBOL_SQUARE_CENTIMETERS const SYMBOL_SQUARE_CENTIMETERS = "cm²" ### SYMBOL_SQUARE_MILLIMETERS const SYMBOL_SQUARE_MILLIMETERS = "mm²" ### SYMBOL_SQUARE_MICROMETERS const SYMBOL_SQUARE_MICROMETERS = "µm²" ### SYMBOL_SQUARE_NANOMETERS const SYMBOL_SQUARE_NANOMETERS = "nm²" ### SYMBOL_SQUARE_INCHES const SYMBOL_SQUARE_INCHES = "in²" ### SYMBOL_SQUARE_FEET const SYMBOL_SQUARE_FEET = "ft²" ### SYMBOL_SQUARE_YARDS const SYMBOL_SQUARE_YARDS = "yd²" ### SYMBOL_SQUARE_MILES const SYMBOL_SQUARE_MILES = "mi²" ### SYMBOL_SQUARE_ACRES const SYMBOL_SQUARE_ACRES = "ac" ### SYMBOL_SQUARE_ARES const SYMBOL_SQUARE_ARES = "a" ### SYMBOL_SQUARE_HECTARES const SYMBOL_SQUARE_HECTARES = "ha" ### COEFFICIENT_SQUARE_MEGAMETERS const COEFFICIENT_SQUARE_MEGAMETERS = 1000000000000.0 ### COEFFICIENT_SQUARE_KILOMETERS const COEFFICIENT_SQUARE_KILOMETERS = 1000000.0 ### COEFFICIENT_SQUARE_METERS const COEFFICIENT_SQUARE_METERS = 1.0 ### COEFFICIENT_SQUARE_CENTIMETERS const COEFFICIENT_SQUARE_CENTIMETERS = 0.0001 ### COEFFICIENT_SQUARE_MILLIMETERS const COEFFICIENT_SQUARE_MILLIMETERS = 1.0E-6 ### COEFFICIENT_SQUARE_MICROMETERS const COEFFICIENT_SQUARE_MICROMETERS = 1.0E-12 ### COEFFICIENT_SQUARE_NANOMETERS const COEFFICIENT_SQUARE_NANOMETERS = 1.0E-18 ### COEFFICIENT_SQUARE_INCHES const COEFFICIENT_SQUARE_INCHES = 0.00064516 ### COEFFICIENT_SQUARE_FEET const COEFFICIENT_SQUARE_FEET = 0.092903 ### COEFFICIENT_SQUARE_YARDS const COEFFICIENT_SQUARE_YARDS = 0.836127 ### COEFFICIENT_SQUARE_MILES const COEFFICIENT_SQUARE_MILES = 2590000.0 ### COEFFICIENT_SQUARE_ACRES const COEFFICIENT_SQUARE_ACRES = 4046.86 ### COEFFICIENT_SQUARE_ARES const COEFFICIENT_SQUARE_ARES = 100.0 ### COEFFICIENT_SQUARE_HECTARES const COEFFICIENT_SQUARE_HECTARES = 10000.0 Properties ---------- ### $converter protected \Measurements\UnitConverter $converter The converter used to represent the unit in terms of the dimension's base unit. * Visibility: **protected** ### $symbol protected string $symbol The symbolic representation of the unit. * Visibility: **protected** Methods ------- ### baseUnit mixed Measurements\BaseUnitConvertible::baseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is **static**. * This method is defined by [Measurements\BaseUnitConvertible](Measurements-BaseUnitConvertible.md) ### squareMegameters \Measurements\Units\UnitArea Measurements\Units\UnitArea::squareMegameters() Returns the square megameters unit of area. * Visibility: **public** * This method is **static**. ### squareKilometers \Measurements\Units\UnitArea Measurements\Units\UnitArea::squareKilometers() Returns the square kilometers unit of area. * Visibility: **public** * This method is **static**. ### squareMeters \Measurements\Units\UnitArea Measurements\Units\UnitArea::squareMeters() Returns the square meters unit of area. * Visibility: **public** * This method is **static**. ### squareCentimeters \Measurements\Units\UnitArea Measurements\Units\UnitArea::squareCentimeters() Returns the square centimeters unit of area. * Visibility: **public** * This method is **static**. ### squareMillimeters \Measurements\Units\UnitArea Measurements\Units\UnitArea::squareMillimeters() Returns the square millimeters unit of area. * Visibility: **public** * This method is **static**. ### squareMicrometers \Measurements\Units\UnitArea Measurements\Units\UnitArea::squareMicrometers() Returns the square micrometers unit of area. * Visibility: **public** * This method is **static**. ### squareNanometers \Measurements\Units\UnitArea Measurements\Units\UnitArea::squareNanometers() Returns the square nanometers unit of area. * Visibility: **public** * This method is **static**. ### squareInches \Measurements\Units\UnitArea Measurements\Units\UnitArea::squareInches() Returns the square inches unit of area. * Visibility: **public** * This method is **static**. ### squareFeet \Measurements\Units\UnitArea Measurements\Units\UnitArea::squareFeet() Returns the square feet unit of area. * Visibility: **public** * This method is **static**. ### squareYards \Measurements\Units\UnitArea Measurements\Units\UnitArea::squareYards() Returns the square yards unit of area. * Visibility: **public** * This method is **static**. ### squareMiles \Measurements\Units\UnitArea Measurements\Units\UnitArea::squareMiles() Returns the square miles unit of area. * Visibility: **public** * This method is **static**. ### acres \Measurements\Units\UnitArea Measurements\Units\UnitArea::acres() Returns the acres unit of area. * Visibility: **public** * This method is **static**. ### ares \Measurements\Units\UnitArea Measurements\Units\UnitArea::ares() Returns the ares unit of area. * Visibility: **public** * This method is **static**. ### hectares \Measurements\Units\UnitArea Measurements\Units\UnitArea::hectares() Returns the hectares unit of area. * Visibility: **public** * This method is **static**. ### __construct mixed Measurements\Unit::__construct(string $symbol) Initializes a new unit with the specified symbol. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) #### Arguments * $symbol **string** - &lt;p&gt;The symbolic representation of the unit.&lt;/p&gt; ### converter \Measurements\UnitConverter Measurements\Dimension::converter() Returns the unit converter used to represent the unit in terms of the dimension's base unit. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### getBaseUnit mixed Measurements\Dimension::getBaseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### symbol string Measurements\Unit::symbol() Return the symbolic representation of the unit. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) ### isEqualTo boolean Measurements\Equatable::isEqualTo(mixed $other) Returns a boolean value that indicates whether the receiver is equal to another given object. * Visibility: **public** * This method is defined by [Measurements\Equatable](Measurements-Equatable.md) #### Arguments * $other **mixed** - &lt;p&gt;The object with which to compare the receiver.&lt;/p&gt; ### __toString string Measurements\Unit::__toString() Converts the unit to its string representation. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) <file_sep>/src/Units/UnitElectricResistance.php <?php namespace Measurements\Units; use Measurements\Dimension; use Measurements\Converters\UnitConverterLinear; /** * The `UnitElectricResistance` class encapsulates units of measure for electric resistance. * You typically use instances of `UnitElectricResistance` to represent specific quantities of electric resistance using the `Measurement` class. * * Electric resistance is the difficulty of passing an electric current through a conductor. * The SI unit for electric resistance is the ohm (Ω), which is derived as the electric resistance that produces one ampere of current between two points in conductor with one volt of electric resistance (1Ω = 1V/1A). * * The base unit of `UnitElectricResistance` is defined as coulombs. */ class UnitElectricResistance extends Dimension { const SYMBOL_MEGAOHMS = "MΩ"; const SYMBOL_KILOOHMS = "kΩ"; const SYMBOL_OHMS = "Ω"; const SYMBOL_MILLIOHMS = "mΩ"; const SYMBOL_MICROOHMS = "µΩ"; const COEFFICIENT_MEGAOHMS = 1E+6; const COEFFICIENT_KILOOHMS = 1000.0; const COEFFICIENT_OHMS = 1.0; const COEFFICIENT_MILLIOHMS = 0.001; const COEFFICIENT_MICROOHMS = 1E-6; /** * Returns the base unit of electric resistance, equal to ohms. * * @return UnitElectricResistance The base unit of electric resistance. */ public static function baseUnit() { return self::ohms(); } /** * Returns the megaohms unit of electric resistance. * * @return UnitElectricResistance The megaohms unit of electric resistance. */ public static function megaohms(): UnitElectricResistance { return new static(static::SYMBOL_MEGAOHMS, new UnitConverterLinear(static::COEFFICIENT_MEGAOHMS)); } /** * Returns the kiloohms unit of electric resistance. * * @return UnitElectricResistance The kiloohms unit of electric resistance. */ public static function kiloohms(): UnitElectricResistance { return new static(static::SYMBOL_KILOOHMS, new UnitConverterLinear(static::COEFFICIENT_KILOOHMS)); } /** * Returns the ohms unit of electric resistance. * * @return UnitElectricResistance The ohms unit of electric resistance. */ public static function ohms(): UnitElectricResistance { return new static(static::SYMBOL_OHMS, new UnitConverterLinear(static::COEFFICIENT_OHMS)); } /** * Returns the milliohms unit of electric resistance. * * @return UnitElectricResistance The milliohms unit of electric resistance. */ public static function milliohms(): UnitElectricResistance { return new static(static::SYMBOL_MILLIOHMS, new UnitConverterLinear(static::COEFFICIENT_MILLIOHMS)); } /** * Returns the microohms unit of electric resistance. * * @return UnitElectricResistance The microohms unit of electric resistance. */ public static function microohms(): UnitElectricResistance { return new static(static::SYMBOL_MICROOHMS, new UnitConverterLinear(static::COEFFICIENT_MICROOHMS)); } } <file_sep>/doc/Measurements-Units-UnitFuelEfficiency.md Measurements\Units\UnitFuelEfficiency =============== The `UnitFuelEfficiency` class encapsulates units of measure for fuel efficiency. You typically use instances of `UnitFuelEfficiency` to represent specific quantities of fuel efficiency using the `Measurement` class. Fuel efficiency corresponds to the thermal efficiency of a process that converts the chemical potential energy of a fuel into kinetic energy. Fuel efficiency can be expressed by SI derived units in terms of cubic meters per meter (m3/m), but is more commonly expressed in terms of liters per kilometer (L/km) and miles per gallon (mpg). The base unit of `UnitFuelEfficiency` is defined as liters per 100 kilometers. * Class name: UnitFuelEfficiency * Namespace: Measurements\Units * Parent class: [Measurements\Dimension](Measurements-Dimension.md) Constants ---------- ### SYMBOL_LITERS_PER_100_KILOMETERS const SYMBOL_LITERS_PER_100_KILOMETERS = "L/100km" ### SYMBOL_MILES_PER_GALLON const SYMBOL_MILES_PER_GALLON = "mpg" ### SYMBOL_MILES_PER_IMPERIAL_GALLON const SYMBOL_MILES_PER_IMPERIAL_GALLON = "mpg" ### COEFFICIENT_LITERS_PER_100_KILOMETERS const COEFFICIENT_LITERS_PER_100_KILOMETERS = 1.0 ### COEFFICIENT_MILES_PER_GALLON const COEFFICIENT_MILES_PER_GALLON = 235.215 ### COEFFICIENT_MILES_PER_IMPERIAL_GALLON const COEFFICIENT_MILES_PER_IMPERIAL_GALLON = 282.481 Properties ---------- ### $converter protected \Measurements\UnitConverter $converter The converter used to represent the unit in terms of the dimension's base unit. * Visibility: **protected** ### $symbol protected string $symbol The symbolic representation of the unit. * Visibility: **protected** Methods ------- ### baseUnit mixed Measurements\BaseUnitConvertible::baseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is **static**. * This method is defined by [Measurements\BaseUnitConvertible](Measurements-BaseUnitConvertible.md) ### litersPer100Kilometers \Measurements\Units\UnitFuelEfficiency Measurements\Units\UnitFuelEfficiency::litersPer100Kilometers() Returns the liter per 100 kilometers unit of fuel efficiency. * Visibility: **public** * This method is **static**. ### milesPerGallon \Measurements\Units\UnitFuelEfficiency Measurements\Units\UnitFuelEfficiency::milesPerGallon() Returns the miles per gallon unit of fuel efficiency. * Visibility: **public** * This method is **static**. ### milesPerImperialGallon \Measurements\Units\UnitFuelEfficiency Measurements\Units\UnitFuelEfficiency::milesPerImperialGallon() Returns the miles per imperial gallon unit of fuel efficiency. * Visibility: **public** * This method is **static**. ### __construct mixed Measurements\Unit::__construct(string $symbol) Initializes a new unit with the specified symbol. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) #### Arguments * $symbol **string** - &lt;p&gt;The symbolic representation of the unit.&lt;/p&gt; ### converter \Measurements\UnitConverter Measurements\Dimension::converter() Returns the unit converter used to represent the unit in terms of the dimension's base unit. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### getBaseUnit mixed Measurements\Dimension::getBaseUnit() Returns the base unit of the dimension. * Visibility: **public** * This method is defined by [Measurements\Dimension](Measurements-Dimension.md) ### symbol string Measurements\Unit::symbol() Return the symbolic representation of the unit. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md) ### isEqualTo boolean Measurements\Equatable::isEqualTo(mixed $other) Returns a boolean value that indicates whether the receiver is equal to another given object. * Visibility: **public** * This method is defined by [Measurements\Equatable](Measurements-Equatable.md) #### Arguments * $other **mixed** - &lt;p&gt;The object with which to compare the receiver.&lt;/p&gt; ### __toString string Measurements\Unit::__toString() Converts the unit to its string representation. * Visibility: **public** * This method is defined by [Measurements\Unit](Measurements-Unit.md)
bd1a64f09b957726311d0a5e44a996e284c8c26b
[ "Markdown", "YAML", "PHP" ]
116
Markdown
marfurt/measurements
2b91efd5a07f55620f8090d6ad88e4322a309689
de2bb653f7ebdb8f27efe1627079983de99858d4
refs/heads/master
<repo_name>Sebb767/AnguLog<file_sep>/angulog/html.php <!DOCTYPE html><!-- This is the HTML output of angulog. It's outsourced to allow minification. --> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="AnguLog - A logviewer app built with angular"> <meta name="author" content="<NAME>"> <title>AnguLog Logviewer for <?php echo $config->appname; ?></title> <!-- inline style sheet --> <style> <?php include('angulog.css'); ?>/*-#!css-*/ </style> <script>var config=<?php echo \Sebb767\AnguLog\arrayToJS(array( 'version' => AL_VERSION, 'refresh_time' => $config->refreshTime, 'logged_in' => $config->checkLogin(), 'substituteNearDates' => $config->substituteNearDates ? '1' : '', 'dateFormat' => $config->dateFormat, )); ?>; /*-#!js-*/ <?php include('external/angular.min.js'); ?> <?php include('external/moment.min.js'); ?> /* actual js code */ <?php include('angulog.min.js'); ?> </script> </head> <body ng-app="AnguLog"> <nav class="navbar"> <div class="navbar-container"> <div class="appname"><?php echo $config->appname; ?></div> <nav id="navbar" class=""> <ul class="navbar-nav" ng-controller="logCtrlController as lc"> <li ng-show="active"><a ng-click="toggleRefresh()">Refresh {{ refreshing ? 'On' : 'Off' }}</a></li> <li ng-click=""><a href='javascript:alert("AnguLog Version "+config.version+"\n"+ "(c) <NAME> <<EMAIL>>, 2015\n"+ "This product is licensed under the GNU GPL.\n\n"+ "Third-Party Products:\n"+ "AngularJS v1.3.13; MIT License\n"+ "moment.js v2.9.0; MIT License\n\n"+ "If you like this product, visist the Github page and get involved:\n"+ "https://github.com/Sebb767/AnguLog");/* not the good style, I know, but ng had a bug here */'>Impress</a></li> <li ng-hide="active"><a href="https://github.com/Sebb767/AnguLog" target="_blank">AnguLog Website</a></li> <li ng-show="active"><a ng-click="logout()">Log out</a></li> </ul> </nav><!--/.nav-collapse --> </div> <span class="powered-by"> <!--<span ng-class="[statusCSS()]">{{ status }}</span>--> <br> <span class="powered-by-al">Powered by</span>&nbsp; <a class="al-version" href="https://github.com/Sebb767/AnguLog" target="_blank">AnguLog <?php echo AL_VERSION; ?></a> </span> </nav> <div class="content-error" ng-controller="logController" ng-show="active"> <div ng-repeat="item in data" ng-class="['error-container', levelToCSS(item.level) ]"> <div class="error-box">{{ item.error }}</div> <div class="error-details"> <span ng-show="(item.file !== undefined && item.file != null && item.file != '')"> In <span class="error-file">{{ ::item.file }}</span> <span ng-show="(item.line !== undefined && item.line != null && item.line != '')"> on <span class="error-line">line {{ ::item.line }}</span> </span>. </span> <span ng-hide="(item.file !== undefined && item.file != null && item.file != '')" class="error-no-data"> No data available</span> <span class="error-time">{{ timeFormat(item.time) }}</span> </div> </div> <br> <div class="ld-more">{{ lmdiv }}</div> </div> <div class="content signin" ng-controller="loginController" ng-show="active" ng-class="['content', 'signin', trying ? 'signin-onwait' : 'signin-normal']"> <form class="signin-form" ng-submit="login()" ui-keypress="{13:'login($event)'}" > <h2 class="form-signin-heading">Please sign in</h2> <div type="text" class="input input-error" ng-show="showerror"><span class="signin-error">Error!</span> {{ error }}</div> <input type="text" id="username" class="input" placeholder="Username" ng-model="name" required="" autofocus="" ng-disabled="trying"> <input type="<PASSWORD>" id="password" class="input" placeholder="<PASSWORD>" ng-model="pw" required="" ng-disabled="trying"> <button class="input input-btn" type="submit" ng-disabled="trying">Sign in</button> </form> </div> </body></html><file_sep>/angulog/code.php <?php // This file contains the main code namespace Sebb767\AnguLog; @session_start(); // start session in case it's not done already $config = new config(); // create config if(!$config->noHeader) header('X-Powered-By', 'AnguLog '.AL_VERSION); // some self-promotion // // helper functions // // print error in json format and exit function error($msg, $exit = true, $reload = false) { echo json_encode(array('error' => $msg, 'success' => false, 'reload' => $reload)); if($exit) exit; } // give data in json format and exit function success($data = null, $exit = true) { echo json_encode(array( 'success' => true, 'error' => '', 'reload' => false, 'data' => $data )); if($exit) exit; } // function to create an error data set function eds($error, $level, $time, $file = null, $line = null) { return array( 'id' => $time.'+'.hash('crc32', $error), // create id 'error' => $error, 'level' => $level, 'time' => $time, 'file' => $file, 'line' => $line ); } // function to get an array element or return a default value function gt(&$array, $index, $default = null) { if(isset($array[$index])) // check wether elem exists return $array[$index]; return $default; // return default } // function to initialize and execute log reader function readLogData() { // create cfg $cfg = new config(); // create the logreader; read+return the data return $cfg->modes[$cfg->mode]($cfg)->readData(); } // convert id [timestamp]+[crc32] to array function idToData($id, $cmp = null) { return array( substr($id, 0, -9), // timestamp substr($id, -8) ); } // compares an $id to an id-string function idCmp($id, $cmp) { return $id[0] == substr($cmp, 0, -9) && $id[1] == substr($cmp, -8); } // converts an array of values to a js object function arrayToJS($array) { $ret = '{'; foreach ($array as $name => $value) { $ret .= $name.':\''.addslashes($value).'\','; } return substr($ret, 0, -1). // remove last , '}'; } // // API // if(isset($_GET['api'])) // wether there is an API function called { if(!$config->noHeader) header('Content-Type', 'text/json'); // API will >always< output json and exit in this closure switch ($_GET['api']) { case 'login': // log in to the user interface //for($i = 0; $i < 1e7; $i++) echo ''; // angular.js sends post data in json format so that php doesn't recognize it $post = json_decode(file_get_contents('php:/'.'/input'), true); // stupid angular! ; . is for minification if(!isset($post['name']) || !isset($post['pw'])) // check for supplied data { error('You have to give username and password!'); } else { if($config->login($post['name'], $post['pw'])) // call the user-supplied login function { $_SESSION[$config->sessionName] = true; success(); } else { error('Wrong username or password!'); } } break; case 'logout': // log out the user $config->logout(); success(); break; case 'get': // query data if(!$config->checkLogin()) error('You need to be logged in for this!', true, true); if($bt = gt($_GET, 'bottom', false)) // get older entries // (older than ?bottom) { $bt = idToData($bt); $data = readLogData(); $c = count($data); for($i = 0; $i < $c; $i++) { if(idCmp($bt, $data[$i]['id'])) // found our bottom element { success(array_slice($data, ++$i, $config->loadCount)); } } error('No such error! (-> '.$bt[0].'+'.$bt[1].')'); } if($bt = gt($_GET, 'after', false)) // get new entries after ?after { $bt = idToData($bt); $data = readLogData(); $c = count($data); for($i = 0; $i < $c; $i++) { if(idCmp($bt, $data[$i]['id'])) // found the last element the client has { success(array_slice($data, 0, $i)); // return newer entries } } error('No such error! (-> '.$bt[0].'+'.$bt[1].')'); } // return last 'initialCount' errors (initial request) success(array_slice(readLogData(), 0, $config->initialCount)); break; case 'version': success(AL_VERSION); break; default: error('Invalid API function: '.htmlentities($_GET['api'])); break; } // the app should have exited with a json response by now! throw new Exception("API didn't exit with JSON response!\nPlease file a bug report."); } <file_sep>/angulog/angulog.php <?php namespace Sebb767\AnguLog; // // configuration // class config { public $appname = 'myApp'; // Name der App public $impress = '/impressum'; // URL zum Impressum public $mode = 'php-error-log'; // which mode to use. public $substituteNearDates = true; // wether to replace todays and // yesterdays dates with the respective phrase public $dateFormat = 'Do MMMM YYYY, H:mm:ss'; // format for log dates public $initialCount = 50; // how many errors to return on the initial request public $loadCount = 25; // how many entries will be loaded by default when // requesting older errors public $refreshTime = 400; // time between refreshes in ms public $noHeader = false; // skip header calls. these may cause 500 errors // This is the array for the available modes // To create a mode, implement a class that implements ILogInterpreter // The PHP Log Interpreter is done here as example // you may include php files in your closure public $modes = array(); public function __construct() // initialize our mode array { $this->modes['php-error-log'] = function($config) { // file is included below to ease minification return (new PhpLogReader($config)); //'/var/log/php-fpm.log' }; } public $sessionName = 'AL-Session-Data'; // the name to use as key in the session array // Function to login a user; return true when successful public function login($username, $password) { return $username == 'root' && $password == '<PASSWORD>'; } // logout - self explaining, kinda public function logout() { $_SESSION[$this->sessionName] = false; } // check wether an user is logged in public function checkLogin() { $config = new config(); return (isset($_SESSION[$config->sessionName]) && $_SESSION[$config->sessionName]); } } // // interface for log readers (use it as reference, don't edit if you want this working) // interface ILogReader { // Read the data and return it public function readData(); /* You have to return arrays of the following array * [] => ( * 'id' => "[timestamp]+[crc32 of error msg]", * 'error' => 'message of your error', * 'level' => [importance as int], * 'time' => [errors timestamp as int], * (optional) 'file' => [Filename], * (optional) 'line' => [Line w/ Error] * ) * take a look at the helper function 'eds'. You have to return the data * in inverse time order, so newest = [0], oldest = [n-1]. **/ } // // code - do not change anything below here if you aren't sure what you're doing #!minify define('AL_VERSION', '0.1.0-testing'); // Version: Major.Minor.Bugfix include('php-logreader.php'); include('code.php'); // // HTML // include('html.php'); <file_sep>/angulog/php-logreader.php <?php namespace Sebb767\AnguLog; class PhpLogReader implements ILogReader { private $cfg = null; private $log = null; public function __construct($config, $file = null) { $this->cfg = $config; if($file == null) $this->log = ini_get('error_log'); // fall back to error log if else // no file is given $this->log = $file; } public function readData() { $errors = explode("\n", file_get_contents($this->log)); // get all errors $data = array(); $matches = array(); // parse each error by line $count = count($errors); for($i = 0; $i < $count; $i++) { $e = trim($errors[$i]); if(empty($e)) continue; // empty line $current_count = count($data); $matches = array(); // clear matches // check for default php error [A-Za-z0-9/\\-+\s]+ $s = '\\s+'; // whitespace identifier if(preg_match(";^\\[([A-Za-z0-9-:\\./\\s]+)\\]$s(PHP$s)?([A-Za-z$s]+):$s(.*?)(\\s+in$s(.*)$s"."on$s"."line$s(\\d+))?".'$;i', $e, $matches)) { $level = 0; switch(trim(strtolower($matches[3]))) { case 'notice': $level = 200; break; case 'warning': $level = 300; break; case 'parse error': $level = 400; break; case 'fatal error': $level = 500; break; default: $level = 200; // default to notice break; } //function eds($error, $level, $time, $file = null, $line = null) $data[] = \Sebb767\AnguLog\eds($matches[4], $level, strtotime($matches[1]), \Sebb767\AnguLog\gt($matches, 6, ''), \Sebb767\AnguLog\gt($matches, 7, '')); } elseif(preg_match(";^\\[([A-Za-z0-9-:\\./\\s]+)\\]{$s}PHP{$s}(Stack{$s}trace\:)".'$;i', $e, $matches) && $current_count != 0) // php stacktrace? { $data[$current_count-1]['error'] .= "\n".$matches[2]; $data[$current_count-1]['stack-trace'] = true; } /* */ elseif(preg_match(";^\\[([A-Za-z0-9-:\\./\\s]+)\\]{$s}PHP{$s}(Stack{$s}trace\:)".'$;i', $e, $matches) && $current_count != 0) // php stacktrace? { $data[$current_count-1]['error'] .= "\n".$matches[2]; $data[$current_count-1]['stack-trace'] = true; } elseif(preg_match(";^\\[([A-Za-z0-9-:\\./\\s]+)\\]{$s}PHP$s(\\d+\\.{$s}.+)".'$;i', $e, $matches) && $current_count != 0 && isset($data[$current_count-1]['stack-trace'])) { $data[$current_count-1]['error'] .= "\n".$matches[2]; } else { // no standard message -> "[time] custom message" // will default to notice $br = strpos($e, ']'); if($br && $time = strtotime(substr($e, 1, $br-1))) // valid date { $data[] = \Sebb767\AnguLog\eds(substr($e, $br+1), 200, $time); } else // invalid date / line -> add to previous { $data[count($data)-1]['error'] .= "\n".$e; } } } // reverse and return data return array_reverse($data); } }<file_sep>/README.md AnguLog ======= A single-file, extendable, easily integrating log viewer with auto-update function. Features -------- - **Single file** - Just place the 172KB file on your Server and there you go! - **Authentification** - Simple authentification which you can integrate into your environment with two lines of code - **Easily extendable** - It's simple to write a parser for you very own log - **Auto-update** - Get new errors blazingly fast, no need to reload - **Easy configureable** - Configure everything you need to at the beginning of the file How to install -------------- Just get the latest version from [builds](../../tree/master/compiled/) and copy it to your server. It will read the php error log defined in the php.ini by default. The standard username is `root` and the password `<PASSWORD>`. Upcoming Features ----------------- - select log server - better error handling - auto-unloading of too many errors - some more features How to support development -------------------------- Send a mail to [<EMAIL>](mailto:<EMAIL>) to show me that you use this project :) <file_sep>/angulog/angulog.js var app = angular.module('AnguLog',[], function($interpolateProvider) { // here was a config option once ... }); app.controller("loginController", ['$scope','$http', '$rootScope', function($scope, $http, $rootScope) { $scope.active = !config.logged_in; $scope.error = ''; // login errors $scope.showerror = false; // wether to show the error field of the login mask var trying = false; // wether the ctrl is currently trying to login $scope.login = function() { if($scope.trying) return; $scope.trying = true; $http.post('?api=login', { name: $scope.name, pw: $scope.pw }). // try to log in success(function(data, status, headers, config) { $scope.trying = false; if(data.success) // logged in { $scope.deactivate(); $rootScope.$emit('logged_in'); } else { $scope.showerror = true; $scope.error = data.error; } }).error(function(data, status, headers, config) { alert("Server Error (" + status + ")!\nPlease retry."); $scope.trying = false; }); }; // reactivate this controller when the user logs out $rootScope.$on('logged_out', function(event, data) { $scope.activate(); }); // called to hide & deactivate this $scope.deactivate = function() { $scope.pw = ''; // reset password $scope.showerror = false; $scope.active = false; }; // reactivate this $scope.activate = function() { $scope.active = true; }; }]); app.controller("logController", ['$scope','$http', '$rootScope', '$window', 'API', '$timeout', '$sce', function($scope, $http, $rootScope, $window, api, $timeout, $sce) { // Check for new errors $scope.refreshing = false; $scope.stopRefresh = function () { $scope.refreshing = false; $rootScope.$emit('refresh_off'); }; $scope.startRefresh = function () { if($scope.refreshing) return; // we have our interval running $scope.refreshing = true; $rootScope.$emit('refresh_on'); if(!refreshRunning) $scope.refresh(); }; $scope.toggleRefresh = function () { if($scope.refreshing) $scope.stopRefresh(); else $scope.startRefresh(); }; // load more div text $scope.lmdiv = 'Loading more ...'; // wether a request is running refreshRunning = false; // newest request $scope.newestRequest = ''; // lowest entry $scope.oldestRequest = ''; // some example data $scope.data = [];/*[ { level: 100, line: 20, file: 'index.php', error: 'I\'m just a Info and I\'m here to show you how multiline works. I\'m just a Info and I\'m here to show you how multiline works. I\'m just a Info and I\'m here to show you how multiline works. I\'m just a Info and I\'m here to show you how multiline works. I\'m just a Info and I\'m here to show you how multiline works. I\'m just a Info and I\'m here to show you how multiline works. I\'m just a Info and I\'m here to show you how multiline works. I\'m just a Info and I\'m here to show you how multiline works. I\'m just a Info and I\'m here to show you how multiline works. I\'m just a Info and I\'m here to show you how multiline works. I\'m just a Info and I\'m here to show you how multiline works. I\'m just a Info and I\'m here to show you how multiline works.', time: 12312312 }, { level: 200, line: 22, file: 'index.php', error: 'You need to notice me, but I\'m not important.', time: 12351223423 }, { level: 300, line: 22, file: 'index.php', error: 'I\'m a warning, better do something.', time: 13323123423 }, { level: 400, line: 22, file: 'index.php', error: 'Oh Snap! There was an error!', time: 1234122123 }, { level: 500, line: 12, file: 'index.php', error: 'Critical! Your App is down!', time: 12312332 } ];/**/ // actually refresh $scope.refresh = function() { if(!$scope.refreshing) return; // don't refresh if we shouldn't if($scope.newestRequest === '') // initial request { api.request({ api: 'get' }, function(data) { $scope.data = data; $scope.newestRequest = data[0].id; $scope.refresh(); // inital refresh $scope.oldestRequest = data[data.length-1].id; }, $scope.stopRefresh()); } else // normal update { api.request({ api: 'get', after: $scope.newestRequest }, function(data) { if(data.length > 0) { $scope.data = data.concat($scope.data); // add data $scope.newestRequest = data[0].id; } // timeout for new refresh $timeout($scope.refresh, config.refresh_time); }, $scope.stopRefresh()); } }; // pre-initialize dates for performance var today = null, yesterday = null, recheckDate = 0; // every 25th time 'date' will be refreshed // so that tabs opened over midnight won't bug // 0%25 == 0, so auto-init is built-in // format the time $scope.timeFormat = function(timestamp) { if(++recheckDate % 25 == 0) { today = moment().startOf('day'); yesterday = moment().subtract(1, 'days'); } var dt = moment.unix(timestamp); if (config.substituteNearDates) { var dts = dt.clone().startOf('day'); if(dts.isSame(today)) return dt.format('[Today], H:mm:ss'); if(dts.isSame(yesterday)) return dt.format('[Yesterday], H:mm:ss'); } // need to recreate since .startOf deletes the hour return dt.format(config.dateFormat); }; // returns a CSS class for an error level $scope.levelToCSS = function (level) { if(level < 200) return 'error-debug'; // gray if(level < 300) return 'error-notify'; // blue if(level < 400) return 'error-warning'; // orange if(level < 500) return 'error-error'; // red return 'error-emergency'; // red-black }; // (re)activate this controller when the user logs in $rootScope.$on('logged_in', function() { $scope.activate(); }); // deactivate on log out $rootScope.$on('logged_out', function() { $scope.deactivate(); }); // Refresh button $rootScope.$on('toggle_refresh', function() { $scope.toggleRefresh(); }); // called to hide & deactivate this $scope.deactivate = function() { $scope.active = false; $scope.data = []; // clear data so that another user atEnd = false; $scope.newestRequest = ''; // ... won't find old logs $scope.oldestRequest = ''; }; // reactivate this controller $scope.activate = function() { $scope.data = []; // if a late request filled it $scope.active = true; $scope.startRefresh(); $scope.newestRequest = ''; $scope.oldestRequest = ''; }; // return wether the scope is active (for API service) isActive = function() { return $scope.active }; // scroll event $window.onscroll = function(ev) { // http://stackoverflow.com/questions/9439725/javascript-how-to-detect-if-browser-window-is-scrolled-to-bottom if ($scope.active && !loadingMore && $scope.oldestRequest != '' && (((document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop) + window.innerHeight) + 50 >= ((document.documentElement && document.documentElement.scrollHeight) || document.body.scrollHeight)) { loadMore(); } }; var loadingMore = false; var atEnd = false; loadMore = function() { if(loadingMore || atEnd) return; // already refreshing loadingMore = true; api.request({ api: 'get', bottom: $scope.oldestRequest }, function(data) { loadingMore = false; if(data.length > 0) // add data { $scope.data = $scope.data.concat(data); // add data $scope.oldestRequest = data[data.length-1].id; } else { atEnd = true; $scope.lmdiv = 'No more entries!'; } }, function() { loadingMore = false; return true; }); } // if we start out with this controller, refresh if(config.logged_in) $scope.activate(); }]); // second controller to control navbar; mirror of logController app.controller('logCtrlController', ['$scope', '$rootScope', '$http', 'API', function($scope, $rootScope, $http, api) { $scope.active = config.logged_in; $scope.refreshing = config.logged_in; $scope.toggleRefresh = function() { $rootScope.$emit('toggle_refresh'); }; $rootScope.$on('refresh_on', function() { $scope.refreshing = true; }); $rootScope.$on('refresh_off', function() { $scope.refreshing = false; }); $scope.logout = function() { api.request({ api: 'logout'}, function(data) { $rootScope.$emit('logged_out'); $scope.active = false; }); }; // unused function, kept for reference // angular was unable to call it from ng-click $scope.impress = function() { /* "AnguLog Version "+config.version+"\n"+ "(c) <NAME> <<EMAIL>>, 2015\n"+ "This product is licensed under the GNU GPL.\n\n"+ "Third-Party Products:\n"+ "AngularJS v1.3.13; MIT License\n"+ "moment.js v2.9.0; MIT License\n\n"+ "If you like this product, visist the Github page and get involved:\n"+ "https://github.com/Sebb767/AnguLog";*/ }; $rootScope.$on('logged_in', function () { $scope.active = true; }); }]); app.controller('statusController', ['$scope', '$rootScope', function($scope, $rootScope) { // status healthy = true; $scope.status = 'Connected to the service.'; $scope.statusCSS = function() { alert('n'); return healthy ? 'webrequest-okay' : 'webrequest-error'; }; }]); //*/ app.controller("configController", ['$rootScope', function($rootScope) { // updates the config $rootScope.$on('logged_in', function() { config.logged_in = true; }); $rootScope.$on('logged_out', function() { config.logged_in = false; }); }]); app.factory('API', ['$http', '$rootScope', function API($http, $rootScope) { var ApiFactory = { handleError: function (data, status) { if(status !== 0)// = no client error { if(!config.logged_in) return; // not active alert('Error (' + status + '): '+ data.error); // Show error message if(data.reload) // fatal error -> reload $window.location.reload(); } }, request: function(params, fn, failfn = null) { $http({ url: '?', method: "GET", params: params }). success(function(data, status, headers, config) { if(data.success) { fn(data.data); // done - call callback } else ApiFactory.handleError(data, status); // handle failure }).error(function(data, status, headers, config) { if(failfn === null || !failfn()) ApiFactory.handleError(null, 0); }); }, }; return ApiFactory; }]);<file_sep>/compile.php #!/usr/bin/env php <?php // compile.php // minifies angulog // it's not THAT dynamic, but it's a helper - what did you expect? // version if($argc < 2) die('Usage: '.$argv[0]." [version] [-n]\n"); define('AL_VERSION', $argv[1]); define('MIN_PHP', !(isset($argv[2]) && trim($argv[2]) == '-n')); if(!MIN_PHP) echo "Not minifying php.\n"; // helper to minify html function minifyHTML($html) { $replace = array( '/<!--[^\[](.*?)[^\]]-->/s' => '', "/\r/" => '', "/\n/" => ' ', "/\t/" => '', "/ +/" => ' ', "/> +</" => '><', "/\" +>/" => '">', ); return preg_replace(array_keys($replace), array_values($replace), $html); } // helper to minify css function minifyCSS($css) { $replace = array( ";/\\*(.|[\r\n])*?\\*/;" => '', "/\r/" => '', "/\n/" => '', "/\t/" => '', "/ +/" => ' ', "/; +/" => ';', "/ +;/" => ';', "/\\} +/" => '}', "/\\] +/" => ']', "/\\) +/" => ')', "/\\{ +/" => '{', "/\\[ +/" => '[', "/\\( +/" => '(', "/ +\\}/" => '}', "/ +\\]/" => ']', "/ +\\)/" => ')', "/ +\\{/" => '{', "/ +\\[/" => '[', "/ +\\(/" => '(', "/, +/" => ',', "/ +,/" => ',', "/= +/" => '=', "/ +=/" => '=', "/ +:/" => ':', "/: +/" => ':', ); return preg_replace(array_keys($replace), array_values($replace), $css); } // helper to minify php function minifyPHP($code) { if(!MIN_PHP) return $code; $replace = array( ";//.*?\n;" => "", ";/\\*(.|[\r\n])*?\\*/;" => '', "/\r/" => '', "/\n/" => '', "/\t/" => ' ', "/ +/" => ' ', "/; +/" => ';', "/ +;/" => ';', "/\\} +/" => '}', "/\\] +/" => ']', "/\\) +/" => ')', "/\\{ +/" => '{', "/\\[ +/" => '[', "/\\( +/" => '(', "/ +\\}/" => '}', "/ +\\]/" => ']', "/ +\\)/" => ')', "/ +\\{/" => '{', "/ +\\[/" => '[', "/ +\\(/" => '(', "/, +/" => ',', "/ +,/" => ',', "/= +/" => '=', "/ +=/" => '=', "/=> +/" => '=>', "/ +=>/" => '=>', "/: +/" => ':', "/ +:/" => ':', ); return preg_replace(array_keys($replace), array_values($replace), $code); } function stripNamespace($code, $namespace = 'Sebb767\\\\AnguLog') { return preg_replace('!namespace +'.$namespace.';!i', '', $code); } // reads the path, strips <?php and namespace, minifies function readPHP($path, $strip_php = true) { $code = file_get_contents($path); if($strip_php) $code = substr($code, 5); // strip <?php $code = stripNamespace($code); return minifyPHP($code); } $path = './angulog/'; $out = file_get_contents($path.'angulog.php'); $out = substr($out, 0, strpos($out, '#!minify'))."//\n"; // strip includes // add version $out .= "define('AL_VERSION', '".AL_VERSION."');"; // we don't minify php that heavy (what for? that 2, 3 kb on a server download?), so we // just add our code here with replaced whitespaces etc $out .= readPHP($path.'php-logreader.php'); // default log reader $out .= readPHP($path.'code.php'); // the code $out .= '?>'; // add trailing end // now we need our html $html = file_get_contents($path.'html.php'); $includes = array();// \? > preg_match_all('#<\?php +include\(\'([A-Za-z0-9\-\./]+)\'\); +\?>#i', $html, $includes); $count = count($includes[0]); $js = ''; $css = ''; for($i = 0; $i < $count; $i++) { if(substr($includes[1][$i], -3, 3) == 'css') // css { $css .= minifyCSS(file_get_contents($path.$includes[1][$i])); $html = str_replace($includes[0][$i], '', $html); echo "Reading ".$includes[1][$i]."\n"; } else // js { if(substr($includes[1][$i], -6, 3) != 'min') // script.[min].js { echo "Minifying ".$includes[1][$i]."\n"; $js .= exec('ng-annotate -a "'.$path.$includes[1][$i].'" | uglifyjs -m'); } else { echo "Reading ".$includes[1][$i]."\n"; $js .= file_get_contents($path.$includes[1][$i]); } $html = str_replace($includes[0][$i], '', $html); } } // minify html now that js/css is out $html = minifyHTML($html); // insert css $html = str_replace('/*-#!css-*/', $css, $html); // ... and js + insert $out .= str_replace('/*-#!js-*/', $js, $html); unset($html); // write out $file = 'compiled/angulog-'.AL_VERSION.'.php'; echo 'Writing to '.$file."\n"; file_put_contents($file, $out);
58ba64d3244cfcc5765ccf7fb34d30a45eb9f7ef
[ "Markdown", "JavaScript", "PHP" ]
7
Markdown
Sebb767/AnguLog
2083875ae9d6c0117fa6d0a19830ba30fe8ba19a
90d08f92d924de2a54d5dc4c012a5f5cf71d3e87
refs/heads/master
<file_sep># Generated by Django 2.1.4 on 2019-06-29 13:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('minuta', '0002_auto_20190626_2020'), ] operations = [ migrations.AddField( model_name='ticket', name='tipo', field=models.CharField(choices=[('A', 'Agregado'), ('M', 'Modificacion'), ('E', 'Error'), ('O', 'Otro')], default='O', max_length=1), ), ] <file_sep>from typing import List from minuta.models import Responsabilidad, Minuta, Asistente class ResponsabilidadService: def crear(minuta:Minuta, responsables:List[Asistente], tarea:str, fecha:str) -> Responsabilidad: responsabilidad = Responsabilidad(minuta=minuta, tarea=tarea, fecha=fecha) responsabilidad.save() for responsable in responsables: responsabilidad.responsables.add(responsable) return responsabilidad <file_sep>from django.test import TestCase from minuta.services.cotizador_service import Cotizador # Create your tests here. from .models import Minuta class AnimalTestCase(TestCase): def test_animals_can_speak(self): """Animals that can speak are correctly identified""" cotizador = Cotizador cotizador.cotizarMes() <file_sep>from functools import reduce from minuta.models import Movimiento, Hora,Programador from django.db.models import Sum, OuterRef, Subquery, FloatField, Case, When from django.db import connection def dictfetchall(cursor): "Return all rows from a cursor as a dict" columns = [col[0] for col in cursor.description] return [ dict(zip(columns, row)) for row in cursor.fetchall() ] def programadores_cotizacion(fecha_desde, fecha_hasta): cursor = connection.cursor() cursor.execute(''' SELECT minuta_programador.id, minuta_programador.nombre, minuta_programador.apellido, CASE WHEN (SELECT SUM(minuta_movimiento.monto) FROM minuta_movimiento where minuta_movimiento.programador_id = minuta_programador.id and minuta_movimiento.monto < 0 and minuta_movimiento.fecha >= %s and minuta_movimiento.fecha <= %s) is null then 0 else (SELECT SUM(minuta_movimiento.monto) FROM minuta_movimiento where minuta_movimiento.programador_id = minuta_programador.id and minuta_movimiento.monto < 0 and minuta_movimiento.fecha >= %s and minuta_movimiento.fecha <= %s) end as total_gastos, CASE WHEN (select sum(minuta_hora.cantidad_horas) from minuta_hora where minuta_hora.programador_id = minuta_programador.id and minuta_hora.fecha >= %s and minuta_hora.fecha <= %s) is null then 0 else (select sum(minuta_hora.cantidad_horas) from minuta_hora where minuta_hora.programador_id = minuta_programador.id and minuta_hora.fecha >= %s and minuta_hora.fecha <= %s) end as total_horas from minuta_programador where minuta_programador.es_socio = 1 ''',[fecha_desde,fecha_hasta,fecha_desde,fecha_hasta,fecha_desde,fecha_hasta,fecha_desde,fecha_hasta]) row = dictfetchall(cursor) return row def programadores_ajuste(mes): cursor = connection.cursor() cursor.execute(''' SELECT minuta_programador.id, minuta_programador.nombre, minuta_programador.apellido, CASE WHEN (SELECT SUM(minuta_movimiento.monto) FROM minuta_movimiento where minuta_movimiento.programador_id = minuta_programador.id and minuta_movimiento.monto < 0 and cast(strftime('%%m', minuta_movimiento.fecha) as int) = %s ) is null then 0 else (SELECT SUM(minuta_movimiento.monto) FROM minuta_movimiento where minuta_movimiento.programador_id = minuta_programador.id and minuta_movimiento.monto < 0 and cast(strftime('%%m', minuta_movimiento.fecha) as int) = %s) end as total_gastos, CASE WHEN (select sum(minuta_hora.cantidad_horas) from minuta_hora where minuta_hora.programador_id = minuta_programador.id and cast(strftime('%%m', minuta_hora.fecha) as int) = %s ) is null then 0 else (select sum(minuta_hora.cantidad_horas) from minuta_hora where minuta_hora.programador_id = minuta_programador.id and cast(strftime('%%m', minuta_hora.fecha) as int) = %s ) end as total_horas_mes, CASE WHEN (SELECT SUM(minuta_movimiento.monto) FROM minuta_movimiento where minuta_movimiento.programador_id = minuta_programador.id and (%s - cast(strftime('%%m', minuta_movimiento.fecha) as int)) <= 3 and (%s - cast(strftime('%%m', minuta_movimiento.fecha) as int)) > 0) is null then 0 else (SELECT SUM(minuta_movimiento.monto) FROM minuta_movimiento where minuta_movimiento.programador_id = minuta_programador.id and (%s - cast(strftime('%%m', minuta_movimiento.fecha) as int)) <= 3 and (%s - cast(strftime('%%m', minuta_movimiento.fecha) as int)) > 0) end as total_ganancia_ajuste, CASE WHEN (select sum(minuta_hora.cantidad_horas) from minuta_hora where minuta_hora.programador_id = minuta_programador.id and (%s - cast(strftime('%%m', minuta_hora.fecha) as int)) <= 3 and (%s - cast(strftime('%%m', minuta_hora.fecha) as int)) > 0) is null then 0 else (select sum(minuta_hora.cantidad_horas) from minuta_hora where minuta_hora.programador_id = minuta_programador.id and (%s - cast(strftime('%%m', minuta_hora.fecha) as int)) <= 3 and (%s - cast(strftime('%%m', minuta_hora.fecha) as int)) > 0) end as total_horas_ajuste from minuta_programador where minuta_programador.es_socio = 1 ''', [mes,mes,mes,mes,mes,mes,mes,mes,mes,mes,mes,mes]) row = dictfetchall(cursor) return row class Cotizador: def cotizarMes(fecha_desde, fecha_hasta): programadores = programadores_cotizacion(fecha_desde, fecha_hasta) ganancia = Movimiento.objects.filter(programador__es_socio=True, fecha__gte=fecha_desde, fecha__lte=fecha_hasta).aggregate(Sum('monto')) horas_totales = sum([pr['total_horas'] for pr in programadores]) for programador in programadores: porcentaje = programador['total_horas'] / horas_totales cobro = ganancia['monto__sum'] * porcentaje total = ganancia['monto__sum'] * cobro + programador['total_gastos'] programador.update({'porcentaje': porcentaje * 100, 'cobro': cobro, 'total':total}) return programadores def cotizarAjuste(mes): programadores = programadores_ajuste(mes) horas_totales = sum([pr['total_horas_ajuste'] for pr in programadores]) ganancia_total = sum([pr['total_ganancia_ajuste'] for pr in programadores]) for programador in programadores: porcentaje_horas = programador['total_horas_ajuste'] / horas_totales porcentaje_ganancia = programador['total_ganancia_ajuste'] / ganancia_total diferencia_porcentaje = porcentaje_ganancia - porcentaje_horas adicional = ganancia_total * diferencia_porcentaje programador.update({'porcentaje_horas_ajuste': porcentaje_horas}) return programadores # cantidad total de horas del periodo # porcentaje que cada uno trabajo de esas horas # sumar el total de ganancia de los tres meses # calcular la ganancia total de cada uno durante los 3 meses # ver que porcentaje es eso de la total<file_sep>from django import forms from django.contrib import admin from .models import Programador, Ticket, Respuesta, Empresa, Proyecto, Minuta, Asistente, Tema, Responsabilidad, Definicion admin.site.register(Empresa) admin.site.register(Proyecto) admin.site.register(Ticket) admin.site.register(Respuesta) admin.site.register(Programador) class DefinicionInLine(admin.StackedInline): model = Definicion class TemaAdmin(admin.ModelAdmin): model = Tema inlines = [DefinicionInLine] class MinutaAdmin(admin.ModelAdmin): model = Minuta list_display = ('motivo', 'fecha', 'proyecto', 'descripcion', 'asistentes_display', 'temas') search_fields = ['motivo'] def asistentes_display(self, obj): s = ' '.join(asistente.nombre.capitalize() +' '+ asistente.apellido.capitalize() +',' for asistente in obj.asistentes.all()) return s[0: len(s)-1] asistentes_display.short_description = 'ASISTENTES' def temas(self, obj): s = ' '.join(tema.titulo.capitalize() + ',' for tema in Tema.objects.all().filter(minuta = obj)) return s[0: len(s)-1] admin.site.register(Minuta, MinutaAdmin) admin.site.register(Asistente) admin.site.register(Tema, TemaAdmin) admin.site.register(Responsabilidad) admin.site.register(Definicion) <file_sep>from django.db import models import datetime from django.utils import timezone class Empresa(models.Model): nombre = models.CharField(max_length=50) def __str__(self): return self.nombre class Programador(models.Model): nombre = models.CharField(max_length=50) apellido = models.CharField(max_length=50) mail = models.EmailField(null=True, blank=True) es_socio = models.BooleanField(default=True) def __str__(self): return self.nombre + ' ' + self.apellido class Proyecto(models.Model): nombre = models.CharField(max_length=50) empresa = models.ForeignKey(Empresa, related_name='proyectos', on_delete=models.CASCADE) horas = models.IntegerField() fecha_limite = models.DateField(null=True, blank=True) fecha_inicio = models.DateField(null=True, blank=True) programadores = models.ManyToManyField(Programador) responsable = models.ForeignKey(Programador, related_name='proyectos', on_delete=models.CASCADE) pago = models.BooleanField(default=False) def __str__(self): return self.nombre class Movimiento(models.Model): TYPES = ( ('C', 'Cobro'), ('P', 'Pago'), ) concepto = models.CharField(max_length=200) programador = models.ForeignKey(Programador, related_name='movimientos', on_delete=models.CASCADE) monto = models.FloatField() descripcion = models.TextField() fecha = models.DateField(null=True, blank=True) proyecto = models.ForeignKey(Proyecto, related_name="movimientos", on_delete=models.CASCADE) tipo = models.CharField(choices=TYPES, max_length=1, default='C') def __str__(self): return self.concepto class Ticket(models.Model): PRIORITIES = ( ('C', 'Critico'), ('A', 'Alto'), ('M', 'Medio'), ('B', 'Bajo'), ) STATUS = ( ('P', 'Pendiente'), ('E', 'En progreso'), ('B', 'Bloqueado'), ('R', 'Resuelto'), ('C', 'Cerrado'), ) TIPOS = ( ('A', 'Agregado'), ('M', 'Modificacion'), ('E', 'Error'), ('O', 'Otro'), ) titulo = models.TextField() descripcion = models.TextField() prioridad = models.CharField(choices=PRIORITIES, max_length=1, default='M') status = models.CharField(choices=STATUS, max_length=1, default='P') proyecto = models.ForeignKey(Proyecto, related_name="tickets", on_delete=models.CASCADE) fecha_apertura = models.DateTimeField(default=timezone.now) fecha_estimada = models.DateTimeField(null=True, blank=True) tipo = models.CharField(choices=TIPOS, max_length=1, default='O') def __str__(self): return self.titulo class Hora(models.Model): cantidad_horas = models.IntegerField() fecha = models.DateField(null=True, blank=True) ticket = models.ForeignKey(Ticket, related_name="horas_aplicadas", on_delete=models.CASCADE) programador = models.ForeignKey(Programador, related_name="horas_aplicadas", on_delete=models.CASCADE) proyecto = models.ForeignKey(Proyecto, related_name="horas_aplicadas", on_delete=models.CASCADE) descripcion = models.TextField() def __str__(self): return self.descripcion class Respuesta(models.Model): fecha = models.DateTimeField(null=True, blank=True) texto = models.TextField() ticket = models.ForeignKey(Ticket, related_name="respuestas", on_delete=models.CASCADE) def __str__(self): return self.texto class Asistente(models.Model): empresa = models.ForeignKey(Empresa, related_name='empleados', on_delete=models.CASCADE) nombre = models.CharField(max_length=50) apellido = models.CharField(max_length=50) mail = models.EmailField(null=True, blank=True) def __str__(self): return self.nombre class Minuta(models.Model): fecha = models.DateField(null=True, blank=True) proyecto = models.ForeignKey(Proyecto, related_name='minutas', on_delete=models.CASCADE) motivo = models.CharField(max_length=100) descripcion = models.TextField() asistentes = models.ManyToManyField(Asistente) def __str__(self): return self.motivo class Responsabilidad(models.Model): responsables = models.ManyToManyField(Asistente) tarea = models.TextField() fecha = models.DateField(null=True, blank=True) minuta = models.ForeignKey(Minuta, related_name='responsabilidades', on_delete=models.CASCADE) def __str__(self): return self.tarea class Tema(models.Model): titulo = models.CharField(max_length=50) minuta = models.ForeignKey(Minuta, related_name='temas', on_delete=models.CASCADE) def __str__(self): return self.titulo class Definicion(models.Model): texto = models.TextField() tema = models.ForeignKey(Tema, related_name='definiciones', on_delete=models.CASCADE) def __str__(self): return self.texto <file_sep>from rest_framework import routers from minuta.views import EmpresaViewSet,\ ProyectoViewSet,\ MinutaViewSet,\ AsistenteViewSet,\ TemaViewSet,\ DefinicionViewSet,\ ResponsabilidadViewSet,\ HoraViewSet,\ ProgramadorViewSet,\ MovimientoViewSet,\ CotizacionDelMes,\ CotizacionAjuste,\ TicketViewset,\ RespuestaViewSet from django.urls import path from rest_framework_simplejwt import views as jwt_views router = routers.DefaultRouter() router.register(r'empresas', EmpresaViewSet) router.register(r'proyectos', ProyectoViewSet) router.register(r'asistentes', AsistenteViewSet) router.register(r'minutas', MinutaViewSet) router.register(r'temas', TemaViewSet) router.register(r'definiciones', DefinicionViewSet) router.register(r'programadores', ProgramadorViewSet) router.register(r'responsabilidades', ResponsabilidadViewSet) router.register(r'horas', HoraViewSet) router.register(r'movimientos', MovimientoViewSet) router.register(r'tickets', TicketViewset) router.register(r'respuestas', RespuestaViewSet) urlpatterns = [ path('cotizacion/', CotizacionDelMes.as_view(), name='cotizacion_del_mes'), path('cotizacion/con_ajuste/', CotizacionAjuste.as_view(), name='cotizacion_con_ajuste'), path('token/', jwt_views.TokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh') ] urlpatterns += router.urls<file_sep># Generated by Django 2.1.4 on 2019-06-26 16:52 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Asistente', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nombre', models.CharField(max_length=50)), ('apellido', models.CharField(max_length=50)), ('mail', models.EmailField(blank=True, max_length=254, null=True)), ], ), migrations.CreateModel( name='Definicion', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('texto', models.TextField()), ], ), migrations.CreateModel( name='Empresa', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nombre', models.CharField(max_length=50)), ], ), migrations.CreateModel( name='Hora', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('cantidad_horas', models.IntegerField()), ('fecha', models.DateField(blank=True, null=True)), ('descripcion', models.TextField()), ], ), migrations.CreateModel( name='Minuta', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('fecha', models.DateField(blank=True, null=True)), ('motivo', models.CharField(max_length=100)), ('descripcion', models.TextField()), ('asistentes', models.ManyToManyField(to='minuta.Asistente')), ], ), migrations.CreateModel( name='Movimiento', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('concepto', models.CharField(max_length=200)), ('monto', models.FloatField()), ('descripcion', models.TextField()), ('fecha', models.DateField(blank=True, null=True)), ('tipo', models.CharField(choices=[('C', 'Cobro'), ('P', 'Pago')], default='C', max_length=1)), ], ), migrations.CreateModel( name='Programador', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nombre', models.CharField(max_length=50)), ('apellido', models.CharField(max_length=50)), ('mail', models.EmailField(blank=True, max_length=254, null=True)), ('es_socio', models.BooleanField(default=True)), ], ), migrations.CreateModel( name='Proyecto', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nombre', models.CharField(max_length=50)), ('horas', models.IntegerField()), ('fecha_limite', models.DateField(blank=True, null=True)), ('fecha_inicio', models.DateField(blank=True, null=True)), ('pago', models.BooleanField(default=False)), ('empresa', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='proyectos', to='minuta.Empresa')), ('programadores', models.ManyToManyField(to='minuta.Programador')), ('responsable', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='proyectos', to='minuta.Programador')), ], ), migrations.CreateModel( name='Responsabilidad', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('tarea', models.TextField()), ('fecha', models.DateField(blank=True, null=True)), ('minuta', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='responsabilidades', to='minuta.Minuta')), ('responsables', models.ManyToManyField(to='minuta.Asistente')), ], ), migrations.CreateModel( name='Tema', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('titulo', models.CharField(max_length=50)), ('minuta', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='temas', to='minuta.Minuta')), ], ), migrations.CreateModel( name='Ticket', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nombre', models.TextField()), ('descripcion', models.TextField()), ('prioridad', models.CharField(choices=[('C', 'Critical'), ('H', 'High'), ('M', 'Medium'), ('L', 'Low')], default='M', max_length=1)), ('status', models.CharField(choices=[('A', 'Abierto'), ('P', 'En progreso'), ('B', 'Bloqueado'), ('R', 'Resuelto'), ('C', 'Cerrado')], default='A', max_length=1)), ('proyecto', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tickets', to='minuta.Proyecto')), ], ), migrations.AddField( model_name='movimiento', name='programador', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='movimientos', to='minuta.Programador'), ), migrations.AddField( model_name='movimiento', name='proyecto', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='movimientos', to='minuta.Proyecto'), ), migrations.AddField( model_name='minuta', name='proyecto', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='minutas', to='minuta.Proyecto'), ), migrations.AddField( model_name='hora', name='programador', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='horas_aplicadas', to='minuta.Programador'), ), migrations.AddField( model_name='hora', name='proyecto', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='horas_aplicadas', to='minuta.Proyecto'), ), migrations.AddField( model_name='hora', name='ticket', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='horas_aplicadas', to='minuta.Ticket'), ), migrations.AddField( model_name='definicion', name='tema', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='definiciones', to='minuta.Tema'), ), migrations.AddField( model_name='asistente', name='empresa', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='empleados', to='minuta.Empresa'), ), ] <file_sep>from minuta.models import Definicion, Tema class DefinicionService: def crear(tema:Tema, texto:str) -> Definicion: definicion = Definicion(tema=tema, texto=texto) definicion.save() return definicion<file_sep>from minuta.models import Tema, Minuta from minuta.services.definicion_service import DefinicionService class TemaService: def crear(minuta:Minuta, titulo:str, definiciones) -> Tema: tema =Tema(titulo=titulo, minuta=minuta) tema.save() for definicion in definiciones: DefinicionService.crear(tema=tema, **definicion) return tema<file_sep>from rest_framework import viewsets from .models import Respuesta, Empresa, Proyecto, Asistente, Minuta, Tema, Definicion, Responsabilidad, Programador, Hora, Movimiento, Ticket from .serializers import RespuestaSerializer, EmpresaSerializer, ProyectoSerializer, AsistenteSerializer, MinutaSerializer, TemaSerializer, DefinicionSerializer, ResponsabilidadSerializer, ProgramadorSerializer, HoraSerializer, MovimientoSerializer, TicketSerializer from rest_framework.response import Response from rest_framework import status from django.db import transaction from minuta.services.minuta_service import MinutaService from rest_framework.views import APIView from minuta.services.cotizador_service import Cotizador from rest_framework.permissions import IsAuthenticated class RespuestaViewSet(viewsets.ModelViewSet): queryset = Respuesta.objects.all() serializer_class = RespuestaSerializer class TicketViewset(viewsets.ModelViewSet): queryset = Ticket.objects.all() serializer_class = TicketSerializer class EmpresaViewSet(viewsets.ModelViewSet): queryset = Empresa.objects.all() serializer_class = EmpresaSerializer class ProyectoViewSet(viewsets.ModelViewSet): queryset = Proyecto.objects.all() serializer_class = ProyectoSerializer class ProgramadorViewSet(viewsets.ModelViewSet): queryset = Programador.objects.all() serializer_class = ProgramadorSerializer class HoraViewSet(viewsets.ModelViewSet): queryset = Hora.objects.all() serializer_class = HoraSerializer class ResponsabilidadViewSet(viewsets.ModelViewSet): queryset = Responsabilidad.objects.all() serializer_class = ResponsabilidadSerializer class AsistenteViewSet(viewsets.ModelViewSet): queryset = Asistente.objects.all() serializer_class = AsistenteSerializer class MinutaViewSet(viewsets.ModelViewSet): queryset = Minuta.objects.all() serializer_class = MinutaSerializer @transaction.atomic def create(self, request, *args, **kwargs): proyecto = Proyecto.objects.filter(id=request.data.get('proyecto')).first() asistentes = list(Asistente.objects.filter(pk__in=request.data.get('asistentes'))) for responsabilidad in request.data.get('responsabilidades'): responsables = list(Asistente.objects.filter(pk__in=responsabilidad['responsables'])) responsabilidad.update({'responsables': responsables}) request.data.update({'proyecto': proyecto, 'asistentes':asistentes}) minuta = MinutaService.crear(**request.data) headers = self.get_success_headers(minuta.id) return Response(minuta.id, status=status.HTTP_201_CREATED, headers=headers) class TemaViewSet(viewsets.ModelViewSet): queryset = Tema.objects.all() serializer_class = TemaSerializer class DefinicionViewSet(viewsets.ModelViewSet): queryset = Definicion.objects.all() serializer_class = DefinicionSerializer class MovimientoViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset = Movimiento.objects.all() serializer_class = MovimientoSerializer class CotizacionDelMes(APIView): def get(self, request): fecha_desde = request.query_params.get('fecha_desde') fecha_hasta = request.query_params.get('fecha_hasta') cotizacion = Cotizador.cotizarMes(fecha_desde=fecha_desde, fecha_hasta=fecha_hasta) return Response(cotizacion) class CotizacionAjuste(APIView): def get(self, request): mes = request.query_params.get('mes') return Response(Cotizador.cotizarAjuste(mes)) <file_sep>from rest_framework import serializers from .models import Respuesta, Empresa, Proyecto, Asistente, Minuta, Tema, Definicion, Responsabilidad, Programador, Hora, Movimiento, Ticket class EmpresaSerializer(serializers.ModelSerializer): class Meta: model = Empresa fields = ('id', 'nombre') class ProgramadorSerializer(serializers.ModelSerializer): class Meta: model = Programador fields = ('id', 'nombre', 'apellido', 'mail', 'es_socio') class HoraSerializer(serializers.ModelSerializer): proyecto_nombre = serializers.CharField(read_only = True, source='proyecto.nombre') programador_nombre = serializers.CharField(read_only = True, source='programador.nombre') class Meta: model = Hora fields = ('id', 'programador', 'proyecto', 'cantidad_horas', 'descripcion', 'fecha', 'ticket', 'proyecto_nombre', 'programador_nombre') class TicketSerializer(serializers.ModelSerializer): proyecto_nombre = serializers.CharField(read_only=True, source='proyecto.nombre') class Meta: model = Ticket fields = ('id', 'titulo', 'descripcion', 'prioridad', 'status', 'proyecto', 'tipo', 'proyecto_nombre', 'proyecto_nombre', 'fecha_estimada', 'fecha_apertura') read_only_fields = ('fecha_apertura',) class RespuestaSerializer(serializers.ModelSerializer): titulo = serializers.CharField(read_only=True, source='ticket.titulo') class Meta: model = Respuesta fields = ('texto', 'titulo', 'ticket', 'fecha') read_only_fields = ('fecha',) class ProyectoSerializer(serializers.ModelSerializer): empresa_detalle = serializers.SerializerMethodField() programadores_detalle = serializers.SerializerMethodField() def get_programadores_detalle(self, obj): ser = ProgramadorSerializer(obj.programadores, many=True) return ser.data def get_empresa_detalle(self, obj): ser = EmpresaSerializer(obj.empresa) return ser.data class Meta: model = Proyecto fields = ('id', 'nombre', 'empresa', 'programadores', 'responsable', 'horas', 'fecha_inicio', 'fecha_limite', 'pago', 'empresa_detalle', 'programadores_detalle') class AsistenteSerializer(serializers.ModelSerializer): empresa_detalle = serializers.SerializerMethodField() def get_empresa_detalle(self, obj): ser = EmpresaSerializer(obj.empresa) return ser.data class Meta: model = Asistente fields = ('id', 'empresa', 'nombre', 'apellido', 'mail', 'empresa_detalle') class DefinicionSerializer(serializers.ModelSerializer): class Meta: model = Definicion fields = ('id', 'tema', 'texto') class TemaSerializer(serializers.ModelSerializer): definiciones = DefinicionSerializer(many=True, read_only=True) class Meta: model = Tema fields = ('id', 'minuta', 'titulo', 'definiciones') class ResponsabilidadSerializer(serializers.ModelSerializer): class Meta: model = Responsabilidad fields = ('id', 'minuta', 'fecha', 'tarea', 'responsables') class MovimientoSerializer(serializers.ModelSerializer): programador = ProgramadorSerializer(read_only=True) programador_id = serializers.PrimaryKeyRelatedField(queryset=Programador.objects.all(), write_only=True, source='programador') #proyecto_id = serializers.PrimaryKeyRelatedField(queryset=Proyecto.objects.all(), source='proyecto') proyecto_nombre = serializers.CharField(read_only=True, source='proyecto.nombre') class Meta: model = Movimiento fields = ('id', 'concepto', 'monto', 'tipo', 'programador', 'programador_id', 'descripcion', 'fecha', 'proyecto_nombre', 'proyecto') class MinutaSerializer(serializers.ModelSerializer): temas = TemaSerializer(many=True, read_only=True) asistentes_detalle = serializers.SerializerMethodField() responsabilidades = ResponsabilidadSerializer(many=True, read_only=True) def get_asistentes_detalle(self, obj): ser = AsistenteSerializer(obj.asistentes, many=True) return ser.data class Meta: model = Minuta fields = ('id', 'fecha', 'proyecto', 'motivo', 'descripcion', 'asistentes', 'temas', 'asistentes_detalle', 'responsabilidades') <file_sep># Generated by Django 2.1.4 on 2019-06-26 20:20 import datetime from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('minuta', '0001_initial'), ] operations = [ migrations.CreateModel( name='Respuesta', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('fecha', models.DateTimeField(blank=True, null=True)), ('texto', models.TextField()), ], ), migrations.RenameField( model_name='ticket', old_name='nombre', new_name='titulo', ), migrations.AddField( model_name='ticket', name='fecha_apertura', field=models.DateTimeField(default=datetime.date.today), ), migrations.AddField( model_name='ticket', name='fecha_estimada', field=models.DateTimeField(blank=True, null=True), ), migrations.AlterField( model_name='ticket', name='prioridad', field=models.CharField(choices=[('C', 'Critico'), ('A', 'Alto'), ('M', 'Medio'), ('B', 'Bajo')], default='M', max_length=1), ), migrations.AlterField( model_name='ticket', name='status', field=models.CharField(choices=[('P', 'Pendiente'), ('E', 'En progreso'), ('B', 'Bloqueado'), ('R', 'Resuelto'), ('C', 'Cerrado')], default='P', max_length=1), ), migrations.AddField( model_name='respuesta', name='ticket', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='respuestas', to='minuta.Ticket'), ), ] <file_sep>from typing import List from minuta.models import Minuta, Proyecto, Asistente from minuta.services.tema_service import TemaService from minuta.services.responsabilidad_service import ResponsabilidadService from django.core.mail import send_mail from django.template.loader import render_to_string from django.utils.html import strip_tags def enviar_mail(minuta: Minuta): temas = [] for tema in minuta.temas.all(): definiciones = [] for definicion in tema.definiciones.all(): definiciones.append(definicion) temas.append({'tema': tema, 'definiciones': definiciones}) responsabilidades = [] for responsabilidad in minuta.responsabilidades.all(): responsables = [] for responsable in responsabilidad.responsables.all(): responsables.append(responsable) responsabilidades.append({'responsabilidad': responsabilidad, 'responsables': responsables}) html_message = render_to_string('minuta_email.html', {'motivo':minuta.motivo, 'descripcion':minuta.descripcion, 'asistentes': minuta.asistentes.all(), 'temas': temas, 'responsabilidades':responsabilidades}) plain_message = strip_tags(html_message) send_mail( 'Minuta: ' + minuta.motivo, plain_message, '<EMAIL>', ['<EMAIL>'], html_message=html_message, fail_silently=False, ) class MinutaService: def crear(fecha:str, motivo:str, asistentes:List[Asistente], proyecto:Proyecto, descripcion:str, temas, responsabilidades) -> Minuta: minuta = Minuta(fecha=fecha, motivo=motivo, proyecto=proyecto, descripcion=descripcion) minuta.save() for asistente in asistentes: minuta.asistentes.add(asistente) for tema in temas: TemaService.crear(minuta=minuta, **tema) for responsabilidad in responsabilidades: ResponsabilidadService.crear(minuta=minuta, **responsabilidad) enviar_mail(minuta=minuta) return minuta <file_sep>Django==2.1.4 django-cors-headers==2.4.0 djangorestframework==3.9.0 djangorestframework-simplejwt==4.3.0 mysqlclient==1.4.2.post1 PyJWT==1.7.1 pytz==2018.9 <file_sep>from django import template register = template.Library() @register.filter(name='definicion_de_tema') def definicion_de_tema(definiciones, id): return list(filter(lambda definicion: definicion.tema_id == id, definiciones))<file_sep>Django==2.1.4 djangorestframework==3.9 django-cors-headers==2.4.0
be1d85ffc2183a0f6b0fe28a90bd604fa8b3d6d4
[ "Text", "Python" ]
17
Text
FedericoJoel/horas
50fabb452ec320fffd4b375ffa18afc1441bf478
66e1ec1b9f24e8bbc11c512c7ec801a845507f86
refs/heads/master
<file_sep>import com.example.mymuseum.retrofit.User import okhttp3.ResponseBody import retrofit2.Call import retrofit2.http.* interface GetDataService { @POST("login") fun login(@Body user: User?): Call<User?>? @POST("register") fun register(@Body user: User?): Call<User?>? @POST("logout") fun logout(@Header("Authorization") api_token: String?): Call<User?>? }<file_sep>package com.example.mymuseum.ui.mensagens import androidx.lifecycle.ViewModel class MensagensViewModel : ViewModel() { }<file_sep>package com.example.mymuseum.activities import GetDataService import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.Button import android.widget.EditText import android.widget.ProgressBar import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.example.mymuseum.R import com.example.mymuseum.retrofit.RetrofitClientInstance import com.example.mymuseum.retrofit.User import retrofit2.Call import retrofit2.Callback import retrofit2.Response import retrofit2.Retrofit import java.lang.String.valueOf import kotlin.system.exitProcess class LoginActivity : AppCompatActivity() { var btn_login: Button? = null var et_email: EditText? = null var et_password:EditText? = null var progressBar: ProgressBar? = null val MyPREFERENCES = "MyPrefs" val ID = "userId" val TOKEN = "<PASSWORD>" var sharedpreferences: SharedPreferences? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) btn_login = findViewById(R.id.button_login_login) et_email = findViewById<EditText>(R.id.editText_login_nome) et_password = findViewById<EditText>(R.id.editText_login_pass) progressBar = findViewById(R.id.progressBar_login) sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE) } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.login_menu, menu) return true } //funcões do menu de opções quando são clicadas override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId){ R.id.menu_login_sair->{ //permite sair da aplicação exitProcess(-1) } } return super.onOptionsItemSelected(item) } fun goToRegister(view: View) { val intent = Intent(this, RegisterActivity::class.java) startActivity(intent) finish() } fun login(view: View) { //Cria uma instancia da interface do retrofit btn_login?.setVisibility(View.GONE); progressBar?.setVisibility(View.VISIBLE); val service = RetrofitClientInstance.retrofitInstance?.create(GetDataService::class.java) val newUser = User(et_email!!.text.toString(), et_password!!.text.toString()) val call = service!!.login(newUser) call!!.enqueue(object: Callback<User?>{ override fun onResponse(call: Call<User?>, response: Response<User?>) { if(response.body() != null){ val intent = Intent(applicationContext, MainActivity::class.java) startActivity(intent) val editor = sharedpreferences!!.edit() response.body()!!.id?.let { editor.putLong("ID", it) } response.body()!!.api_token?.let { editor.putString("TOKEN", it) } editor.commit() Toast.makeText(applicationContext, valueOf(sharedpreferences!!.getString("ID", "")),Toast.LENGTH_LONG).show() Toast.makeText(applicationContext, valueOf(sharedpreferences!!.getString("TOKEN", "")),Toast.LENGTH_LONG).show() //Toast.makeText(applicationContext, "Bem Vindo", Toast.LENGTH_LONG).show() finish(); } } override fun onFailure(call: Call<User?>, t: Throwable) { Toast.makeText(applicationContext, "Dados não retornados", Toast.LENGTH_LONG).show() btn_login?.setVisibility(View.VISIBLE); progressBar?.setVisibility(View.GONE); } }) } } <file_sep>package com.example.mymuseum.ui.home import android.graphics.Color import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import androidx.recyclerview.widget.LinearLayoutManager import com.example.mymuseum.R import com.example.mymuseum.adapters.CategoriaAdapter import kotlinx.android.synthetic.main.fragment_home.view.* class HomeFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val root = inflater.inflate(R.layout.fragment_home, container, false) root.setBackgroundColor(Color.CYAN) //é criado um layout manager para este fragmento root.recylerView.layoutManager = LinearLayoutManager(activity) //depois é chamado o adaptador customizado root.recylerView.adapter = CategoriaAdapter() return root } } <file_sep>package com.example.mymuseum.adapters import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.example.mymuseum.R import kotlinx.android.synthetic.main.categoria_row.view.* class CategoriaAdapter : RecyclerView.Adapter<CustomViewHolder>(){ //imagem default val intImage = R.drawable.icon_perfil //array de imagens 2 val stringTitulo = arrayOf("Io", "Maldamba", "Grover", "Grock") val stringDescricao = arrayOf("Waifu", "Op as Fuck", "Nice to play", "play it always as damage") // associa um layout personalizado a cada linha(celula) do adaptador override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomViewHolder { val layoutInflater = LayoutInflater.from(parent.context) val cellForRow = layoutInflater.inflate(R.layout.categoria_row, parent, false) return CustomViewHolder(cellForRow) } //o tamanho deste adaptador é igual ao tamanho de imagens em qualquer um dos arrays override fun getItemCount(): Int { return stringTitulo.size } //pupola cada celula costumizada com elementos de cada um dos arrays override fun onBindViewHolder(holder: CustomViewHolder, position: Int) { //a cada posicao vai ser inserida uma imagem val image = intImage val titulo = stringTitulo.get(position) val descricao = stringDescricao.get(position) //é associada a imagem do array ao seu recurso, neste caso uma imageView holder?.view?.categoria_image?.setImageResource(image) holder?.view?.categoria_titulo.setText(titulo) holder?.view?.categoria_descricao.setText(descricao) } } // permite receber uma view, neste caso uma ImageView class CustomViewHolder(val view : View) : RecyclerView.ViewHolder(view){ }<file_sep>rootProject.name='MyMuseum' include ':app' <file_sep>package com.example.mymuseum.ui.contactos import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.EditText import android.widget.TextView import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import com.example.mymuseum.R import com.example.mymuseum.activities.ContactosSucesso import com.example.mymuseum.activities.RegisterActivity import kotlinx.android.synthetic.main.fragment_contactos.* import kotlinx.android.synthetic.main.fragment_contactos.view.* class ContactosFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val root = inflater.inflate(R.layout.fragment_contactos, container, false) val mensagem: EditText = root.findViewById(R.id.contactos_mensagem_corpo) root.contactos_button.setOnClickListener { val intent = Intent (requireActivity().applicationContext, ContactosSucesso::class.java) startActivity(intent) mensagem.text = null } return root } } <file_sep>package com.example.mymuseum.ui.contactos import androidx.lifecycle.ViewModel class ContactosViewModel : ViewModel() { }<file_sep>package com.example.mymuseum.retrofit import android.text.Editable import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName class User( @field:Expose @field:SerializedName("email") var email: String, @field:Expose @field:SerializedName("password") var password: String ) { @SerializedName("id") @Expose var id: Long? = null @SerializedName("api_token") @Expose var api_token: String? = null }<file_sep>package com.example.mymuseum.ui.comprarbilhete import androidx.lifecycle.ViewModel class ComprarBilheteViewModel : ViewModel() { }<file_sep>package com.example.mymuseum.ui.perfil import androidx.lifecycle.ViewModel class PerfilViewModel : ViewModel() { }
83c4315f112ef1ff349a0ba18c2ade9e4565bd9b
[ "Kotlin", "Gradle" ]
11
Kotlin
Capi15/MyMuseum
eb493a324a93cac7eddf354db11c0511113e9a71
2227ace012dd591cb8d5077c614ba712912e42c4
refs/heads/master
<file_sep># js-exercieses øvelser
a51d9baa01b7538a8105cc6bff77176051b97d64
[ "Markdown" ]
1
Markdown
trin455i/js-exercieses
c4ee68f56572af96973b681fca5c299c3040630b
78b0220c05174eca61a059262d8f0e77f1b53576
refs/heads/master
<repo_name>valeriyr82/ContactsApp<file_sep>/app.js /** * Module dependencies */ var express = require('express') fs = require('fs-extra'), routes = require('./routes'), api = require('./routes/api'), http = require('http'), path = require('path'), config = require('./config'); var app = module.exports = express(); /** * Configuration */ // all environments app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.static(path.join(__dirname, 'public'))); app.use(app.router); // development only if (app.get('env') === 'development') { app.use(express.errorHandler()); }; // production only if (app.get('env') === 'production') { // TODO }; // MySQL /*var mysql = require('mysql'); var db = mysql.createConnection({ host: config.db.mysql_host, user: config.db.mysql_user, password: <PASSWORD>, database: config.db.mysql_db, multipleStatements: true });*/ //PostgreSQL var pg = require('pg'); var conString = config.pg; var db = new pg.Client(conString); db.connect(); // Routes app.get('/', routes.index); app.get('/partial/:name', routes.partial); //USER API app.get('/api/getuserinfo/:id', api.getUserInfo(db)); //Person API app.put('/api/updateperson/:id', api.updatePerson(db)); app.delete('/api/deleteperson/:id', api.deletePerson(db)); //Organization API app.put('/api/updateorg/:id', api.updateOrg(db)); app.delete('/api/deleteorg/:id', api.deleteOrg(db)); //Email app.get('/api/getuseremails/:uid', api.getEmails(db)); app.post('/api/addemail', api.addEmail(db)); app.put('/api/setprimaryemail/:uid/:eid', api.setPrimaryEmail(db)); app.delete('/api/removeemail/:id', api.deleteEmail(db)); //Summary app.put('/api/updatesummary/:id', api.updateSummary(db)); //Image Upload app.get('/api/getpictures/:uid', api.getPictures(db)); app.post('/api/upload/:uid', api.uploadImage(db, fs, __dirname)); app.put('/api/setprimarypic/:uid/:pid', api.setPrimaryPic(db)); // redirect all others to the index (HTML5 history) app.get('*', routes.index); /** * Start Server */ http.createServer(app).listen(app.get('port'), function () { console.log('Express server listening on port ' + app.get('port')); });<file_sep>/views/index.jade extends layout block body header(ng-controller='AppCtrl') .navbar .navbar-inner .container-fluid a.brand(href="#") i.icon-heart-empty span Contact .collapse.nav-collapse ul.nav li a(href="contact/1") Contact ul.nav.pull-right li.dropdow.dark.user-menu a.dropdown-toggle(data-toggle="dropdown", href="#") span.user-name {{usernmae}} b.caret ul.dropdown-menu li a(href="#") i.icon-signout | Sign out ul.nav.pull-right li.only-icon a.btn-link(ng-click="open_create_contact_dlg()") i.icon-plus form.navbar-search.pull-right.hidden-phone div(style="margin:0;padding:0;display:inline") input(name="utf8", type="hidden", value="&#x2713;") button.btn.btn-link.icon-search(type='submit') input.search-query.span2(type='text', placeholder='Search...',id="q_header", name="q",autocomplete="off") div(modal="shouldBeOpen", close="close_create_contact_dlg()", options="opts") .modal-header button.close(data-dismiss="modal", type="button", ng-click="close_create_contact_dlg()") &times; h3 New Contact .modal-body.row-fluid .span12.text-center .span5 a.btn.btn-large(ng-click="open_person_dlg()") i.icon-user .span5 a.btn.btn-large(ng-click="open_org_dlg()") i.icon-briefcase .container-fluid.content div div(ng-view) script(src='js/lib/angular/angular.js') script(src='js/app.js') script(src='js/controllers/app_controller.js') script(src='js/controllers/contact_controller.js') script(src='js/services/global_utils.js') script(src='js/directives/ui-bootstrap-0.5.0.js') script(src='js/lib/jquery/jquery-2.0.3.min.js') script(src='js/lib/bootstrap/bootstrap.min.js') script(src='js/lib/plugins/flot/excanvas.js') script(src='js/lib/jquery_ui/jquery-ui.min.js') script(src='js/lib/plugins/fileupload/jquery.iframe-transport.min.js') script(src='js/lib/plugins/fileupload/jquery.fileupload.min.js') script(src='js/directives/imageupload.js')<file_sep>/views/layout.jade !!! html(ng-app="contactApp") head meta(content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no', name='viewport') meta(content='text/html;charset=utf-8', http-equiv='content-type') base(href='/') title Contact //if lt IE 9 script(src='/js/lib/html5shiv.js', type='text/javascript') link(rel='stylesheet', href='/css/bootstrap/bootstrap.css') link(rel='stylesheet', href='/css/bootstrap/bootstrap-responsive.css') link(rel='stylesheet', href='/css/light-theme.css', id='color-settings-body-color', media='all') link(rel='stylesheet', href='/css/app.css') body.contrast-green block body<file_sep>/public/js/services/global_utils.js angular.module("contactApp").factory("GlobalUtil", function($rootScope, $http) { function GlobalUtil(data) { angular.extend(this, data); } GlobalUtil.showDialogName = ''; GlobalUtil.displayDialog = function(name) { this.showDialogName = name; $rootScope.$broadcast('showDialog'); }; GlobalUtil.setImageName = function(name) { this.imgName = name; $rootScope.$broadcast("setImageName"); } return GlobalUtil; }); <file_sep>/routes/api.js /* * Serve JSON to our AngularJS client */ exports.getUserInfo = function(db) { return function(req, res) { var userid = req.params.id; db.query("SELECT a.id, a.username, a.primary_email, a.summary, a.firstname, a.lastname, " + "a.orgname, b.email, c.picname, a.primary_pic from users a " + "LEFT JOIN emails b ON a.primary_email = b.id " + "LEFT JOIN pictures c ON a.primary_pic = c.id " + "WHERE a.id = $1", [userid], function(err, rows) { if(err) res.json(null); if(rows) res.json(rows.rows); }); }; }; exports.updatePerson = function(db) { return function(req, res) { var id = req.route.params.id; var firstname = req.body.firstname; var lastname = req.body.lastname; db.query("UPDATE users SET firstname = $1, lastname = $2 WHERE id = $3", [firstname, lastname, id], function(err) { if(err) console.log(err); else res.json({success: 'success'}); }); }; }; exports.deletePerson = function(db) { return function(req, res) { var id = req.route.params.id; db.query("UPDATE users SET firstname = '', lastname = '' WHERE id = $1", [id], function(err) { if(err) console.log(err); else res.json({success: 'success'}); }); }; }; exports.updateOrg = function(db) { return function(req, res) { var id = req.route.params.id; var orgname = req.body.orgname; db.query("UPDATE users SET orgname = $1 WHERE id = $2", [orgname, id], function(err) { if(err) console.log(err); else res.json({success: 'success'}); }); }; }; exports.deleteOrg = function(db) { return function(req, res) { var id = req.route.params.id; db.query("UPDATE users SET orgname = '' WHERE id = $1", [id], function(err) { if(err) console.log(err); else res.json({success: 'success'}); }); }; }; exports.addEmail = function(db) { return function(req, res) { var email = req.body.email; var userid = req.body.userid; db.query("INSERT INTO emails(email, userid) VALUES($1, $2)", [email, userid], function(err, result) { res.json({id: result.insertId}); }); }; }; exports.getEmails = function(db) { return function(req, res) { var uid = req.params.uid; db.query("SELECT id, email FROM emails WHERE userid = $1", [uid], function(err, rows) { if(rows) res.json(rows.rows); if(err) res.json(null); }); }; }; exports.setPrimaryEmail = function(db) { return function(req, res) { var eid = req.params.eid; var uid = req.params.uid; db.query("UPDATE users SET primary_email = $1 WHERE id = $2", [eid, uid], function(err) { if(err) res.json(null); else res.json({success: "success"}); }); }; }; exports.deleteEmail = function(db) { return function(req, res) { var id = req.params.id; db.query("DELETE FROM emails WHERE id = $1", [id], function(err) { if(err) console.log(err); else res.json({success: "success"}); }); }; }; exports.updateSummary = function(db) { return function(req, res) { var id = req.params.id; var summary = req.body.summary; db.query("UPDATE users SET summary = $1 WHERE id = $2", [summary, id], function(err) { if(err) console.log(err); else res.json({success: "success"}); }); }; }; exports.getPictures = function(db) { return function(req, res) { var uid = req.params.uid; db.query("SELECT id, picname FROM pictures WHERE userid = $1", [uid], function(err, rows) { if(rows) res.json(rows.rows); if(err) res.json(null); }); }; }; exports.uploadImage = function(db, fs, dirpath) { return function(req, res) { var uid = req.params.uid; var new_path = dirpath + '/public/images/photos/'; var file_name = req.files.file.name; fs.copy(req.files.file.path, new_path + file_name, function(err) { if(err) res.json(null); else { db.query("INSERT INTO pictures(picname, userid) VALUES($1, $2)", [file_name, uid], function(err, result) { if(err) res.json(null); else res.json({photo: file_name, id: result.insertId}); }); } }); }; }; exports.setPrimaryPic = function(db) { return function(req, res) { var pid = req.params.pid; var uid = req.params.uid; db.query("UPDATE users SET primary_pic = $1 WHERE id = $2", [pid, uid], function(err) { if(err) res.json(null); else res.json({success: "success"}); }); }; };<file_sep>/public/js/controllers/contact_controller.js 'use strict'; function ContactCtrl($scope, $rootScope, $routeParams ,$http, GlobalUtil) { $scope.userid = $routeParams.id; getUserInfo(); function getUserInfo() { $http.get('/api/getuserinfo/' + $scope.userid).success(function(response) { console.log(response); $scope.firstname = response[0].firstname; $scope.lastname = response[0].lastname; $scope.orgname = response[0].orgname; $scope.primaryemail = response[0].primary_email; $scope.primaryemailtxt = response[0].email; $scope.primarypic = response[0].primary_pic; $scope.primarypicname = response[0].picname; $scope.summary = response[0].summary; $rootScope.usernmae = response[0].username; }).error(function(err) { console.log(err); }); } getEmails(); function getEmails() { $http.get('/api/getuseremails/' + $scope.userid).success(function(data) { $scope.emails = data; $scope.rows = []; $scope.cols = []; $scope.$watch("emails.length", function() { $scope.rows.length = Math.ceil($scope.emails.length / 2); $scope.cols.length = 2; }); }).error(function(err) { console.log(err); }); } getPictures(); function getPictures() { $http.get('/api/getpictures/' + $scope.userid).success(function(data) { $scope.pictures = data; $scope.prows = []; $scope.pcols = []; $scope.$watch("pics.length", function() { $scope.prows.length = Math.ceil($scope.pictures.length / 4); $scope.pcols.length = 4; }); }).error(function(err) { console.log(err); }); } $scope.open_add_email_dlg = function () { $scope.isEmailDlgOpen = true; }; $scope.close_add_email_dlg = function () { $scope.isEmailDlgOpen = false; }; $scope.save_email = function() { var email = {'email': $scope.email, 'userid': $scope.userid}; $http.post('/api/addemail', email).success(function(data) { getEmails(); }).error(function(data) { }); $scope.isEmailDlgOpen = false; }; $scope.removeemail = function(email_id) { $http.delete('/api/removeemail/'+email_id).success(function(data) { getEmails(); getUserInfo(); }).error(function(data) { }); }; $scope.setprimaryemail = function(email_id) { $http.put('/api/setprimaryemail/' + $scope.userid + '/' +email_id).success(function(data) { getUserInfo(); }).error(function(data) { }); }; $scope.open_person_dlg = function (newPerson) { $scope.title = newPerson ? "Create Person" : "Edit Person"; $scope.button_title = newPerson ? "Create" : "Save"; $scope.isPersonDlgOpen = true; $scope.first_name = $scope.firstname; $scope.last_name = $scope.lastname; }; $scope.close_person_dlg = function () { $scope.isPersonDlgOpen = false; }; $scope.$on('showDialog', function() { if(GlobalUtil.showDialogName == 'person') { $scope.open_person_dlg(true); $scope.isPersonDlgOpen = true; } else if(GlobalUtil.showDialogName == 'organization') { $scope.open_org_dlg(true); $scope.isOrgDlgOpen = true; } }); $scope.$on("setImageName", function(name) { $scope.$apply(function() { $scope.isImgDlgOpen = false; }); getPictures(); }); $scope.save_person = function() { var person = {firstname: $scope.first_name, lastname: $scope.last_name}; $http.put('/api/updateperson/'+$scope.userid, person).success(function(data) { $scope.isPersonDlgOpen = false; $scope.firstname = $scope.first_name; $scope.lastname = $scope.last_name; $scope.first_name = ""; $scope.last_name = ""; }).error(function(data) { }); } $scope.delete_person = function() { $http.delete('/api/deleteperson/'+$scope.userid).success(function(data) { $scope.firstname = ''; $scope.lastname = ''; }).error(function(data) { }); }; $scope.open_org_dlg = function(newOrg) { $scope.title = newOrg ? "Create Organization" : "Edit Organization"; $scope.button_title = newOrg ? "Create" : "Save"; $scope.isOrgDlgOpen = true; $scope.org_name = $scope.orgname; } $scope.close_org_dlg = function() { $scope.isOrgDlgOpen = false; } $scope.delete_org = function() { $http.delete('/api/deleteorg/'+$scope.userid).success(function(data) { $scope.orgname = ""; }).error(function(data) { }); }; $scope.save_organization = function() { var organization = {orgname: $scope.org_name}; $http.put('/api/updateorg/'+$scope.userid, organization).success(function(data) { $scope.isOrgDlgOpen = false; $scope.orgname = $scope.org_name; $scope.org_name = ""; }).error(function(data) { }); }; $scope.save_summary = function() { var summary = {summary: $scope.txtsummary} $http.put('/api/updatesummary/'+$scope.userid, summary).success(function(data) { $scope.summary = $scope.txtsummary; $scope.isSummaryDlgOpen = false; }).error(function(data) { }); }; $scope.open_summary_dlg = function() { $scope.txtsummary = $scope.summary; $scope.isSummaryDlgOpen = true; }; $scope.close_summary_dlg = function() { $scope.isSummaryDlgOpen = false; }; $scope.open_img_dlg = function() { $scope.isImgDlgOpen = true; }; $scope.close_img_dlg = function() { $scope.isImgDlgOpen = false; }; $scope.setprimarypic = function(pic_id) { $http.put('/api/setprimarypic/' + $scope.userid + '/' + pic_id).success(function(data) { getUserInfo(); }).error(function(data) { }); }; $scope.opts = { backdropFade: true, dialogFade:true }; } <file_sep>/contact_sql.sql /* SQLyog - Free MySQL GUI v5.15 Host - 5.5.24-log : Database - contacts ********************************************************************* Server version : 5.5.24-log */ SET NAMES utf8; SET SQL_MODE=''; create database if not exists `contacts`; USE `contacts`; SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO'; /*Table structure for table `emails` */ DROP TABLE IF EXISTS `emails`; CREATE TABLE `emails` ( `id` int(10) NOT NULL AUTO_INCREMENT, `email` varchar(50) NOT NULL, `userid` int(10) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1; /*Table structure for table `user` */ DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(10) NOT NULL AUTO_INCREMENT, `username` varchar(30) NOT NULL, `firstname` varchar(50) NOT NULL, `lastname` varchar(30) NOT NULL, `orgname` varchar(100) NOT NULL, `primary_email` int(10) NOT NULL, `summary` text NOT NULL, `photo` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1; SET SQL_MODE=@OLD_SQL_MODE;<file_sep>/config.js //MySQL Config exports.db = { "mysql_host" : "127.0.0.1", "mysql_user" : "root", "mysql_pass" : "", "mysql_db" : "contacts" }; exports.pg = "tcp://postgres:123456@localhost/contact";<file_sep>/README.md Workplace Contacts ======== Application creates modifies and deletes contact information for people and organizations. Contact Profiles -------- There are two types of contact profile: 1. Person: model requires first name and last name 2. Organization: model requires name Users create person and organization profiles. Users -------- User: models requires person profile, username and password Users create users, in other words no self-registration. Permissions -------- Each user have model based CRUD permissions: e.g. Create-Person, Retrieve-Person, Update-Person, Delete-Person <file_sep>/public/js/directives/imageupload.js angular.module("contactApp").directive('dragDropUpload', ['GlobalUtil', function(GlobalUtil) { // Helper function that formats the file sizes function formatFileSize(bytes) { if (typeof bytes !== 'number') { return ''; } if (bytes >= 1000000000) { return (bytes / 1000000000).toFixed(2) + ' GB'; } if (bytes >= 1000000) { return (bytes / 1000000).toFixed(2) + ' MB'; } return (bytes / 1000).toFixed(2) + ' KB'; } return { restrict: 'A', scope: { userId: '=' }, link: function(scope, elem, attr, ctrl) { var dragForm = "<form id='file-upload' method='post' action='" + attr.submitUrl + scope.userId +"' enctype='multipart/form-data'> \ <div id='drop'> \ Drop Here<br> \ <a>Browse</a> \ <input type='file' name='file' multiple /> \ </div> \ </form>"; $(elem).html(dragForm).promise().done(function() { $(this).find("#file-upload #drop a").on('click', function() { $(this).parent().find('input').click(); }); $(this).find("#file-upload").fileupload({ // This element will accept file drag/drop uploading dropZone: $(this).find("#file-upload #drop"), add: function(e, data) { data.submit(); }, done: function(e, data) { GlobalUtil.setImageName(data.result.photo); } }); }); // Prevent the default action when a file is dropped on the window $(document).on('dragover', function (e) { e.preventDefault(); $('#drop').addClass('active'); }); $(document).on('drop dragleave', function (e) { e.preventDefault(); $('#drop').removeClass('active'); }); } } }]); <file_sep>/views/partials/contact.jade .row-fluid .span12 .span3 .box-content img(alt="230x230&amp;text=photo", ng-src="images/photos/{{primarypicname}}") .span9.box .box-header(ng-hide="firstname == '' && lastname == ''") .title h2 {{firstname}} {{lastname}} .actions a.btn.btn-link.edit(ng-click="open_person_dlg(false)") i.icon-pencil a.btn.btn-link.remove(ng-click="delete_person()") i.icon-remove .box-header(ng-hide="orgname == ''") .title h2 {{orgname}} .actions a.btn.btn-link.edit(ng-click="open_org_dlg(false)") i.icon-pencil a.btn.btn-link.remove(ng-click="delete_org()") i.icon-remove .box-header .title | Pictures .actions a.btn.btn-link(ng-click="open_img_dlg()") i.icon-plus .box-header(ng-repeat="row in prows") .span3(ng-repeat="item in pcols", ng-show="pictures[$parent.$index*4 + $index]") .box-header img(ng-src="images/photos/{{pictures[$parent.$index*4 + $index].picname}}",ng-click="setprimarypic(pictures[$parent.$index*4 + $index].id)") .box-header .title | Emails .actions a.btn.btn-link(ng-click="open_add_email_dlg()") i.icon-plus .box-header .span6 .box-content | {{primaryemailtxt}} .box-header(ng-repeat="row in rows") .span6(ng-repeat="item in cols", ng-show="emails[$parent.$index*2 + $index]") .box-header .title | {{emails[$parent.$index*2 + $index].email}} .actions a.btn.btn-link(ng-click="setprimaryemail(emails[$parent.$index*2 + $index].id)") i.icon-star a.btn.btn-link(ng-click="removeemail(emails[$parent.$index*2 + $index].id)") i.icon-remove .box-header .title | Summary .actions a.btn.btn-link.edit(ng-click="open_summary_dlg()") i.icon-pencil .box-content | {{summary}} div(modal="isImgDlgOpen", close="close_img_dlg()", options="opts") .modal-header button.close(data-dismiss="modal", type="button", ng-click="close_img_dlg()") &times; h3 Image Upload .modal-body.row-fluid .span12.text-center div(drag-drop-upload, user-id='userid', submit-url='/api/upload/') div(modal="isSummaryDlgOpen", close="close_summary_dlg()", options="opts") .modal-header button.close(data-dismiss="modal", type="button", ng-click="close_summary_dlg()") &times; h3 Edit Summary .modal-body.row-fluid .span12.text-center form.form.form-horizontal(name="summary_form", style='margin-bottom: 0;', novalidate) textarea(rows=8, cols=30, ng-model="txtsummary") .modal-footer a.btn.btn-primary(ng-click="save_summary()") Save div(modal="isEmailDlgOpen", close="close_add_email_dlg()", options="opts") .modal-header button.close(data-dismiss="modal", type="button", ng-click="close_add_email_dlg()") &times; h3 Add Email .modal-body.row-fluid .span12.text-center form.form.form-horizontal(name="email_form", style='margin-bottom: 0;', novalidate) input(data-rule-email='true', data-rule-required='true', id='new_email', name='new_email', placeholder='E-mail', type='email', ng-model="email", required) span.text-red(ng-show="email_form.new_email.$error.required") Required! span.text-red(ng-show="email_form.new_email.$error.email") No valid email! .modal-footer a.btn.btn-primary(ng-disabled="email_form.$invalid", ng-click="save_email()") Create div(modal="isPersonDlgOpen", close="close_person_dlg()", options="opts") .modal-header button.close(data-dismiss="modal", type="button", ng-click="close_person_dlg()") &times; h3 {{title}} .modal-body.row-fluid .span12.text-center form.form.form-horizontal(name="person_form", style='margin-bottom: 0;', novalidate) .control-group input(data-rule-email='true', data-rule-required='true', id='first_name', name='first_name', placeholder='<NAME>', type='text', ng-model="first_name", required) span.text-red(ng-show="person_form.first_name.$error.required") Required! .control-group input(data-rule-email='true', data-rule-required='true', id='last_name', name='last_name', placeholder='<NAME>', type='text', ng-model="last_name", required) span.text-red(ng-show="person_form.last_name.$error.required") Required! .modal-footer a.btn.btn-primary(ng-disabled="person_form.$invalid", ng-click="save_person()") {{button_title}} div(modal="isOrgDlgOpen", close="close_org_dlg()", options="opts") .modal-header button.close(data-dismiss="modal", type="button", ng-click="close_org_dlg()") &times; h3 {{title}} .modal-body.row-fluid .span12.text-center form.form.form-horizontal(name="org_form", style='margin-bottom: 0;', novalidate) .control-group input(data-rule-email='true', data-rule-required='true', id='org_name', name='org_name', placeholder='Organization', type='text', ng-model="org_name", required) span.text-red(ng-show="org_form.org_name.$error.required") Required! .modal-footer a.btn.btn-primary(ng-disabled="org_form.$invalid", ng-click="save_organization()") {{button_title}}<file_sep>/public/js/app.js 'use strict'; // Declare app level module which depends on filters, and services angular.module('contactApp', ['ui.bootstrap']). config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) { $routeProvider.when('/contact/:id', {templateUrl: 'partial/contact', controller: ContactCtrl}); $routeProvider.otherwise({redirectTo: '/'}); $locationProvider.html5Mode(true); }]);
04508dc06de9488a65ac634929aac404b28ea01d
[ "Markdown", "SQL", "JavaScript", "Pug" ]
12
Markdown
valeriyr82/ContactsApp
380bd5f9be3a07d1be5a79d87e0682f0a5914e06
d75527b252e194a783ed408c7e20809114cd6e71
refs/heads/master
<file_sep><!DOCTYPE html> <html lang="en"> <?php include("includes/head.html"); ?> <body> <?php include("includes/navigation.html"); ?> <div class="container"> <?php include("includes/header.html"); ?> <div id="page" class="projects" display="none"></div> <!-- Start page content --> <h2>Projects</h2> <p> Listed below are a few of my personal projects. </p> <div class="row"> <div class="col-xs-8 col-sm-6 col-md-4"> <div class="thumbnail"> <div class="well well-sm"> <img src="/img/mirror.png" class="img-responsive img-rounded"> </div> <div class="caption caption-uniform-block"> <h3>Mirror</h3> <p> A mirror simulation app with some extra features that was made for the Android platform. </p> </div> <div class="caption"> <a href="https://github.com/bjcrawford/Mirror-Core" class="btn btn-primary" role="button">Explore Code &raquo;</a> <a href="https://play.google.com/store/apps/details?id=com.wckd_dev.mirror" class="btn btn-primary" role="button">Play Store &raquo;</a> </div> </div> </div> <div class="col-xs-8 col-sm-6 col-md-4"> <div class="thumbnail"> <div class="well well-sm"> <img src="/img/bc_shell.png" class="img-responsive img-rounded"> </div> <div class="caption caption-uniform-block"> <h3>bc_shell</h3> <p> A command line interpreter written for use within a linux enviroment. </p> </div> <div class="caption"> <a href="http://github.com/bjcrawford/bc_shell" class="btn btn-primary" role="button">Explore Code &raquo;</a> </div> </div> </div> <div class="col-xs-8 col-sm-6 col-md-4"> <div class="thumbnail"> <div class="well well-sm"> <img src="/img/gravity.png" class="img-responsive img-rounded"> </div> <div class="caption caption-uniform-block"> <h3>Gravity</h3> <p> A space themed adventure/puzzle game created for the Android platform. </p> </div> <div class="caption"> <a href="http://github.com/bjcrawford/Gravity" class="btn btn-primary" role="button">Explore code &raquo;</a> </div> </div> </div> <div class="col-xs-8 col-sm-6 col-md-4"> <div class="thumbnail"> <div class="well well-sm"> <img src="/img/raspibuilds.png" class="img-responsive img-rounded"> </div> <div class="caption caption-uniform-block"> <h3>RasPi Builds</h3> <p> A web application built using JSP, HTML, CSS, JS, and SQL. </p> </div> <div class="caption"> <a href="http://cis-linux2.temple.edu:8080/SP15_2308_tuf00901/index.jsp" class="btn btn-primary" role="button">Explore Site &raquo;</a> </div> </div> </div> <div class="col-xs-8 col-sm-6 col-md-4"> <div class="thumbnail"> <div class="well well-sm"> <img src="/img/genalgs.png" class="img-responsive img-rounded"> </div> <div class="caption caption-uniform-block"> <h3>Genetic Algorithms</h3> <p> An analysis of genetic algorithm variations written in Java. </p> </div> <div class="caption"> <a href="http://github.com/bjcrawford/SGAVariationAnalysis" class="btn btn-primary" role="button">Explore Code &raquo;</a> </div> </div> </div> <div class="col-xs-8 col-sm-6 col-md-4"> <div class="thumbnail"> <div class="well well-sm"> <img src="/img/sia.png" class="img-responsive img-rounded"> </div> <div class="caption caption-uniform-block"> <h3>Stock Information App</h3> <p> An informational stock portfolio application created for the Android platform. </p> </div> <div class="caption"> <a href="http://github.com/bjcrawford/StockInformationApp" class="btn btn-primary" role="button">Explore Code &raquo;</a> </div> </div> </div> <div class="col-xs-8 col-sm-6 col-md-4"> <div class="thumbnail"> <div class="well well-sm"> <img src="/img/bst-puzzle.png" class="img-responsive img-rounded"> </div> <div class="caption caption-uniform-block"> <h3>BST Puzzle</h3> <p> A binary search tree puzzle game built with Java. </p> </div> <div class="caption"> <a href="https://github.com/bjcrawford/BST-Puzzle" class="btn btn-primary" role="button">Explore Code &raquo;</a> </div> </div> </div> <div class="col-xs-8 col-sm-6 col-md-4"> <div class="thumbnail"> <div class="well well-sm"> <img src="/img/hashtablevisualization.png" class="img-responsive img-rounded"> </div> <div class="caption caption-uniform-block"> <h3>VisualHashTable</h3> <p> A hash table visualization made with Java. </p> </div> <div class="caption"> <a href="http://github.com/bjcrawford/VisualHashTable" class="btn btn-primary" role="button">Explore Code &raquo;</a> </div> </div> </div> <div class="col-xs-8 col-sm-6 col-md-4"> <div class="thumbnail"> <div class="well well-sm"> <img src="/img/callcentersim.png" class="img-responsive img-rounded"> </div> <div class="caption caption-uniform-block"> <h3>CallCenterSim</h3> <p> A call center simulation created using Java. </p> </div> <div class="caption"> <a href="http://github.com/bjcrawford/CallCenterSim" class="btn btn-primary" role="button">Explore Code &raquo;</a> </div> </div> </div> </div> <!-- End page content --> <?php include("includes/footer.html"); ?> </div> <script>initPage();</script> </body> </html><file_sep><!DOCTYPE html> <html lang="en"> <?php include("includes/head.html"); ?> <body> <?php include("includes/navigation.html"); ?> <div class="container"> <?php include("includes/header.html"); ?> <div id="page" class="contact" display="none"></div> <!-- Start page content --> <h1>Contact me</h1> <hr> <h3>Email:</h3> <p class="indent"> brettjamescrawford (at) gmail (dot) com </p> <h3>Other:</h3> <p class="indent"> <a href="http://www.linkedin.com/in/brettjcrawford"><NAME></a> (LinkedIn)<br/> <a href="https://github.com/bjcrawford">bjcrawford</a> (Github)<br/> <a href="http://www.wckd-dev.com">wckdDev</a> (Mobile Development) </p> <!-- End page content --> <?php include("includes/footer.html"); ?> </div> <script>initPage();</script> </body> </html><file_sep><!DOCTYPE html> <html lang="en"> <?php include("includes/head.html"); ?> <body> <?php include("includes/navigation.html"); ?> <div class="container"> <?php include("includes/header.html"); ?> <div id="page" class="home" display="none"></div> <!-- Start page content --> <div class="row"> <div class="col-xs-5 col-sm-5 col-md-5"> <img src="/img/me.jpg" class="img-responsive img-rounded"> </div> <div class="col-xs-7 col-sm-7 col-md-7"> <h2>About Me</h2> <p> My name is <NAME>. I graduated in spring of 2015 from Temple University in Philadelphia, PA with a degree in computer science. I enjoy all things computer and technology related and thrive on the idea of using technology to make our lives better. Recently, I have been working/<a href="http://imgur.com/a/mQdXJ">playing</a> with the Raspberry Pi in various ways, becoming familiar with Mac OS X, and working on my Android mobile application development company, <a href="http://www.wckd-dev.com">wckdDev</a>. I have just moved to Iowa City, Iowa to join my wife, Kate, as she attends the University of Iowa and to start a new position at Rockwell Collins in Cedar Rapids. We live together with our 5 year old pug, Oscar. </p> <br/> <h2>LinkedIn</h2> <p>You can view my experience and skills or connect with me on my LinkedIn profile.</p> <p><a href="http://www.linkedin.com/in/brettjcrawford" class="btn btn-primary" role="button">Visit my LinkedIn Profile &raquo;</a></p> </div> </div> <!-- End page content --> <?php include("includes/footer.html"); ?> </div> <script>initPage();</script> </body> </html><file_sep><!DOCTYPE html> <html lang="en"> <?php include("includes/head.html"); ?> <body> <?php include("includes/navigation.html"); ?> <div class="container"> <?php include("includes/header.html"); ?> <div id="page" class="resume" display="none"></div> <!-- Start page content --> <div class="row"> <div class="col-xs-6 col-sm-8 col-md-9"> <div class="well well-sm"> <img src="/docs/BrettJCrawford.png" class="img-responsive"> </div> </div> <div class="col-xs-6 col-sm-4 col-md-3"> <br/> <h2>Resume Formats</h2> <ul> <li><a href="/docs/BrettJCrawford.doc">BrettJCrawford.doc</a></li> <li><a href="/docs/BrettJCrawford.docx">BrettJCrawford.docx</a></li> <li><a href="/docs/BrettJCrawford.txt">BrettJCrawford.txt</a></li> <li><a href="/docs/BrettJCrawford.pdf">BrettJCrawford.pdf</a></li> <li><a href="/docs/BrettJCrawford.png">BrettJCrawford.png</a></li> </ul> </div> </div> <!-- End page content --> <?php include("includes/footer.html"); ?> </div> <script>initPage();</script> </body> </html>
99982afa74d6201ac9f4d40d52f000174a1a7c57
[ "PHP" ]
4
PHP
bjcrawford/BJC_Website
a9fee1ba6eacd1f455198b8e8e3c22be4eb8bf34
4c4b41f95164e5522a835dd2370b74a223319ef2
refs/heads/master
<repo_name>serg83/pizza_project<file_sep>/App.js import React, { Component } from "react"; import EmailForm from '/EmailForm.js'; import AppRouter from './MainPage.js'; //import { Router, Route, Link, Switch } from 'react-router-dom'; //import fontawesome from 'fortawesome'; //npm install --save react-fontawesome //import { Router, Route, Link, Switch } from "react-router-dom"; // import "./styles.css"; /*const inputStyle = { width: 235, margin: 5 }*/ /* index.html---font-awesome shopping cart <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"></link>*/ class App extends Component { constructor(props) { super(props); this.state = { pizza: [ { name: "pizza capriciosa" }, { price: "price : 15 $" } ], count: 0, quantity: 0, price: 0 }; this.increment = this.increment.bind(this); this.decrement = this.decrement.bind(this); } increment() { this.setState({ count: this.state.count + 1, quantity: this.state.quantity + 1, price: this.state.price + 15 }); } decrement() { if (this.state.count > 0) { this.setState({ count: this.state.count - 1, quantity: this.state.quantity - 1, price: this.state.price - 15 }); } } render() { /*const inputStyle*/ /*const renderOnline = */ const pizzas = this.state.pizza.map((item, index) => ( <li key={index}>{item.name}{item.price}</li> )); return ( /* style={inputStyle}*/ <div className="App" style={{ backgroundColor: "pink", width: 750 }}> <AppRouter /> <h1>Shopping Cart: {this.state.count + " items"} <a href='/EmailForm/' ><button style={{ color: "green", fontSize: 24, borderRadius: 3 }}> Order <i className="fa fa-shopping-cart" /> </button></a> </h1> <button style={{ color: "blue", fontSize: 24, borderRadius: 3 }} type="button"onClick={this.increment} >Add </button> <button style={{ color: "red", fontSize: 24, borderRadius: 3 }} type="button" onClick={this.decrement} > Remove </button> <ul> {pizzas} <li>{this.state.quantity + " selected pizza(s)"}</li> </ul> <h1>Total Price: {this.state.price + " $"}</h1> <EmailForm /> <img src="https://images.unsplash.com/photo-1513104890138-7c749659a591?ixlib=rb-1.2.1&amp;ixid=eyJhcHBfaWQiOjEyMDd9&amp;auto=format&amp;fit=crop&amp;w=750&amp;q=80 750w" alt="pizza" /> </div> ); } } export default App <file_sep>/src/index.js import React from "react"; import ReactDOM from "react-dom"; import App from '../App.js'; //import AppRouter from '/MainPage.js'; //import styles.css const app = document.getElementById("root"); ReactDOM.render(<App />, app); <file_sep>/EmailForm.js import React, { Component } from "react"; import { Button, Form, FormGroup, Label, Input, FormText } from "reactstrap"; import axios from "axios"; class EmailForm extends Component { constructor(props) { super(props); this.state = { email: "", text: "" }; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(event) { this.setState({ [event.target.name]: event.target.value }); } async handleSubmit(event) { event.preventDefault(); const { email, text } = this.state; const form = await axios.post("/api/form", { email, text }); } render() { return ( <div> <p>Email Form: Delivery</p> <Form onSubmit={this.handleSubmit}> <FormGroup> <Label for="email">Email: </Label> <Input type="email" name="email" id="Email" placeholder="Place your Email" onChange={this.handleChange} /> </FormGroup> <br /> <FormGroup> <Label for="comments">Comments: </Label> <Input type="textarea" name="text" id="Text" onChange={this.handleChange} /> </FormGroup> <br /> <Button style={{ backgroundColor: "red", color: "white", fontSize: 24, borderRadius: 3 }} > Place Order </Button> </Form> </div> ); } } export default EmailForm;
0458ebb3c8ed493dc1c6c082e4c65f91a3e67c0a
[ "JavaScript" ]
3
JavaScript
serg83/pizza_project
790a2c749c5d2fb232d466227355c6212d6f6ae1
17bbcee1dd4a87042542aacb568b83f111080bb8
refs/heads/master
<file_sep># firm-construction <file_sep>window.onload = function() { 'use strict'; var launch = { init: function(){ menu.click(); } }; var menu = { click: function() { var menuClick = document.querySelector('header .menu-button'), menu = document.querySelector('#menu'), navItems = document.querySelectorAll('#menu .navigation li'), body = document.querySelector('body'); menuClick.addEventListener('click', function() { if(this.classList.contains('is-active')) { this.classList.remove('is-active'); menu.classList.remove('is-active'); body.classList.remove('no-scroll'); } else { this.classList.add('is-active'); menu.classList.add('is-active'); body.classList.add('no-scroll'); } }); Array.prototype.forEach.call(navItems, function (item) { item.addEventListener('click', function() { menuClick.classList.toggle('is-active'); menu.classList.toggle('is-active'); }) }); } }; launch.init(); };
ee2845511aa573dd8102a073e7875b7a1e20fe75
[ "Markdown", "JavaScript" ]
2
Markdown
tijsluitse/firm-construction
a8480a79b19c950d2079ac45ec6687ecf4c6c9be
13ee7d720ff0e599534c246ddd607ab0fc044c14
refs/heads/master
<file_sep>#!/bin/bash function preInstall { yum install -y tar wget git wget http://repos.fedorapeople.org/repos/dchen/apache-maven/epel-apache-maven.repo -O /etc/yum.repos.d/epel-apache-maven.repo yum install -y epel-release cat > /etc/yum.repos.d/wandisco-svn.repo <<EOF [WANdiscoSVN] name=WANdisco SVN Repo 1.9 enabled=1 baseurl=http://opensource.wandisco.com/centos/7/svn-1.9/RPMS/$basearch/ gpgcheck=1 gpgkey=http://opensource.wandisco.com/RPM-GPG-KEY-WANdisco EOF yum update systemd yum groupinstall -y "Development Tools" yum install -y apache-maven python-devel java-1.8.0-openjdk-devel zlib-devel libcurl-devel openssl-devel cyrus-sasl-devel cyrus-sasl-md5 apr-devel subversion-devel apr-util-devel } function mesos { wget http://www.apache.org/dist/mesos/0.28.1/mesos-0.28.1.tar.gz tar -zxf mesos-0.28.1.tar.gz mv mesos-0.28.1 mesos cd mesos ./bootstrap mkdir build cd build ../configure make } preInstall mesos <file_sep># TestVagrant VagrantTest <file_sep>#!/bin/bash function installCommon { echo "install tar wget git" yum install -y tar wget git } function installJava { echo "install open jdk" wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/7u79-b15/jdk-7u79-linux-x64.tar.gz" tar xzf jdk-7u79-linux-x64.tar.gz mv jdk1.7.0_79 java mv java /opt/ rm jdk-7u79-linux-x64.tar.gz echo "creating java environment variables" echo export JAVA_HOME=/opt/java >> /etc/profile.d/java.sh echo export PATH=\${JAVA_HOME}/bin:\${PATH} >> /etc/profile.d/java.sh } function setRootPasswd { echo "[setup root password & gen ssh key]" echo "vagrant" | passwd root --stdin } function setssh { mkdir -p /root/.ssh ssh-keygen -t rsa -N "" -f "/root/.ssh/id_rsa" } function setHosts { rm /etc/hosts echo "192.168.1.44 dfnode1" >> /etc/hosts echo "192.168.1.45 dfnode2" >> /etc/hosts echo "192.168.1.46 dfnode3" >> /etc/hosts #TOTAL_NODES=2 #for i in $(seq 1 $TOTAL_NODES) #do # entry="10.211.55.10${i} node${i}" # echo "adding ${entry}" # echo "${entry}" >> /etc/nhosts #done #cp /etc/nhosts /etc/hosts } installCommon #installJava setRootPasswd setssh setHosts <file_sep># -*- mode: ruby -*- # vi: set ft=ruby : nodes = [ { :hostname => 'dfnode1', :ip => '192.168.1.44' }, { :hostname => 'dfnode2', :ip => '192.168.1.45' }, { :hostname => 'dfnode3', :ip => '192.168.1.46' } ] Vagrant.configure(2) do |config| nodes.each do |node| config.vm.define node[:hostname] do |nodeconfig| nodeconfig.vm.box = "centos/7" nodeconfig.vm.network "public_network", ip:node[:ip], bridge:"enp8s0" nodeconfig.vm.hostname = node[:hostname] nodeconfig.vm.provider "virtualbox" do |vb| vb.memory = "16384" vb.cpus = "8" end nodeconfig.vm.provision "shell", path: "./common.sh" nodeconfig.vm.provision "shell", path: "./install_mesos.sh" end end end
0a807c9cd0acd3887e64f8e7a9f69f23d54cb305
[ "Markdown", "Shell", "Ruby" ]
4
Markdown
deandu540/TestVagrant
dbe954170116664f32db6dbfc331efc1e22f052e
60bc38c7868227281d6419a5d631d1c5962df72b
refs/heads/master
<file_sep># hello-world My first repository11!!1! I created this repository which is my first repository. I will do the directions at https://guides.github.com/activities/hello-world. After when I am more experienced with github i will add some sample programs here. I'm a github user. I live on Earth. I like programming.
37ccbaed0bd66d4a1104d36e30c44bc491743c6f
[ "Markdown" ]
1
Markdown
ev3commander/hello-world
0e7d3cbc73218f8131e20c1c01f84b85950e5ac7
1b56edddcc79d80719b9561af377329893194e34
refs/heads/main
<file_sep># <NAME> 2015202074 Veb aplikacija za on-lajn prodaju tehničkih proizvoda Aplikacija treba da omogući administratorima da dodaju nove artikle u bazu podataka aplikacije za elektronsku trgovinu. Samo prijavljeni korisnici, koji se na portal prijave sa ispravnih parametrima naloga administratora sadržaja mogu da pristupe administrativnom panelu portala. U ovom panelu mogu da dodaju nove proizvode koji se sastoji od naslova, slike, detaljnog opisa proizvoda, cene i treba da pripadaju određenoj kategoriji. Sa korisničke strane treba omogućiti prikaz svih proizvoda poređanih po ceni za svaku od kategorija. Kategorije prikazati u vidu menija na veb sajtu, gde svaka kategorija ima opis i sliku koja predstavlja generalizovani prikaz vrste proizvoda koje obuhvata. Kada korisnik otvori stranicu nekog proizvoda, treba da vidi sve detalje o proizvodu, kao što su naslov, slika, opis i cena i da dobije mogućnost da izvrši kupovinu, tj. naručivanje određenog proizvoda. Izabrani proizvod treba čuvati u korpi proizvoda dokle god korisnik ne odabere opciju za kraj kupovine. Na kraju kupovine, prikazati korisniku listu proizvoda koje je dodao u korpu i ponuditi da neki proizvod obriše, da se vrati nazad na kupovinu ili da potvrdi kupovinu. Ako korisnik potvrdi kupovinu, uzeti podatke o korisniku, među kojima su ime, prezime, poštanska adresa i adresa elektronske pošte, a korisniku prikazati izgled uplatnice, sa pozivom na broj koji je identifikacioni broj porudžbine, njegove podatke i podatke primaoca, sa prikazom tekućeg računa i svrhom uplate. Poslati korisniku na adresu elektronske pošte koju je upisao u formularu prilikom narudžbine listing stavki koje je kupio. Grafički interfejs veb sajta treba da bude realizovan sa responsive dizajnom.
efc8a736b4e99ab909c785e925095a3cfaf60d60
[ "Markdown" ]
1
Markdown
djmilosh88/milosdjokic
40a584a99f0fbe0b969ec7b899980097c33d332b
7863cedb70987e747d95337fd470640df3e3f04e
refs/heads/master
<repo_name>jhoa2708/Estadistica<file_sep>/Analisis_Datos.R library(readxl ) Datos<- read_excel("D:/TESIS_rev/TESIS_DATA/Datos_estadistica_ordenados_1.xlsx") #Convierto datos en dataframe Datos <- as.data.frame(Datos) Datos <- data.frame(Datos[,-1], row.names=Datos[,1]) ################################# #Creo las variables iniciales #Datos concentraciones totales Datos_CT<-Datos[,c(1:7,12,17,22,27,32,37,42,47,52,53)] #Concentraciones totales solo numeros Datos_Num <-Datos[,c(1:51)] #Concentraciones totales solo numeros Datos_Num_CT<-Datos_Num[,c(1:7,12,17,22,27,32,37,42,47)] #Temporada seca solo numeros Datos_Num_TS<-Datos_Num[c(0:10),] #Temporada humeda solo numeros Datos_Num_TH<-Datos_Num[c(11:20),] ################################# #Correlacion de datos(Solo se puede usar datos numericos) #Todos los datos Corr<-round(cor(Datos_Num),2) #Temporada seca Corr_TS<-round(cor(Datos_Num_TS),2) #Temporada humeda Corr_TH<-round(cor(Datos_Num_TH),2) #Concentraciones totales Corr_CT<-round(cor(Datos_Num_CT),2) # Solo triangulo superior para concentraciones totales Upper_Corr_CT<-Corr_CT Upper_Corr_CT[lower.tri(Upper_Corr_CT)]<-"" Upper_Corr_CT<-as.data.frame(Upper_Corr_CT) print(Upper_Corr_CT) #De ahora en adelante se usará los valores para la correlacion de concentraciones totales #Tabla de valores de correlacion y pearson library("Hmisc") Corr_CT_1<- rcorr(as.matrix(Datos_Num_CT)) # flattenCorrMatrix # cormat : matrix of the correlation coefficients # pmat : matrix of the correlation p-values flattenCorrMatrix <- function(cormat, pmat) { ut <- upper.tri(cormat) data.frame( row = rownames(cormat)[row(cormat)[ut]], column = rownames(cormat)[col(cormat)[ut]], cor =(cormat)[ut], p = pmat[ut] ) } flattenCorrMatrix(Corr_CT_1$r, Corr_CT_1$P) #Tabla con codificacion simbolica symnum(Corr_CT, abbr.colnames = FALSE) library(corrplot) library(GGally) library(qgraph) # Create a new pdf device pdf("Correlacion_todo.pdf") #Grafica sin numeros corrplot(Corr_CT,type = "upper", order = "hclust",tl.col = "black", tl.srt = 45) #Grafica con numeros y mejor dividida # Insignificant correlations are leaved blank corrplot(Corr_CT_1$r, type="upper", order="hclust", p.mat = Corr_CT_1$P, sig.level = 0.01, insig = "blank") #Correlacion con Qgraph qgraph(cor(Datos_Num_CT)) qgraph(cor(Datos_Num_CT), layout="spring", posCol="darkgreen", negCol="darkmagenta") #Grafico con histogramas y significancia col<- colorRampPalette(c("blue", "white", "red"))(20) heatmap(x = Corr_CT, col = col, symm = TRUE) #Heatmap con "TRUE" or "FALSE" to see how the correlation matrix changes ggcorr(Corr_CT,label = TRUE,label_alpha = FALSE) dev.off() # Close the pdf device pdf("Heatmap.pdf") # scale data to mean=0, sd=1 and convert to matrix Datos_scaled <- as.matrix(scale(Datos_Num)) # create heatmap and don't reorder columns heatmap(Datos_scaled, Colv=F, scale='none') # cluster rows hc.rows <- hclust(dist(Datos_scaled)) plot(hc.rows) # transpose the matrix and cluster columns hc.cols <- hclust(dist(t(Datos_scaled))) plot(hc.cols) # draw heatmap for first cluster heatmap(Datos_scaled[cutree(hc.rows,k=2)==1,], Colv=as.dendrogram(hc.cols), scale='none') # draw heatmap for second cluster heatmap(Datos_scaled[cutree(hc.rows,k=2)==2,], Colv=as.dendrogram(hc.cols), scale='none') dev.off() # Close the pdf device ####################################################### #Principal component analysis #PCA con princomp pdf("PCA_1.pdf") Datos_CT_pca<- princomp(Datos_Num_CT, cor=T) screeplot(Datos_CT_pca) biplot(Datos_CT_pca, col=c("black","red"), cex=c(0.7,0.8)) dev.off() # Close the pdf device pdf("PCA_2.pdf") # en vez de Datos_1[,c(1:51)] puede ser Datos_1_Num Datos.pca <- prcomp(Datos[,c(1:51)], center = TRUE,scale. = TRUE) library(ggbiplot) ggbiplot(Datos.pca,labels=rownames(Datos)) #Se crean caracteres de las columnas con las que se quieren hacer elipses a<-unlist(Datos[52], recursive = TRUE, use.names = TRUE) b<-unlist(Datos[53], recursive = TRUE, use.names = TRUE) ggbiplot(Datos.pca,ellipse=TRUE, labels=rownames(Datos), groups=a) ggbiplot(Datos.pca,ellipse=TRUE, labels=rownames(Datos), groups=b) dev.off() # Close the pdf device pdf("PCA_3.pdf") #PCA con Principal library("psych") #Sin rotacion Datos_CT_pca_unrot <- principal(Datos_Num_CT, nfactors=3, rotate="none") qg_pca_unrot<-qgraph(loadings(Datos_CT_pca_unrot), posCol="darkgreen", layout="spring", negCol="darkmagenta", edge.width=2) qgraph(qg_pca_unrot, layout="spring", posCol="darkgreen", negCol="darkmagenta", edge.width=2) #Con rotacion varimax Datos_CT_pca_rot <- principal(Datos_Num_CT, nfactors=3, rotate="varimax") qg_pca_rot<-qgraph(loadings(Datos_CT_pca_rot), posCol="darkgreen", layout="spring", negCol="darkmagenta", edge.width=2) qgraph(qg_pca_rot, layout="spring", posCol="darkgreen", negCol="darkmagenta", edge.width=2) dev.off() # Close the pdf device pdf("PCA_4.pdf") library("FactoMineR") library("factoextra") Datos_1.pca <- PCA(Datos_1_Num_CT, graph = FALSE) fviz_eig(Datos_1.pca, addlabels = TRUE, ylim = c(0, 50)) fviz_pca_var(Datos_1.pca, col.var = "black") library("corrplot") corrplot(var$cos2, is.corr=FALSE) # Total cos2 of variables on Dim.1 and Dim.2 fviz_cos2(Dat.pca, choice = "var", axes = 1:2) # Color by cos2 values: quality on the factor map fviz_pca_var(Dat.pca, col.var = "cos2", gradient.cols = c("#00AFBB", "#E7B800", "#FC4E07"), repel = TRUE # Avoid text overlapping ) # Change the transparency by cos2 values fviz_pca_var(Dat.pca, alpha.var = "cos2") library("corrplot") corrplot(var$contrib, is.corr=FALSE) # Contributions of variables to PC1 fviz_contrib(Dat.pca, choice = "var", axes = 1, top = 10) # Contributions of variables to PC2 fviz_contrib(Dat.pca, choice = "var", axes = 2, top = 10) fviz_contrib(Dat.pca, choice = "var", axes = 1:2, top = 10) fviz_pca_var(Dat.pca, col.var = "contrib", gradient.cols = c("#00AFBB", "#E7B800", "#FC4E07") ) <file_sep>/PCA_nota.r library(readxl) Datos_1 <- read_excel("D:/TESIS_rev/TESIS_DATA/Datos_estadistica_ordenados_1.xlsx") Datos_1 <- as.data.frame(Datos_1) Datos_1 <- data.frame(Datos_1[,-1], row.names=Datos_1[,1]) Datos_1.pca <- prcomp(Datos_1[,c(1:51)], center = TRUE,scale. = TRUE) summary(Datos_1.pca) library(ggbiplot) ggbiplot(Datos_1.pca) library(ggbiplot) ggbiplot(Datos_1.pca,labels=rownames(Datos_1)) a<-unlist(Datos_1[52], recursive = TRUE, use.names = TRUE) b<-unlist(Datos_1[53], recursive = TRUE, use.names = TRUE) ggbiplot(Datos_1.pca,ellipse=TRUE, labels=rownames(Datos_1), groups=a) ggbiplot(Datos_1.pca,ellipse=TRUE, labels=rownames(Datos_1), groups=b)
82749b56c7976c01c6857af1768961147b076f28
[ "R" ]
2
R
jhoa2708/Estadistica
b7675b11111a654f8b3a62523412d15115c3efff
2c33eb2beb0d8a639698068246c563f561904587